test.cc 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829
  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. session_t create_session(ctx_t ctx, socket_t sock);
  75. void free_session(session_t session);
  76. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  77. time_t timeout_usec, TlsError *err);
  78. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  79. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  80. void shutdown(session_t session, bool graceful);
  81. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  82. namespace impl {
  83. SecTrustSettingsResult
  84. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  85. } // namespace impl
  86. #endif
  87. } // namespace tls
  88. } // namespace httplib
  89. #endif
  90. using namespace std;
  91. using namespace httplib;
  92. const char *HOST = "localhost";
  93. static int get_base_port() {
  94. const char *shard = getenv("GTEST_SHARD_INDEX");
  95. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  96. }
  97. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  98. // New standalone tests MUST use svr.bind_to_any_port() instead.
  99. const int PORT = get_base_port();
  100. const string LONG_QUERY_VALUE = string(25000, '@');
  101. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  102. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  103. const string TOO_LONG_QUERY_URL =
  104. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  105. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  106. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  107. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  108. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  109. return file.name == key;
  110. });
  111. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  112. return *it;
  113. #else
  114. if (it != items.end()) { return *it; }
  115. throw std::runtime_error("invalid multipart form data name error");
  116. #endif
  117. }
  118. static void read_file(const std::string &path, std::string &out) {
  119. std::ifstream fs(path, std::ios_base::binary);
  120. if (!fs) {
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return;
  123. #else
  124. throw std::runtime_error("File not found: " + path);
  125. #endif
  126. }
  127. fs.seekg(0, std::ios_base::end);
  128. auto size = fs.tellg();
  129. fs.seekg(0);
  130. out.resize(static_cast<size_t>(size));
  131. fs.read(&out[0], static_cast<std::streamsize>(size));
  132. }
  133. class UnixSocketTest : public ::testing::Test {
  134. protected:
  135. void TearDown() override { std::remove(pathname_.c_str()); }
  136. void client_GET(const std::string &addr) {
  137. httplib::Client cli{addr};
  138. cli.set_address_family(AF_UNIX);
  139. ASSERT_TRUE(cli.is_valid());
  140. const auto &result = cli.Get(pattern_);
  141. ASSERT_TRUE(result) << "error: " << result.error();
  142. const auto &resp = result.value();
  143. EXPECT_EQ(resp.status, StatusCode::OK_200);
  144. EXPECT_EQ(resp.body, content_);
  145. }
  146. static std::string make_sock_path() {
  147. const char *shard = getenv("GTEST_SHARD_INDEX");
  148. return shard ? std::string("./httplib-server-") + shard + ".sock"
  149. : "./httplib-server.sock";
  150. }
  151. const std::string pathname_{make_sock_path()};
  152. const std::string pattern_{"/hi"};
  153. const std::string content_{"Hello World!"};
  154. };
  155. TEST_F(UnixSocketTest, pathname) {
  156. httplib::Server svr;
  157. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. });
  160. std::thread t{[&] {
  161. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  162. }};
  163. auto se = detail::scope_exit([&] {
  164. svr.stop();
  165. t.join();
  166. ASSERT_FALSE(svr.is_running());
  167. });
  168. svr.wait_until_ready();
  169. ASSERT_TRUE(svr.is_running());
  170. client_GET(pathname_);
  171. // ".//x.sock", which is not taken for a URL
  172. client_GET("./" + pathname_.substr(1));
  173. }
  174. #if defined(__linux__) || \
  175. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  176. TEST_F(UnixSocketTest, PeerPid) {
  177. httplib::Server svr;
  178. std::string remote_port_val;
  179. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  180. res.set_content(content_, "text/plain");
  181. remote_port_val = std::to_string(req.remote_port);
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(pathname_);
  194. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  195. }
  196. #endif
  197. #ifdef __linux__
  198. TEST_F(UnixSocketTest, abstract) {
  199. constexpr char svr_path[]{"\x00httplib-server.sock"};
  200. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  201. httplib::Server svr;
  202. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. client_GET(abstract_addr);
  216. }
  217. #endif
  218. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  219. httplib::Server svr;
  220. std::string received_host_header;
  221. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  222. // Capture the Host header sent by the client
  223. auto host_iter = req.headers.find("Host");
  224. if (host_iter != req.headers.end()) {
  225. received_host_header = host_iter->second;
  226. }
  227. res.set_content(content_, "text/plain");
  228. });
  229. std::thread t{[&] {
  230. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  231. }};
  232. auto se = detail::scope_exit([&] {
  233. svr.stop();
  234. t.join();
  235. ASSERT_FALSE(svr.is_running());
  236. });
  237. svr.wait_until_ready();
  238. ASSERT_TRUE(svr.is_running());
  239. // Test that Host header is automatically set to "localhost" for Unix socket
  240. // connections
  241. httplib::Client cli{pathname_};
  242. cli.set_address_family(AF_UNIX);
  243. ASSERT_TRUE(cli.is_valid());
  244. const auto &result = cli.Get(pattern_);
  245. ASSERT_TRUE(result) << "error: " << result.error();
  246. const auto &resp = result.value();
  247. EXPECT_EQ(resp.status, StatusCode::OK_200);
  248. EXPECT_EQ(resp.body, content_);
  249. // Verify that Host header was automatically set to "localhost"
  250. EXPECT_EQ(received_host_header, "localhost");
  251. }
  252. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  253. // Another socket in the working directory, which a Location can name as
  254. // its host
  255. const auto other_path = "other-" + pathname_.substr(2);
  256. httplib::Server svr;
  257. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  258. // An absolute Location naming the Host this client sends
  259. res.set_redirect("http://localhost" + pattern_);
  260. });
  261. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  262. res.set_redirect("http://" + other_path + pattern_);
  263. });
  264. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  265. res.set_redirect("http://mapped.test" + pattern_);
  266. });
  267. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  268. res.set_header("X-Auth", req.get_header_value("Authorization"));
  269. res.set_content(content_, "text/plain");
  270. });
  271. httplib::Server other;
  272. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  273. res.set_content("other", "text/plain");
  274. });
  275. std::thread t{[&] {
  276. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  277. }};
  278. std::thread t2{[&] {
  279. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  280. }};
  281. auto se = detail::scope_exit([&] {
  282. svr.stop();
  283. other.stop();
  284. t.join();
  285. t2.join();
  286. std::remove(other_path.c_str());
  287. });
  288. svr.wait_until_ready();
  289. other.wait_until_ready();
  290. httplib::Client cli{pathname_};
  291. cli.set_address_family(AF_UNIX);
  292. cli.set_follow_location(true);
  293. cli.set_bearer_token_auth("token");
  294. // Another host: the same socket, without the credentials
  295. auto res = cli.Get("/cross");
  296. ASSERT_TRUE(res) << "error: " << res.error();
  297. EXPECT_EQ(StatusCode::OK_200, res->status);
  298. EXPECT_EQ(content_, res->body);
  299. EXPECT_EQ("", res->get_header_value("X-Auth"));
  300. // localhost is this client's own host
  301. res = cli.Get("/redirect");
  302. ASSERT_TRUE(res) << "error: " << res.error();
  303. EXPECT_EQ(StatusCode::OK_200, res->status);
  304. EXPECT_EQ(content_, res->body);
  305. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  306. // A host the caller mapped to a socket goes there
  307. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  308. res = cli.Get("/mapped");
  309. ASSERT_TRUE(res) << "error: " << res.error();
  310. EXPECT_EQ(StatusCode::OK_200, res->status);
  311. EXPECT_EQ("other", res->body);
  312. }
  313. #ifndef _WIN32
  314. TEST(SocketStream, wait_writable_UNIX) {
  315. int fds[2];
  316. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  317. const auto asSocketStream = [&](socket_t fd,
  318. std::function<bool(Stream &)> func) {
  319. return detail::process_client_socket(
  320. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  321. };
  322. asSocketStream(fds[0], [&](Stream &s0) {
  323. EXPECT_EQ(s0.socket(), fds[0]);
  324. EXPECT_TRUE(s0.wait_writable());
  325. EXPECT_TRUE(s0.is_peer_alive());
  326. EXPECT_EQ(0, close(fds[1]));
  327. EXPECT_FALSE(s0.is_peer_alive());
  328. return true;
  329. });
  330. EXPECT_EQ(0, close(fds[0]));
  331. }
  332. TEST(SocketStream, wait_writable_INET) {
  333. sockaddr_in addr;
  334. memset(&addr, 0, sizeof(addr));
  335. addr.sin_family = AF_INET;
  336. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  337. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  338. int disconnected_svr_sock = -1;
  339. std::thread svr{[&] {
  340. const int s = socket(AF_INET, SOCK_STREAM, 0);
  341. ASSERT_LE(0, s);
  342. // PORT + 1 is shared with the SSL redirect tests and with
  343. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  344. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  345. // because that happens on a worker thread the ASSERT does not stop the
  346. // test: it runs on and fails at the disconnected_svr_sock check instead.
  347. default_socket_options(s);
  348. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  349. ASSERT_EQ(0, listen(s, 1));
  350. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  351. ASSERT_EQ(0, close(s));
  352. }};
  353. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  354. std::thread cli{[&] {
  355. const int s = socket(AF_INET, SOCK_STREAM, 0);
  356. ASSERT_LE(0, s);
  357. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  358. ASSERT_EQ(0, close(s));
  359. }};
  360. cli.join();
  361. svr.join();
  362. ASSERT_NE(disconnected_svr_sock, -1);
  363. const auto asSocketStream = [&](socket_t fd,
  364. std::function<bool(Stream &)> func) {
  365. return detail::process_client_socket(
  366. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  367. };
  368. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  369. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  370. // wait_writable() returns true because select_write() only checks if the
  371. // send buffer has space. Peer disconnection is detected later by send().
  372. EXPECT_TRUE(ss.wait_writable());
  373. return true;
  374. });
  375. ASSERT_EQ(0, close(disconnected_svr_sock));
  376. }
  377. #endif // #ifndef _WIN32
  378. TEST(SetSocketOptTest, TcpNoDelay) {
  379. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  380. ASSERT_NE(sock, INVALID_SOCKET);
  381. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  382. int val = 0;
  383. socklen_t len = sizeof(val);
  384. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  385. reinterpret_cast<char *>(&val), &len));
  386. EXPECT_NE(val, 0);
  387. detail::close_socket(sock);
  388. }
  389. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  390. // accept() reports failures through WSAGetLastError() on Windows and through
  391. // errno everywhere else. Asking the wrong one is what made the accept loop
  392. // treat every recoverable failure as fatal on Windows.
  393. struct Classification {
  394. bool resource;
  395. bool transient;
  396. };
  397. auto classify = [](int err) {
  398. #ifdef _WIN32
  399. WSASetLastError(err);
  400. #else
  401. errno = err;
  402. #endif
  403. // Read both before asserting: an assertion may clobber the error slot.
  404. Classification c;
  405. c.resource = detail::is_accept_resource_error();
  406. c.transient = detail::is_accept_transient_error();
  407. return c;
  408. };
  409. #ifdef _WIN32
  410. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  411. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  412. WSAECONNRESET, WSAECONNABORTED};
  413. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  414. #else
  415. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  416. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  417. ECONNABORTED};
  418. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  419. #endif
  420. for (auto err : resource_errors) {
  421. const auto c = classify(err);
  422. EXPECT_TRUE(c.resource) << "error " << err;
  423. EXPECT_FALSE(c.transient) << "error " << err;
  424. }
  425. for (auto err : transient_errors) {
  426. const auto c = classify(err);
  427. EXPECT_TRUE(c.transient) << "error " << err;
  428. EXPECT_FALSE(c.resource) << "error " << err;
  429. }
  430. for (auto err : fatal_errors) {
  431. const auto c = classify(err);
  432. EXPECT_FALSE(c.resource) << "error " << err;
  433. EXPECT_FALSE(c.transient) << "error " << err;
  434. }
  435. #ifdef _WIN32
  436. WSASetLastError(0);
  437. #else
  438. errno = 0;
  439. #endif
  440. }
  441. TEST(ClientTest, MoveConstructible) {
  442. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  443. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  444. }
  445. TEST(ClientTest, MoveAssignable) {
  446. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  447. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  448. }
  449. #ifdef _WIN32
  450. TEST(StartupTest, WSAStartup) {
  451. WSADATA wsaData;
  452. int ret = WSAStartup(0x0002, &wsaData);
  453. ASSERT_EQ(0, ret);
  454. }
  455. #endif
  456. TEST(DecodePathTest, PercentCharacter) {
  457. EXPECT_EQ(
  458. decode_path_component(
  459. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  460. U8("descrip=Gastos áéíóúñÑ 6"));
  461. }
  462. TEST(DecodePathTest, PercentCharacterNUL) {
  463. string expected;
  464. expected.push_back('x');
  465. expected.push_back('\0');
  466. expected.push_back('x');
  467. EXPECT_EQ(decode_path_component("x%00x"), expected);
  468. }
  469. TEST(DecodePathTest, UnicodeEncoding) {
  470. // %u0041 = 'A' (1-byte UTF-8)
  471. EXPECT_EQ("A", decode_path_component("%u0041"));
  472. // %u00E9 = 'é' (2-byte UTF-8)
  473. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  474. // %u3042 = 'あ' (3-byte UTF-8)
  475. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  476. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  477. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  478. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  479. // neighbours)
  480. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  481. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  482. }
  483. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  484. // A sign or whitespace inside the two-character escape window must not be
  485. // accepted as a valid percent-encoding; the sequence is passed through
  486. // literally, matching decode_uri_component / decode_path_component.
  487. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  488. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  489. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  490. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  491. // Well-formed escapes still decode.
  492. EXPECT_EQ("-", decode_query_component("%2D", false));
  493. EXPECT_EQ("A", decode_query_component("%41", false));
  494. }
  495. TEST(SanitizeFilenameTest, VariousPatterns) {
  496. // Path traversal
  497. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  498. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  499. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  500. // Normal and edge cases
  501. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  502. EXPECT_EQ("filename.txt",
  503. httplib::sanitize_filename("/path/to/filename.txt"));
  504. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  505. EXPECT_EQ("", httplib::sanitize_filename(".."));
  506. EXPECT_EQ("", httplib::sanitize_filename(""));
  507. // Null bytes stripped
  508. EXPECT_EQ("safe.txt",
  509. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  510. // Whitespace-only rejected
  511. EXPECT_EQ("", httplib::sanitize_filename(" "));
  512. }
  513. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  514. // before it is dropped; anywhere else it is an ordinary file name character.
  515. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  516. #ifdef _WIN32
  517. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  518. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  519. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  520. #else
  521. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  522. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  523. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  524. #endif
  525. }
  526. // Forward declaration (see the base64_encode note below): split builds move the
  527. // definition into httplib.cc, so re-declaring it here lets the test link.
  528. namespace httplib {
  529. namespace detail {
  530. bool is_chunked_transfer_encoding(const Headers &headers);
  531. } // namespace detail
  532. } // namespace httplib
  533. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  534. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  535. auto make = [](std::initializer_list<const char *> lines) {
  536. Headers h;
  537. for (auto te : lines) {
  538. if (te) { h.emplace("Transfer-Encoding", te); }
  539. }
  540. return h;
  541. };
  542. // Sole coding, matched case-insensitively.
  543. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  544. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  545. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  546. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  547. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  548. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  549. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  550. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  551. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  552. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  553. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  554. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  555. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  556. // were received, into one list. Headers preserves that order, so the answer
  557. // is decided by the last coding of the last line and the order the lines
  558. // arrived in is significant.
  559. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  560. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  561. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  562. // The split can fall anywhere in the list.
  563. EXPECT_TRUE(
  564. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  565. EXPECT_FALSE(
  566. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  567. // A trailing line naming no coding leaves the list ending in nothing, so it
  568. // must not inherit the chunked from the line before it.
  569. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  570. }
  571. // Forward declarations (see the base64_encode note below).
  572. namespace httplib {
  573. namespace detail {
  574. bool parse_status_line(const char *line, std::string &version, int &status,
  575. std::string &reason);
  576. std::string file_extension(const std::string &path);
  577. std::string
  578. find_content_type(const std::string &path,
  579. const std::map<std::string, std::string> &user_data,
  580. const std::string &default_content_type);
  581. bool can_compress_content_type(const std::string &content_type);
  582. bool is_prohibited_header_name(const std::string &name);
  583. bool is_valid_path(const std::string &path);
  584. #ifdef CPPHTTPLIB_SSL_ENABLED
  585. bool match_hostname(const std::string &pattern, const std::string &hostname);
  586. #endif
  587. } // namespace detail
  588. } // namespace httplib
  589. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  590. struct {
  591. const char *line;
  592. const char *version;
  593. int status;
  594. const char *reason;
  595. } cases[] = {
  596. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  597. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  598. // The reason phrase may be empty, or left out along with its space.
  599. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  600. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  601. };
  602. for (const auto &c : cases) {
  603. std::string version;
  604. int status = 0;
  605. std::string reason = "unset";
  606. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  607. << c.line;
  608. EXPECT_EQ(c.version, version);
  609. EXPECT_EQ(c.status, status);
  610. EXPECT_EQ(c.reason, reason);
  611. }
  612. }
  613. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  614. const char *lines[] = {
  615. "HTTP/2 200 OK\r\n",
  616. "HTTP/1.2 200 OK\r\n",
  617. "HTTP/1.1 20 OK\r\n",
  618. "HTTP/1.1 2000 OK\r\n",
  619. "HTTP/1.1 2x0 OK\r\n",
  620. "HTTP/1.1 200 OK\r\n",
  621. "HTTP/1.1 200OK\r\n",
  622. "HTTP/1.1 200 O\rK\r\n",
  623. "HTTP/1.1 200 OK",
  624. "HTTP/1.1 200 OK\r\nX",
  625. "",
  626. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  627. "HTTP/1.1 200 OK\n",
  628. #endif
  629. };
  630. for (auto line : lines) {
  631. std::string version;
  632. int status = 0;
  633. std::string reason;
  634. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  635. << line;
  636. }
  637. }
  638. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  639. // Long enough to overflow the stack when matched with std::regex.
  640. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  641. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  642. std::string version;
  643. int status = 0;
  644. std::string reason;
  645. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  646. EXPECT_EQ(200, status);
  647. EXPECT_EQ(long_reason, reason);
  648. }
  649. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  650. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  651. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  652. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  653. EXPECT_EQ("", detail::file_extension("noext"));
  654. EXPECT_EQ("", detail::file_extension("a."));
  655. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  656. EXPECT_EQ("", detail::file_extension("a.b-c"));
  657. // Long enough to overflow the stack when matched with std::regex.
  658. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  659. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  660. }
  661. #ifdef CPPHTTPLIB_SSL_ENABLED
  662. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  663. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  664. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  665. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  666. // A wildcard needs two labels after it, in the leftmost label only
  667. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  668. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  669. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  670. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  671. EXPECT_FALSE(
  672. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  673. // No name may have an empty label
  674. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  675. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  676. }
  677. #endif
  678. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  679. detail::case_ignore::hash hash;
  680. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  681. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  682. // Long enough to overflow the stack if hashed one call per character.
  683. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  684. }
  685. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  686. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  687. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  688. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  689. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  690. // Same 26-bit hash as html, svg and js.
  691. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  692. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  693. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  694. }
  695. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  696. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  697. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  698. }
  699. }
  700. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  701. // name anywhere else.
  702. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  703. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  704. #ifdef _WIN32
  705. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  706. #else
  707. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  708. #endif
  709. }
  710. }
  711. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  712. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  713. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  714. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  715. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  716. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  717. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  718. // Same 26-bit hash as application/json.
  719. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  720. }
  721. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  722. Request req;
  723. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  724. EXPECT_TRUE(req.is_multipart_form_data());
  725. std::string boundary;
  726. EXPECT_TRUE(detail::parse_multipart_boundary(
  727. req.get_header_value("Content-Type"), boundary));
  728. EXPECT_EQ("x", boundary);
  729. }
  730. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  731. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  732. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  733. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  734. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  735. // Same 26-bit hash as REMOTE_ADDR.
  736. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  737. }
  738. // Forward declaration: in split builds split.py strips `inline` and moves the
  739. // definition into httplib.cc, so detail::base64_encode is not visible from the
  740. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  741. // in both header-only and split builds.
  742. namespace httplib {
  743. namespace detail {
  744. std::string base64_encode(const std::string &in);
  745. } // namespace detail
  746. } // namespace httplib
  747. TEST(Base64EncodeTest, KnownAnswers) {
  748. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  749. // where the accumulator's top bit is already set before the next shift.
  750. EXPECT_EQ("", detail::base64_encode(""));
  751. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  752. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  753. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  754. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  755. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  756. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  757. // High bytes keep the top bit set across several rounds.
  758. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  759. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  760. }
  761. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  762. string unescapedCharacters = "-_.!~*'()";
  763. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  764. }
  765. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  766. string reservedCharacters = ";,/?:@&=+$";
  767. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  768. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  769. }
  770. TEST(ClientQueryOrder, PreserveOrder) {
  771. // This test reproduces Issue #2259: client may reorder query parameters
  772. // when sending a GET request. The expected behavior is that the client
  773. // preserves the original query string order when the caller supplied it
  774. // as part of the path.
  775. Server svr;
  776. svr.Get("/", [&](const Request &req, Response &res) {
  777. // Echo back the raw target so the test can assert ordering
  778. res.set_content(req.target, "text/plain");
  779. });
  780. std::thread t{[&] { svr.listen(HOST, PORT); }};
  781. auto se = detail::scope_exit([&] {
  782. svr.stop();
  783. t.join();
  784. ASSERT_FALSE(svr.is_running());
  785. });
  786. svr.wait_until_ready();
  787. Client cli(HOST, PORT);
  788. ASSERT_TRUE(cli.is_valid());
  789. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  790. auto res = cli.Get(original);
  791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  792. // Expect the echoed target to exactly match the original path (order
  793. // preserved)
  794. EXPECT_EQ(res->body, original);
  795. }
  796. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  797. string chineseCharacters = U8("中国語");
  798. string russianCharacters = U8("дом");
  799. string brazilianCharacters = U8("óculos");
  800. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  801. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  802. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  803. "%D0%B4%D0%BE%D0%BC");
  804. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  805. }
  806. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  807. string unescapedCharacters = "-_.!~*'()";
  808. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  809. }
  810. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  811. string reservedCharacters = ";,/?:@&=+$";
  812. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  813. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  814. }
  815. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  816. string chineseCharacters = U8("中国語");
  817. string russianCharacters = U8("дом");
  818. string brazilianCharacters = U8("óculos");
  819. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  820. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  821. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  822. "%D0%B4%D0%BE%D0%BC");
  823. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  824. }
  825. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  826. // Issue #2082 use case: encoding path component with ampersand
  827. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  828. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  829. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  830. }
  831. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  832. string unescapedCharacters = "-_.!~*'()";
  833. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  834. }
  835. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  836. string reservedCharacters = ";,/?:@&=+$#";
  837. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  838. }
  839. TEST(EncodeUriTest, TestUTF8Characters) {
  840. string chineseCharacters = U8("中国語");
  841. string russianCharacters = U8("дом");
  842. string brazilianCharacters = U8("óculos");
  843. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  844. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  845. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  846. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  847. }
  848. TEST(EncodeUriTest, TestCompleteUri) {
  849. string uri =
  850. "https://example.com/path/to/resource?query=value&param=test#fragment";
  851. EXPECT_EQ(
  852. httplib::encode_uri(uri),
  853. "https://example.com/path/to/resource?query=value&param=test#fragment");
  854. }
  855. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  856. string uri =
  857. "https://example.com/path with spaces/file name.html?q=hello world";
  858. EXPECT_EQ(httplib::encode_uri(uri),
  859. "https://example.com/path%20with%20spaces/"
  860. "file%20name.html?q=hello%20world");
  861. }
  862. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  863. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  864. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  865. }
  866. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  867. string unescapedCharacters = "-_.!~*'()";
  868. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  869. }
  870. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  871. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  872. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  873. string encodedBrazilian = "%C3%B3culos";
  874. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  875. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  876. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  877. }
  878. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  879. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  880. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  881. "Piri Tommy Villiers - on & on");
  882. }
  883. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  884. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  885. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  886. }
  887. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  888. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  889. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  890. }
  891. TEST(DecodeUriTest, TestUTF8Characters) {
  892. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  893. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  894. string encodedBrazilian = "%C3%B3culos";
  895. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  896. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  897. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  898. }
  899. TEST(DecodeUriTest, TestCompleteUri) {
  900. string encodedUri = "https://example.com/path%20with%20spaces/"
  901. "file%20name.html?q=hello%20world";
  902. EXPECT_EQ(
  903. httplib::decode_uri(encodedUri),
  904. "https://example.com/path with spaces/file name.html?q=hello world");
  905. }
  906. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  907. string original =
  908. "https://example.com/path with spaces/file name.html?q=hello world";
  909. string encoded = httplib::encode_uri(original);
  910. string decoded = httplib::decode_uri(encoded);
  911. EXPECT_EQ(decoded, original);
  912. }
  913. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  914. // decode_uri is the inverse of encode_uri: an escaped reserved character
  915. // stays encoded so it is not promoted into a real delimiter, while
  916. // non-reserved escapes still decode (like JS decodeURI).
  917. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  918. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  919. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  920. "%3F%3A%40%26%3D%2B%24%2C%3B");
  921. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  922. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  923. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  924. "http://example.com/a%2Fb");
  925. // decode_uri_component still decodes the reserved character.
  926. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  927. }
  928. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  929. string original = "Piri Tommy Villiers - on & on";
  930. string encoded = httplib::encode_uri_component(original);
  931. string decoded = httplib::decode_uri_component(encoded);
  932. EXPECT_EQ(decoded, original);
  933. }
  934. TEST(TrimTests, TrimStringTests) {
  935. EXPECT_EQ("abc", detail::trim_copy("abc"));
  936. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  937. EXPECT_TRUE(detail::trim_copy("").empty());
  938. }
  939. TEST(AsciiTest, LocaleIndependentClassification) {
  940. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  941. // which consult the global C locale: std::isalnum(0xC5) can return true
  942. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  943. // helpers must classify every byte by the ASCII grammar alone.
  944. for (int i = 0; i < 256; i++) {
  945. auto c = static_cast<char>(i);
  946. auto is_digit = i >= '0' && i <= '9';
  947. auto is_upper = i >= 'A' && i <= 'Z';
  948. auto is_lower = i >= 'a' && i <= 'z';
  949. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  950. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  951. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  952. << "byte " << i;
  953. }
  954. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  955. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  956. // Non-ASCII bytes must be percent-encoded, never passed through as
  957. // alphanumeric.
  958. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  959. }
  960. TEST(FromCharsTest, Double) {
  961. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  962. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  963. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  964. auto parse = [](const std::string &s, double &v) {
  965. return detail::from_chars(s.data(), s.data() + s.size(), v);
  966. };
  967. double v = -1.0;
  968. // Representative quality values.
  969. EXPECT_EQ(parse("0", v).ec, std::errc{});
  970. EXPECT_DOUBLE_EQ(v, 0.0);
  971. EXPECT_EQ(parse("1", v).ec, std::errc{});
  972. EXPECT_DOUBLE_EQ(v, 1.0);
  973. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  974. EXPECT_DOUBLE_EQ(v, 0.8);
  975. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  976. EXPECT_DOUBLE_EQ(v, 0.001);
  977. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  978. EXPECT_DOUBLE_EQ(v, 1.0);
  979. // A missing integer or fractional part is tolerated.
  980. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  981. EXPECT_DOUBLE_EQ(v, 0.5);
  982. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  983. EXPECT_DOUBLE_EQ(v, 5.0);
  984. // Values outside [0, 1] still parse; the caller range-checks them.
  985. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  986. EXPECT_DOUBLE_EQ(v, 123.456);
  987. // Stops at the first byte that is not part of the number and reports where.
  988. std::string trailing = "0.9, text/html";
  989. auto r = parse(trailing, v);
  990. EXPECT_EQ(r.ec, std::errc{});
  991. EXPECT_DOUBLE_EQ(v, 0.9);
  992. EXPECT_EQ(*r.ptr, ',');
  993. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  994. // outright, and an 'e'/'E' simply ends the number.
  995. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  996. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  997. std::string exp_input = "1.5e3";
  998. r = parse(exp_input, v);
  999. EXPECT_EQ(r.ec, std::errc{});
  1000. EXPECT_DOUBLE_EQ(v, 1.5);
  1001. EXPECT_EQ(*r.ptr, 'e');
  1002. // Invalid inputs.
  1003. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1004. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1005. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1006. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1007. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1008. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1009. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1010. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1011. std::errc{});
  1012. EXPECT_DOUBLE_EQ(v, 0.0);
  1013. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1014. std::errc{});
  1015. EXPECT_GE(v, 0.0);
  1016. EXPECT_LE(v, 1.0);
  1017. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1018. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1019. }
  1020. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1021. // Simple case without quality values
  1022. std::vector<std::string> result1;
  1023. EXPECT_TRUE(detail::parse_accept_header(
  1024. "text/html,application/json,text/plain", result1));
  1025. EXPECT_EQ(result1.size(), 3U);
  1026. EXPECT_EQ(result1[0], "text/html");
  1027. EXPECT_EQ(result1[1], "application/json");
  1028. EXPECT_EQ(result1[2], "text/plain");
  1029. // With quality values
  1030. std::vector<std::string> result2;
  1031. EXPECT_TRUE(detail::parse_accept_header(
  1032. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1033. EXPECT_EQ(result2.size(), 3U);
  1034. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1035. EXPECT_EQ(result2[1], "text/html");
  1036. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1037. }
  1038. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1039. // Mixed with and without quality values
  1040. std::vector<std::string> result;
  1041. EXPECT_TRUE(detail::parse_accept_header(
  1042. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1043. EXPECT_EQ(result.size(), 3U);
  1044. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1045. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1046. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1047. }
  1048. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1049. // Empty header
  1050. std::vector<std::string> empty_result;
  1051. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1052. EXPECT_TRUE(empty_result.empty());
  1053. // Single type
  1054. std::vector<std::string> single_result;
  1055. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1056. EXPECT_EQ(single_result.size(), 1U);
  1057. EXPECT_EQ(single_result[0], "application/json");
  1058. // Wildcard types
  1059. std::vector<std::string> wildcard_result;
  1060. EXPECT_TRUE(detail::parse_accept_header(
  1061. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1062. EXPECT_EQ(wildcard_result.size(), 3U);
  1063. EXPECT_EQ(wildcard_result[0], "application/json");
  1064. EXPECT_EQ(wildcard_result[1], "text/*");
  1065. EXPECT_EQ(wildcard_result[2], "*/*");
  1066. }
  1067. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1068. // Common browser Accept header
  1069. std::vector<std::string> browser_result;
  1070. EXPECT_TRUE(
  1071. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1072. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1073. browser_result));
  1074. EXPECT_EQ(browser_result.size(), 6U);
  1075. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1076. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1077. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1078. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1079. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1080. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1081. // API client header
  1082. std::vector<std::string> api_result;
  1083. EXPECT_TRUE(detail::parse_accept_header(
  1084. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1085. api_result));
  1086. EXPECT_EQ(api_result.size(), 3U);
  1087. EXPECT_EQ(api_result[0], "application/json");
  1088. EXPECT_EQ(api_result[1], "application/xml");
  1089. EXPECT_EQ(api_result[2], "text/plain");
  1090. }
  1091. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1092. // Quality value with 3 decimal places
  1093. std::vector<std::string> decimal_result;
  1094. EXPECT_TRUE(detail::parse_accept_header(
  1095. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1096. EXPECT_EQ(decimal_result.size(), 2U);
  1097. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1098. EXPECT_EQ(decimal_result[1], "text/html");
  1099. // Zero quality (should still be included but with lowest priority)
  1100. std::vector<std::string> zero_q_result;
  1101. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1102. zero_q_result));
  1103. EXPECT_EQ(zero_q_result.size(), 2U);
  1104. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1105. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1106. // No spaces around commas
  1107. std::vector<std::string> no_space_result;
  1108. EXPECT_TRUE(detail::parse_accept_header(
  1109. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1110. no_space_result));
  1111. EXPECT_EQ(no_space_result.size(), 3U);
  1112. EXPECT_EQ(no_space_result[0], "text/html");
  1113. EXPECT_EQ(no_space_result[1], "application/json");
  1114. EXPECT_EQ(no_space_result[2], "text/plain");
  1115. }
  1116. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1117. // Quality values always use '.' as the decimal separator, so parsing must
  1118. // not depend on the process locale. An embedding application may have
  1119. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1120. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1121. std::string saved = cur ? cur : "C";
  1122. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1123. "fr_FR.UTF-8"};
  1124. bool switched = false;
  1125. for (const auto loc : comma_locales) {
  1126. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1127. std::localeconv()->decimal_point[0] == ',') {
  1128. switched = true;
  1129. break;
  1130. }
  1131. }
  1132. if (!switched) {
  1133. std::setlocale(LC_NUMERIC, saved.c_str());
  1134. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1135. }
  1136. // The higher-weighted type appears later in the list, so a correct parse
  1137. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1138. // sensitive parse reads both weights as 0 and leaves the original order.
  1139. std::vector<std::string> result;
  1140. EXPECT_TRUE(detail::parse_accept_header(
  1141. "application/json;q=0.1,text/html;q=0.9", result));
  1142. ASSERT_EQ(result.size(), 2U);
  1143. EXPECT_EQ(result[0], "text/html");
  1144. EXPECT_EQ(result[1], "application/json");
  1145. std::setlocale(LC_NUMERIC, saved.c_str());
  1146. }
  1147. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1148. std::vector<std::string> result;
  1149. // Invalid quality value (> 1.0)
  1150. EXPECT_FALSE(
  1151. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1152. // Invalid quality value (< 0.0)
  1153. EXPECT_FALSE(
  1154. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1155. // Invalid quality value (not a number)
  1156. EXPECT_FALSE(detail::parse_accept_header(
  1157. "text/html;q=invalid,application/json", result));
  1158. // A valid numeric prefix does not make the entire quality value valid.
  1159. EXPECT_FALSE(detail::parse_accept_header(
  1160. "text/html;q=0.5junk,application/json", result));
  1161. // Empty quality value
  1162. EXPECT_FALSE(
  1163. detail::parse_accept_header("text/html;q=,application/json", result));
  1164. // Invalid media type format (no slash and not wildcard)
  1165. EXPECT_FALSE(
  1166. detail::parse_accept_header("invalidtype,application/json", result));
  1167. // Valid cases should still work
  1168. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1169. EXPECT_EQ(result.size(), 1U);
  1170. EXPECT_EQ(result[0], "*/*");
  1171. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1172. EXPECT_EQ(result.size(), 1U);
  1173. EXPECT_EQ(result[0], "*");
  1174. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1175. EXPECT_EQ(result.size(), 1U);
  1176. EXPECT_EQ(result[0], "text/*");
  1177. }
  1178. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1179. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1180. // and must not be answered with 400 Bad Request.
  1181. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1182. struct {
  1183. const char *value;
  1184. std::vector<std::string> expected;
  1185. } cases[] = {
  1186. {",application/json", {"application/json"}},
  1187. {"text/html,", {"text/html"}},
  1188. {"text/html,,*/*", {"text/html", "*/*"}},
  1189. // An empty element may be spelled with whitespace in it
  1190. {"text/html, , application/json", {"text/html", "application/json"}},
  1191. // Nothing but empty elements is an empty list, which means the same
  1192. // thing as no Accept header at all
  1193. {",,,", {}},
  1194. // Quality values still apply across ignored empty elements
  1195. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1196. };
  1197. for (const auto &c : cases) {
  1198. std::vector<std::string> result;
  1199. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1200. << "value: " << c.value;
  1201. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1202. }
  1203. // An invalid entry is still rejected when empty elements surround it
  1204. std::vector<std::string> result;
  1205. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1206. }
  1207. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1208. // or ';' inside one does not end the list element or the parameter. Section
  1209. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1210. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1211. struct {
  1212. const char *value;
  1213. std::vector<std::string> expected;
  1214. } cases[] = {
  1215. {"text/html;profile=\"a,b\",application/json",
  1216. {"text/html", "application/json"}},
  1217. // A "q=" inside a quoted value is not the weight
  1218. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1219. {"text/html", "application/json"}},
  1220. // The weight after a quoted value still applies
  1221. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1222. {"application/json", "text/html"}},
  1223. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1224. {"application/json", "text/html"}},
  1225. {"text/html;profile=\"a\\\"b\",application/json",
  1226. {"text/html", "application/json"}},
  1227. // An escaped backslash does not escape the '"' after it
  1228. {"text/html;profile=\"a\\\\\",application/json",
  1229. {"text/html", "application/json"}},
  1230. };
  1231. for (const auto &c : cases) {
  1232. std::vector<std::string> result;
  1233. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1234. << "value: " << c.value;
  1235. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1236. }
  1237. }
  1238. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1239. Server svr;
  1240. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1241. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1242. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1243. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1244. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1245. res.set_content("ok", "text/plain");
  1246. });
  1247. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1248. EXPECT_TRUE(false);
  1249. res.set_content("bad request", "text/plain");
  1250. });
  1251. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1252. auto se = detail::scope_exit([&] {
  1253. svr.stop();
  1254. listen_thread.join();
  1255. ASSERT_FALSE(svr.is_running());
  1256. });
  1257. svr.wait_until_ready();
  1258. Client cli("localhost", PORT);
  1259. {
  1260. auto res = cli.Get(
  1261. "/accept_ok",
  1262. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1264. EXPECT_EQ(StatusCode::OK_200, res->status);
  1265. }
  1266. {
  1267. auto res = cli.Get("/accept_bad_request",
  1268. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1270. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1271. }
  1272. }
  1273. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1274. Server svr;
  1275. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1276. res.set_content("ok", "text/plain");
  1277. });
  1278. std::atomic<int> start_count{0};
  1279. std::atomic<bool> running_when_called{false};
  1280. svr.set_start_handler([&]() {
  1281. running_when_called = svr.is_running();
  1282. start_count++;
  1283. });
  1284. auto port = svr.bind_to_any_port(HOST);
  1285. std::thread t([&]() { svr.listen_after_bind(); });
  1286. auto se = detail::scope_exit([&] {
  1287. svr.stop();
  1288. t.join();
  1289. ASSERT_FALSE(svr.is_running());
  1290. });
  1291. svr.wait_until_ready();
  1292. // A successful request proves the accept loop is running, which the start
  1293. // handler precedes; so by now the handler must have run exactly once.
  1294. Client cli(HOST, port);
  1295. cli.set_connection_timeout(std::chrono::seconds(5));
  1296. auto res = cli.Get("/");
  1297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1298. EXPECT_EQ(StatusCode::OK_200, res->status);
  1299. EXPECT_EQ(1, start_count.load());
  1300. EXPECT_TRUE(running_when_called.load());
  1301. }
  1302. TEST(DivideTest, DivideStringTests) {
  1303. auto divide = [](const std::string &str, char d) {
  1304. std::string lhs;
  1305. std::string rhs;
  1306. detail::divide(str, d,
  1307. [&](const char *lhs_data, std::size_t lhs_size,
  1308. const char *rhs_data, std::size_t rhs_size) {
  1309. lhs.assign(lhs_data, lhs_size);
  1310. rhs.assign(rhs_data, rhs_size);
  1311. });
  1312. return std::make_pair(std::move(lhs), std::move(rhs));
  1313. };
  1314. {
  1315. const auto res = divide("", '=');
  1316. EXPECT_EQ(res.first, "");
  1317. EXPECT_EQ(res.second, "");
  1318. }
  1319. {
  1320. const auto res = divide("=", '=');
  1321. EXPECT_EQ(res.first, "");
  1322. EXPECT_EQ(res.second, "");
  1323. }
  1324. {
  1325. const auto res = divide(" ", '=');
  1326. EXPECT_EQ(res.first, " ");
  1327. EXPECT_EQ(res.second, "");
  1328. }
  1329. {
  1330. const auto res = divide("a", '=');
  1331. EXPECT_EQ(res.first, "a");
  1332. EXPECT_EQ(res.second, "");
  1333. }
  1334. {
  1335. const auto res = divide("a=", '=');
  1336. EXPECT_EQ(res.first, "a");
  1337. EXPECT_EQ(res.second, "");
  1338. }
  1339. {
  1340. const auto res = divide("=b", '=');
  1341. EXPECT_EQ(res.first, "");
  1342. EXPECT_EQ(res.second, "b");
  1343. }
  1344. {
  1345. const auto res = divide("a=b", '=');
  1346. EXPECT_EQ(res.first, "a");
  1347. EXPECT_EQ(res.second, "b");
  1348. }
  1349. {
  1350. const auto res = divide("a=b=", '=');
  1351. EXPECT_EQ(res.first, "a");
  1352. EXPECT_EQ(res.second, "b=");
  1353. }
  1354. {
  1355. const auto res = divide("a=b=c", '=');
  1356. EXPECT_EQ(res.first, "a");
  1357. EXPECT_EQ(res.second, "b=c");
  1358. }
  1359. }
  1360. TEST(SplitTest, ParseQueryString) {
  1361. string s = "key1=val1&key2=val2&key3=val3";
  1362. Params dic;
  1363. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1364. [&](const char *b, const char *e) {
  1365. string key, val;
  1366. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1367. if (key.empty()) {
  1368. key.assign(b2, e2);
  1369. } else {
  1370. val.assign(b2, e2);
  1371. }
  1372. });
  1373. dic.emplace(key, val);
  1374. });
  1375. EXPECT_EQ("val1", dic.find("key1")->second);
  1376. EXPECT_EQ("val2", dic.find("key2")->second);
  1377. EXPECT_EQ("val3", dic.find("key3")->second);
  1378. }
  1379. TEST(SplitTest, ParseInvalidQueryTests) {
  1380. {
  1381. string s = " ";
  1382. Params dict;
  1383. detail::parse_query_text(s, dict);
  1384. EXPECT_TRUE(dict.empty());
  1385. }
  1386. {
  1387. string s = " = =";
  1388. Params dict;
  1389. detail::parse_query_text(s, dict);
  1390. EXPECT_TRUE(dict.empty());
  1391. }
  1392. }
  1393. TEST(ParseQueryTest, ParseQueryString) {
  1394. {
  1395. std::string s = "key1=val1&key2=val2&key3=val3";
  1396. Params dic;
  1397. detail::parse_query_text(s, dic);
  1398. EXPECT_EQ("val1", dic.find("key1")->second);
  1399. EXPECT_EQ("val2", dic.find("key2")->second);
  1400. EXPECT_EQ("val3", dic.find("key3")->second);
  1401. }
  1402. {
  1403. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1404. Params dic;
  1405. detail::parse_query_text(s, dic);
  1406. EXPECT_EQ("", dic.find("key1")->second);
  1407. EXPECT_EQ("val1", dic.find("key2")->second);
  1408. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1409. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1410. }
  1411. }
  1412. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1413. Params dic;
  1414. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1415. dic.emplace("key1", "val1");
  1416. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1417. dic.emplace("key2", "val2");
  1418. dic.emplace("key3", "val3");
  1419. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1420. }
  1421. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1422. Params params;
  1423. params.emplace("a", "1");
  1424. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1425. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1426. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1427. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1428. // Long enough to overflow the stack when matched with std::regex.
  1429. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1430. EXPECT_EQ("/p?" + long_query + "&a=1",
  1431. append_query_params("/p?" + long_query, params));
  1432. }
  1433. // Joins every entry of a Headers or Params into "key=value " so a whole
  1434. // traversal can be compared in one assertion. Both are instantiations of the
  1435. // same insertion-ordered container, so one helper serves both.
  1436. template <typename Map> static std::string entries_to_string(const Map &m) {
  1437. std::string s;
  1438. for (const auto &entry : m) {
  1439. s += entry.first + "=" + entry.second + " ";
  1440. }
  1441. return s;
  1442. }
  1443. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1444. // Params used to be a std::multimap, which sorted by name and handed the
  1445. // caller's query back alphabetised. A client signing its query string could
  1446. // not reproduce the order it asked for.
  1447. Params dic;
  1448. dic.emplace("zulu", "1");
  1449. dic.emplace("alpha", "2");
  1450. dic.emplace("mike", "3");
  1451. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1452. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1453. }
  1454. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1455. Params dic;
  1456. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1457. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1458. }
  1459. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1460. Request req;
  1461. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1462. req.params);
  1463. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1464. EXPECT_EQ("first", req.get_param_value("tag"));
  1465. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1466. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1467. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1468. EXPECT_EQ("", req.get_param_value("tag", 3));
  1469. }
  1470. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1471. // Params shares its container with Headers, which matches field names
  1472. // case-insensitively. Parameter names must not pick that up.
  1473. Params dic;
  1474. dic.emplace("Key", "upper");
  1475. dic.emplace("key", "lower");
  1476. EXPECT_EQ(2U, dic.size());
  1477. EXPECT_EQ(1U, dic.count("Key"));
  1478. EXPECT_EQ(1U, dic.count("key"));
  1479. EXPECT_EQ("upper", dic.find("Key")->second);
  1480. EXPECT_EQ("lower", dic.find("key")->second);
  1481. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1482. }
  1483. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1484. Server svr;
  1485. std::string order;
  1486. svr.Get("/order", [&](const Request &req, Response &res) {
  1487. order = entries_to_string(req.params);
  1488. res.set_content("ok", "text/plain");
  1489. });
  1490. auto port = svr.bind_to_any_port(HOST);
  1491. thread t = thread([&] { svr.listen_after_bind(); });
  1492. auto se = detail::scope_exit([&] {
  1493. svr.stop();
  1494. t.join();
  1495. ASSERT_FALSE(svr.is_running());
  1496. });
  1497. svr.wait_until_ready();
  1498. Client cli(HOST, port);
  1499. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1500. ASSERT_TRUE(res);
  1501. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1502. }
  1503. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1504. Server svr;
  1505. std::string field_order, file_order;
  1506. svr.Post("/order", [&](const Request &req, Response &res) {
  1507. for (const auto &field : req.form.fields) {
  1508. field_order += field.first + "=" + field.second.content + " ";
  1509. }
  1510. for (const auto &file : req.form.files) {
  1511. file_order += file.first + "=" + file.second.filename + " ";
  1512. }
  1513. res.set_content("ok", "text/plain");
  1514. });
  1515. auto port = svr.bind_to_any_port(HOST);
  1516. thread t = thread([&] { svr.listen_after_bind(); });
  1517. auto se = detail::scope_exit([&] {
  1518. svr.stop();
  1519. t.join();
  1520. ASSERT_FALSE(svr.is_running());
  1521. });
  1522. svr.wait_until_ready();
  1523. UploadFormDataItems items = {
  1524. {"zulu", "1", "", ""},
  1525. {"alpha", "2", "", ""},
  1526. {"mike", "3", "", ""},
  1527. {"zebra", "z", "z.txt", "text/plain"},
  1528. {"apple", "a", "a.txt", "text/plain"},
  1529. };
  1530. Client cli(HOST, port);
  1531. auto res = cli.Post("/order", items);
  1532. ASSERT_TRUE(res);
  1533. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1534. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1535. }
  1536. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1537. Server svr;
  1538. std::vector<std::string> values;
  1539. std::string first, second, out_of_range, order;
  1540. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1541. values = req.form.get_fields("tag");
  1542. first = req.form.get_field("tag", 0);
  1543. second = req.form.get_field("tag", 1);
  1544. out_of_range = req.form.get_field("tag", 2);
  1545. for (const auto &field : req.form.fields) {
  1546. order += field.first + "=" + field.second.content + " ";
  1547. }
  1548. res.set_content("ok", "text/plain");
  1549. });
  1550. auto port = svr.bind_to_any_port(HOST);
  1551. thread t = thread([&] { svr.listen_after_bind(); });
  1552. auto se = detail::scope_exit([&] {
  1553. svr.stop();
  1554. t.join();
  1555. ASSERT_FALSE(svr.is_running());
  1556. });
  1557. svr.wait_until_ready();
  1558. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1559. // not adjacent in the container.
  1560. UploadFormDataItems items = {
  1561. {"tag", "first", "", ""},
  1562. {"other", "x", "", ""},
  1563. {"tag", "second", "", ""},
  1564. };
  1565. Client cli(HOST, port);
  1566. auto res = cli.Post("/repeated", items);
  1567. ASSERT_TRUE(res);
  1568. ASSERT_EQ(2U, values.size());
  1569. EXPECT_EQ("first", values[0]);
  1570. EXPECT_EQ("second", values[1]);
  1571. EXPECT_EQ("first", first);
  1572. EXPECT_EQ("second", second);
  1573. // std::multimap already kept entries sharing a name in insertion order, so
  1574. // everything above passes without this change too. The whole traversal is
  1575. // what tells the two apart: sorting by name would hoist "other" to the front
  1576. // and the two "tag" parts would end up adjacent.
  1577. EXPECT_EQ("tag=first other=x tag=second ", order);
  1578. // Advancing past the last entry of a name used to run off the container;
  1579. // the container's saturating increment makes it return the default instead.
  1580. EXPECT_EQ("", out_of_range);
  1581. }
  1582. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1583. Server svr;
  1584. std::string file_names;
  1585. svr.Post("/upload", [&](const Request &req, Response &res) {
  1586. for (const auto &file : req.form.files) {
  1587. file_names += file.first + "|" + file.second.filename + " ";
  1588. }
  1589. res.set_content("ok", "text/plain");
  1590. });
  1591. auto port = svr.bind_to_any_port(HOST);
  1592. thread t = thread([&] { svr.listen_after_bind(); });
  1593. auto se = detail::scope_exit([&] {
  1594. svr.stop();
  1595. t.join();
  1596. ASSERT_FALSE(svr.is_running());
  1597. });
  1598. svr.wait_until_ready();
  1599. // A trailing backslash would otherwise escape the closing quote.
  1600. UploadFormDataItems items = {
  1601. {"dir\\", "x", "a.txt", "text/plain"},
  1602. {"b", "y", "a\\\\b.txt", "text/plain"},
  1603. };
  1604. Client cli(HOST, port);
  1605. auto res = cli.Post("/upload", items);
  1606. ASSERT_TRUE(res);
  1607. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1608. }
  1609. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1610. // Server::read_content() keeps a FormFields::iterator alive across the
  1611. // content callbacks that fill the part it points at. The container is
  1612. // vector-backed, so a later emplace can reallocate and invalidate an older
  1613. // iterator; 64 parts grow the vector through seven reallocations, which
  1614. // checks that every part's content still lands in its own entry.
  1615. const size_t part_count = 64;
  1616. // One formula for both the parts sent and the values expected back, so the
  1617. // two cannot drift apart.
  1618. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1619. auto content_of = [](size_t i) {
  1620. return std::string(64, static_cast<char>('a' + (i % 26)));
  1621. };
  1622. Server svr;
  1623. std::vector<std::pair<std::string, std::string>> received;
  1624. svr.Post("/many", [&](const Request &req, Response &res) {
  1625. for (const auto &field : req.form.fields) {
  1626. received.emplace_back(field.first, field.second.content);
  1627. }
  1628. res.set_content("ok", "text/plain");
  1629. });
  1630. auto port = svr.bind_to_any_port(HOST);
  1631. thread t = thread([&] { svr.listen_after_bind(); });
  1632. auto se = detail::scope_exit([&] {
  1633. svr.stop();
  1634. t.join();
  1635. ASSERT_FALSE(svr.is_running());
  1636. });
  1637. svr.wait_until_ready();
  1638. UploadFormDataItems items;
  1639. for (size_t i = 0; i < part_count; i++) {
  1640. items.push_back({name_of(i), content_of(i), "", ""});
  1641. }
  1642. Client cli(HOST, port);
  1643. auto res = cli.Post("/many", items);
  1644. ASSERT_TRUE(res);
  1645. ASSERT_EQ(part_count, received.size());
  1646. for (size_t i = 0; i < part_count; i++) {
  1647. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1648. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1649. }
  1650. }
  1651. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1652. string content_type = "multipart/form-data; boundary=something";
  1653. string boundary;
  1654. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(boundary, "something");
  1657. }
  1658. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1659. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1660. string boundary;
  1661. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1662. EXPECT_TRUE(ret);
  1663. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1664. }
  1665. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1666. string content_type =
  1667. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1668. string boundary;
  1669. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1670. EXPECT_TRUE(ret);
  1671. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1672. }
  1673. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1674. string content_type =
  1675. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1676. string boundary;
  1677. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1678. EXPECT_TRUE(ret);
  1679. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1680. }
  1681. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1682. const string boundary(70, 'a');
  1683. string content_type = "multipart/form-data; boundary=" + boundary;
  1684. string parsed;
  1685. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1686. EXPECT_TRUE(ret);
  1687. EXPECT_EQ(parsed, boundary);
  1688. }
  1689. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1690. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1691. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1692. string parsed;
  1693. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1694. EXPECT_FALSE(ret);
  1695. }
  1696. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1697. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1698. // is 72 characters on the wire and still valid.
  1699. const string boundary(70, 'a');
  1700. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1701. string parsed;
  1702. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1703. EXPECT_EQ(parsed, boundary);
  1704. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1705. parsed.clear();
  1706. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1707. }
  1708. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1709. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1710. // The parameter parser must not treat that '=' as the key/value separator.
  1711. string content_type =
  1712. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1713. "charset=UTF-8";
  1714. string parsed;
  1715. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1716. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1717. }
  1718. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1719. // A ';' inside the quoted-string is part of the value, not a parameter
  1720. // separator, so it must not truncate the boundary.
  1721. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1722. string parsed;
  1723. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1724. EXPECT_EQ(parsed, "a;b");
  1725. }
  1726. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1727. string parsed;
  1728. EXPECT_TRUE(detail::parse_multipart_boundary(
  1729. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1730. EXPECT_EQ("a\\b", parsed);
  1731. EXPECT_TRUE(detail::parse_multipart_boundary(
  1732. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1733. EXPECT_EQ("a\"b", parsed);
  1734. }
  1735. TEST(ParseDispositionParamsTest, QuotedValues) {
  1736. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1737. // ';' and '=' are ordinary characters inside one.
  1738. struct {
  1739. const char *value;
  1740. std::vector<std::pair<const char *, const char *>> expected;
  1741. } cases[] = {
  1742. {"name=\"file1\"; filename=\"a.txt\"",
  1743. {{"name", "file1"}, {"filename", "a.txt"}}},
  1744. // Whitespace around '=' and ';' is still trimmed
  1745. {"name=\"file2\" ;filename = \"a.html\"",
  1746. {{"name", "file2"}, {"filename", "a.html"}}},
  1747. // '=' inside the value used to leave only the text after the last one
  1748. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1749. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1750. {"name=\"x=y\"", {{"name", "x=y"}}},
  1751. // ';' inside the value used to truncate the pair and leave a bogus one
  1752. {"name=\"file3\"; filename=\"a;b.txt\"",
  1753. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1754. // An unquoted value keeps working, and so does filename*
  1755. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1756. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1757. // A parameter with no key is dropped rather than turned into one whose
  1758. // key is the value
  1759. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1760. // An escaped quote does not end the value
  1761. {"name=\"a\\\"; filename=evil.php\"",
  1762. {{"name", "a\"; filename=evil.php"}}},
  1763. // Other backslashes, as in a Windows path, are kept
  1764. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1765. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1766. };
  1767. for (const auto &c : cases) {
  1768. Params params;
  1769. detail::parse_disposition_params(c.value, params);
  1770. for (const auto &kv : c.expected) {
  1771. auto it = params.find(kv.first);
  1772. ASSERT_NE(it, params.end())
  1773. << "value: " << c.value << ", key: " << kv.first;
  1774. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1775. }
  1776. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1777. }
  1778. }
  1779. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1780. Server svr;
  1781. std::string filename;
  1782. std::string content;
  1783. svr.Post("/upload", [&](const Request &req, Response &) {
  1784. const auto &file = req.form.get_file("file");
  1785. filename = file.filename;
  1786. content = file.content;
  1787. });
  1788. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1789. auto se = detail::scope_exit([&] {
  1790. svr.stop();
  1791. thread.join();
  1792. ASSERT_FALSE(svr.is_running());
  1793. });
  1794. svr.wait_until_ready();
  1795. std::string body = "--B\r\n"
  1796. "Content-Disposition: form-data; name=\"file\"; "
  1797. "filename=\"a.txt\"\r\n"
  1798. "Content-Type: text/plain\r\n"
  1799. "\r\n"
  1800. "hello\r\n"
  1801. "--B--\r\n";
  1802. Client cli(HOST, PORT);
  1803. auto res = cli.Post(
  1804. "/upload",
  1805. [&](size_t offset, DataSink &sink) {
  1806. if (offset < body.size()) {
  1807. sink.write(&body[offset], 1);
  1808. } else {
  1809. sink.done();
  1810. }
  1811. return true;
  1812. },
  1813. "multipart/form-data; boundary=B");
  1814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1815. EXPECT_EQ(StatusCode::OK_200, res->status);
  1816. EXPECT_EQ("a.txt", filename);
  1817. EXPECT_EQ("hello", content);
  1818. }
  1819. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1820. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1821. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1822. Server svr;
  1823. std::string field_value, file_name, file_filename;
  1824. bool has_field = false, has_file = false;
  1825. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1826. has_field = req.form.has_field("x=y");
  1827. field_value = req.form.get_field("x=y");
  1828. has_file = req.form.has_file("file1");
  1829. const auto &file = req.form.get_file("file1");
  1830. file_name = file.name;
  1831. file_filename = file.filename;
  1832. res.set_content("ok", "text/plain");
  1833. });
  1834. auto port = svr.bind_to_any_port(HOST);
  1835. thread t = thread([&] { svr.listen_after_bind(); });
  1836. auto se = detail::scope_exit([&] {
  1837. svr.stop();
  1838. t.join();
  1839. ASSERT_FALSE(svr.is_running());
  1840. });
  1841. svr.wait_until_ready();
  1842. UploadFormDataItems items = {
  1843. {"x=y", "field-value", "", ""},
  1844. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1845. };
  1846. Client cli(HOST, port);
  1847. auto res = cli.Post("/quoted", items);
  1848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1849. ASSERT_EQ(StatusCode::OK_200, res->status);
  1850. EXPECT_TRUE(has_field);
  1851. EXPECT_EQ("field-value", field_value);
  1852. EXPECT_TRUE(has_file);
  1853. EXPECT_EQ("file1", file_name);
  1854. EXPECT_EQ("a;b=report.pdf", file_filename);
  1855. }
  1856. TEST(GetHeaderValueTest, DefaultValue) {
  1857. Headers headers = {{"Dummy", "Dummy"}};
  1858. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1859. EXPECT_STREQ("text/plain", val);
  1860. }
  1861. TEST(GetHeaderValueTest, DefaultValueInt) {
  1862. Headers headers = {{"Dummy", "Dummy"}};
  1863. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1864. EXPECT_EQ(100ull, val);
  1865. }
  1866. TEST(GetHeaderValueTest, RegularValue) {
  1867. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1868. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1869. EXPECT_STREQ("text/html", val);
  1870. }
  1871. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1872. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1873. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1874. EXPECT_STREQ("text/html", val);
  1875. }
  1876. TEST(GetHeaderValueTest, SetContent) {
  1877. Response res;
  1878. res.set_content("html", "text/html");
  1879. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1880. res.set_content("text", "text/plain");
  1881. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1882. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1883. }
  1884. TEST(GetHeaderValueTest, RegularValueInt) {
  1885. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1886. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1887. EXPECT_EQ(100ull, val);
  1888. }
  1889. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1890. Headers headers = {{"Content-Length", "x"}};
  1891. auto is_invalid_value = false;
  1892. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1893. is_invalid_value);
  1894. EXPECT_EQ(0ull, val);
  1895. EXPECT_TRUE(is_invalid_value);
  1896. }
  1897. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1898. // An all-digit value that overflows size_t must be reported as invalid, not
  1899. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1900. // a large length to a small one on 32-bit builds, leaving the framing length
  1901. // wrong while is_invalid_value stayed false.
  1902. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1903. auto is_invalid_value = false;
  1904. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1905. is_invalid_value);
  1906. EXPECT_TRUE(is_invalid_value);
  1907. // A well-formed length is unaffected.
  1908. Headers ok = {{"Content-Length", "1234"}};
  1909. is_invalid_value = false;
  1910. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1911. is_invalid_value);
  1912. EXPECT_EQ(1234ull, val);
  1913. EXPECT_FALSE(is_invalid_value);
  1914. }
  1915. TEST(GetHeaderValueTest, Range) {
  1916. {
  1917. Headers headers = {make_range_header({{1, -1}})};
  1918. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1919. EXPECT_STREQ("bytes=1-", val);
  1920. }
  1921. {
  1922. Headers headers = {make_range_header({{-1, 1}})};
  1923. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1924. EXPECT_STREQ("bytes=-1", val);
  1925. }
  1926. {
  1927. Headers headers = {make_range_header({{1, 10}})};
  1928. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1929. EXPECT_STREQ("bytes=1-10", val);
  1930. }
  1931. {
  1932. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1933. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1934. EXPECT_STREQ("bytes=1-10, 100-", val);
  1935. }
  1936. {
  1937. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1938. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1939. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1940. }
  1941. {
  1942. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1943. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1944. EXPECT_STREQ("bytes=0-0, -1", val);
  1945. }
  1946. }
  1947. TEST(BearerTokenAuthTest, SchemeValidation) {
  1948. // A value shorter than "Bearer " must not throw from the fixed-length
  1949. // substr, and a non-Bearer scheme must not be reported as a token.
  1950. struct {
  1951. const char *value;
  1952. const char *expected;
  1953. } cases[] = {
  1954. {"x", ""},
  1955. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1956. {"Bearer abc123", "abc123"},
  1957. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1958. };
  1959. for (const auto &c : cases) {
  1960. Request req;
  1961. req.set_header("Authorization", c.value);
  1962. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1963. }
  1964. }
  1965. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1966. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1967. // to depend on the standard library (libstdc++ handed back duplicates in
  1968. // reverse insertion order, libc++ in insertion order).
  1969. Request req;
  1970. req.set_header("Accept-Encoding", "gzip");
  1971. req.set_header("Accept-Encoding", "deflate");
  1972. req.set_header("Accept-Encoding", "br");
  1973. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1974. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1975. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1976. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1977. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1978. }
  1979. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1980. Request req;
  1981. req.set_header("X-Test", "only");
  1982. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1983. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1984. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1985. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1986. }
  1987. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1988. Request req;
  1989. req.set_header("X-First", "1");
  1990. req.set_header("X-Test", "2");
  1991. req.params.emplace("first", "1");
  1992. req.params.emplace("test", "2");
  1993. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1994. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1995. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1996. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1997. // The second one is negative when read as a signed value
  1998. const auto max_id = (std::numeric_limits<size_t>::max)();
  1999. for (auto id : {max_id / 2, max_id}) {
  2000. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2001. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2002. EXPECT_EQ("", req.get_param_value("test", id));
  2003. EXPECT_EQ("", req.form.get_field("test", id));
  2004. EXPECT_EQ("", req.form.get_file("test", id).content);
  2005. }
  2006. }
  2007. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2008. Headers headers;
  2009. headers.emplace("Host", "example.com");
  2010. headers.emplace("Accept-Encoding", "gzip");
  2011. headers.emplace("User-Agent", "test");
  2012. headers.emplace("Accept-Encoding", "deflate");
  2013. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2014. "Accept-Encoding=deflate ",
  2015. entries_to_string(headers));
  2016. }
  2017. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2018. Headers headers = {{"Content-Type", "text/html"},
  2019. {"CONTENT-TYPE", "text/xml"}};
  2020. EXPECT_EQ(2U, headers.count("content-type"));
  2021. auto it = headers.find("content-type");
  2022. ASSERT_TRUE(it != headers.end());
  2023. EXPECT_EQ("text/html", it->second);
  2024. }
  2025. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2026. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2027. // drop only those fields and leave everything positioned between them.
  2028. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2029. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2030. auto rng = headers.equal_range("a");
  2031. headers.erase(rng.first, rng.second);
  2032. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2033. }
  2034. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2035. Headers headers = {
  2036. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2037. EXPECT_EQ(3U, headers.erase("A"));
  2038. EXPECT_EQ(0U, headers.count("A"));
  2039. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2040. }
  2041. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2042. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2043. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2044. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2045. }
  2046. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2047. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2048. headers.emplace_front("Host", "example.com");
  2049. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2050. entries_to_string(headers));
  2051. }
  2052. TEST(ParseHeaderValueTest, Range) {
  2053. {
  2054. Ranges ranges;
  2055. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2056. EXPECT_TRUE(ret);
  2057. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2058. }
  2059. {
  2060. Ranges ranges;
  2061. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2062. EXPECT_TRUE(ret);
  2063. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2064. }
  2065. {
  2066. Ranges ranges;
  2067. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2068. EXPECT_TRUE(ret);
  2069. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2070. }
  2071. {
  2072. Ranges ranges;
  2073. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2074. EXPECT_FALSE(ret);
  2075. }
  2076. {
  2077. Ranges ranges;
  2078. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2079. EXPECT_TRUE(ret);
  2080. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2081. }
  2082. {
  2083. Ranges ranges;
  2084. auto ret =
  2085. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2086. EXPECT_TRUE(ret);
  2087. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2088. }
  2089. {
  2090. Ranges ranges;
  2091. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2092. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2093. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2094. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2095. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2096. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2097. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2098. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2099. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2100. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2101. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2102. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2103. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2104. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2105. EXPECT_FALSE(
  2106. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2107. EXPECT_TRUE(ranges.empty());
  2108. }
  2109. {
  2110. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2111. // remainder of the representation, so it stays accepted.
  2112. Ranges ranges;
  2113. auto ret =
  2114. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2115. EXPECT_TRUE(ret);
  2116. ASSERT_EQ(1u, ranges.size());
  2117. EXPECT_EQ(0, ranges[0].first);
  2118. EXPECT_EQ(-1, ranges[0].second);
  2119. }
  2120. // RFC 9110 14.1: range unit names are case-insensitive.
  2121. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2122. Ranges ranges;
  2123. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2124. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2125. }
  2126. }
  2127. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2128. Request req;
  2129. req.set_header("Accept-Encoding", "gzip");
  2130. Response res;
  2131. res.set_header("Content-Type", "text/plain");
  2132. auto ret = detail::encoding_type(req, res);
  2133. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2134. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2135. #else
  2136. EXPECT_TRUE(ret == detail::EncodingType::None);
  2137. #endif
  2138. }
  2139. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2140. Request req;
  2141. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2142. Response res;
  2143. res.set_header("Content-Type", "text/plain");
  2144. auto ret = detail::encoding_type(req, res);
  2145. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2146. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2147. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2148. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2149. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2150. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2151. #else
  2152. EXPECT_TRUE(ret == detail::EncodingType::None);
  2153. #endif
  2154. }
  2155. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2156. Request req;
  2157. req.set_header("Accept-Encoding",
  2158. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2159. Response res;
  2160. res.set_header("Content-Type", "text/plain");
  2161. auto ret = detail::encoding_type(req, res);
  2162. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2163. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2164. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2165. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2166. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2167. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2168. #else
  2169. EXPECT_TRUE(ret == detail::EncodingType::None);
  2170. #endif
  2171. }
  2172. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2173. // All supported encodings rejected with q=0 should return None
  2174. Request req;
  2175. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2176. Response res;
  2177. res.set_header("Content-Type", "text/plain");
  2178. auto ret = detail::encoding_type(req, res);
  2179. EXPECT_TRUE(ret == detail::EncodingType::None);
  2180. }
  2181. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2182. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2183. Request req;
  2184. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2185. Response res;
  2186. res.set_header("Content-Type", "text/plain");
  2187. auto ret = detail::encoding_type(req, res);
  2188. EXPECT_TRUE(ret == detail::EncodingType::None);
  2189. }
  2190. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2191. Request req;
  2192. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2193. Response res;
  2194. res.set_header("Content-Type", "text/plain");
  2195. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2196. }
  2197. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2198. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2199. Request req;
  2200. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2201. Response res;
  2202. res.set_header("Content-Type", "text/plain");
  2203. auto ret = detail::encoding_type(req, res);
  2204. EXPECT_TRUE(ret == detail::EncodingType::None);
  2205. }
  2206. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2207. // RFC 7231: Accept-Encoding values are case-insensitive
  2208. Request req;
  2209. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2210. Response res;
  2211. res.set_header("Content-Type", "text/plain");
  2212. auto ret = detail::encoding_type(req, res);
  2213. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2214. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2215. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2216. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2217. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2218. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2219. #else
  2220. EXPECT_TRUE(ret == detail::EncodingType::None);
  2221. #endif
  2222. }
  2223. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2224. // q value should determine priority, not hardcoded order
  2225. Request req;
  2226. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2227. Response res;
  2228. res.set_header("Content-Type", "text/plain");
  2229. auto ret = detail::encoding_type(req, res);
  2230. // gzip has highest q=1.0, so it should be selected even though
  2231. // br and zstd are also supported
  2232. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2233. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2234. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2235. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2236. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2237. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2238. #else
  2239. EXPECT_TRUE(ret == detail::EncodingType::None);
  2240. #endif
  2241. }
  2242. TEST(BufferStreamTest, read) {
  2243. detail::BufferStream strm1;
  2244. Stream &strm = strm1;
  2245. EXPECT_EQ(5, strm.write("hello"));
  2246. char buf[512];
  2247. EXPECT_EQ(2, strm.read(buf, 2));
  2248. EXPECT_EQ('h', buf[0]);
  2249. EXPECT_EQ('e', buf[1]);
  2250. EXPECT_EQ(2, strm.read(buf, 2));
  2251. EXPECT_EQ('l', buf[0]);
  2252. EXPECT_EQ('l', buf[1]);
  2253. EXPECT_EQ(1, strm.read(buf, 1));
  2254. EXPECT_EQ('o', buf[0]);
  2255. EXPECT_EQ(0, strm.read(buf, 1));
  2256. }
  2257. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2258. auto host = "www.httpwatch.com";
  2259. auto ip = hosted_at(host);
  2260. EXPECT_EQ("23.96.13.243", ip);
  2261. std::vector<std::string> addrs;
  2262. hosted_at(host, addrs);
  2263. EXPECT_EQ(1u, addrs.size());
  2264. }
  2265. #if 0 // It depends on each test environment...
  2266. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2267. auto host = "www.youtube.com";
  2268. std::vector<std::string> addrs;
  2269. hosted_at(host, addrs);
  2270. EXPECT_EQ(20u, addrs.size());
  2271. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2272. EXPECT_TRUE(it != addrs.end());
  2273. }
  2274. #endif
  2275. class ChunkedEncodingTest : public ::testing::Test {
  2276. protected:
  2277. ChunkedEncodingTest()
  2278. : cli_(HOST, PORT)
  2279. #ifdef CPPHTTPLIB_SSL_ENABLED
  2280. ,
  2281. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2282. #endif
  2283. {
  2284. cli_.set_connection_timeout(2);
  2285. #ifdef CPPHTTPLIB_SSL_ENABLED
  2286. cli_.enable_server_certificate_verification(false);
  2287. #endif
  2288. }
  2289. virtual void SetUp() {
  2290. read_file("./image.jpg", image_data_);
  2291. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2292. res.set_content("Hello World!", "text/plain");
  2293. });
  2294. svr_.Get(
  2295. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2296. res.set_chunked_content_provider(
  2297. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2298. size_t remaining = image_data_.size() - offset;
  2299. if (remaining == 0) {
  2300. sink.done();
  2301. } else {
  2302. constexpr size_t CHUNK_SIZE = 1024;
  2303. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2304. sink.write(&image_data_[offset], send_size);
  2305. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2306. }
  2307. return true;
  2308. });
  2309. });
  2310. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2311. svr_.wait_until_ready();
  2312. }
  2313. virtual void TearDown() {
  2314. svr_.stop();
  2315. if (!request_threads_.empty()) {
  2316. std::this_thread::sleep_for(std::chrono::seconds(1));
  2317. for (auto &t : request_threads_) {
  2318. t.join();
  2319. }
  2320. }
  2321. t_.join();
  2322. }
  2323. #ifdef CPPHTTPLIB_SSL_ENABLED
  2324. SSLClient cli_;
  2325. SSLServer svr_;
  2326. #else
  2327. Client cli_;
  2328. Server svr_;
  2329. #endif
  2330. thread t_;
  2331. std::vector<thread> request_threads_;
  2332. std::string image_data_;
  2333. };
  2334. TEST_F(ChunkedEncodingTest, NormalGet) {
  2335. auto res = cli_.Get("/chunked");
  2336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2337. std::string out;
  2338. read_file("./image.jpg", out);
  2339. EXPECT_EQ(StatusCode::OK_200, res->status);
  2340. EXPECT_EQ(out, res->body);
  2341. }
  2342. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2343. std::string body;
  2344. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2345. body.append(data, data_length);
  2346. return true;
  2347. });
  2348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2349. std::string out;
  2350. read_file("./image.jpg", out);
  2351. EXPECT_EQ(StatusCode::OK_200, res->status);
  2352. EXPECT_EQ(out, body);
  2353. }
  2354. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2355. std::string body;
  2356. auto res = cli_.Get(
  2357. "/chunked",
  2358. [&](const Response &response) {
  2359. EXPECT_EQ(StatusCode::OK_200, response.status);
  2360. return true;
  2361. },
  2362. [&](const char *data, size_t data_length) {
  2363. body.append(data, data_length);
  2364. return true;
  2365. });
  2366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2367. std::string out;
  2368. read_file("./image.jpg", out);
  2369. EXPECT_EQ(StatusCode::OK_200, res->status);
  2370. EXPECT_EQ(out, body);
  2371. }
  2372. TEST(RangeTest, FromHTTPBin_Online) {
  2373. auto host = "httpbingo.org";
  2374. auto path = std::string{"/range/32"};
  2375. #ifdef CPPHTTPLIB_SSL_ENABLED
  2376. auto port = 443;
  2377. SSLClient cli(host, port);
  2378. #else
  2379. auto port = 80;
  2380. Client cli(host, port);
  2381. #endif
  2382. cli.set_connection_timeout(5);
  2383. {
  2384. auto res = cli.Get(path);
  2385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2386. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2387. EXPECT_EQ(StatusCode::OK_200, res->status);
  2388. }
  2389. {
  2390. Headers headers = {make_range_header({{1, -1}})};
  2391. auto res = cli.Get(path, headers);
  2392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2393. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2394. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2395. }
  2396. {
  2397. Headers headers = {make_range_header({{1, 10}})};
  2398. auto res = cli.Get(path, headers);
  2399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2400. EXPECT_EQ("bcdefghijk", res->body);
  2401. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2402. }
  2403. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2404. // entire resource, while the original httpbin returned 200. Both are
  2405. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2406. {
  2407. Headers headers = {make_range_header({{0, 31}})};
  2408. auto res = cli.Get(path, headers);
  2409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2410. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2411. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2412. res->status == StatusCode::PartialContent_206);
  2413. }
  2414. {
  2415. Headers headers = {make_range_header({{0, -1}})};
  2416. auto res = cli.Get(path, headers);
  2417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2418. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2419. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2420. res->status == StatusCode::PartialContent_206);
  2421. }
  2422. // go-httpbin returns 206 with clamped range for over-range requests,
  2423. // while the original httpbin returned 416. Both behaviors are observed
  2424. // in real servers, so we only verify the request succeeds.
  2425. {
  2426. Headers headers = {make_range_header({{0, 32}})};
  2427. auto res = cli.Get(path, headers);
  2428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2429. }
  2430. }
  2431. TEST(RangeTest, IgnoredForPost) {
  2432. Server svr;
  2433. svr.Post("/", [](const Request &, Response &res) {
  2434. res.set_content("abcdefg", "text/plain");
  2435. });
  2436. auto port = svr.bind_to_any_port(HOST);
  2437. ASSERT_GT(port, 0);
  2438. thread t = thread([&] { svr.listen_after_bind(); });
  2439. auto se = detail::scope_exit([&] {
  2440. svr.stop();
  2441. t.join();
  2442. ASSERT_FALSE(svr.is_running());
  2443. });
  2444. svr.wait_until_ready();
  2445. Client cli(HOST, port);
  2446. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2447. auto res = cli.Post("/", Headers{{"Range", range}});
  2448. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2449. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2450. EXPECT_EQ("abcdefg", res->body) << range;
  2451. }
  2452. }
  2453. TEST(RangeTest, IgnoredForUnknownUnit) {
  2454. Server svr;
  2455. svr.Get("/", [](const Request &, Response &res) {
  2456. res.set_content("abcdefg", "text/plain");
  2457. });
  2458. auto port = svr.bind_to_any_port(HOST);
  2459. ASSERT_GT(port, 0);
  2460. thread t = thread([&] { svr.listen_after_bind(); });
  2461. auto se = detail::scope_exit([&] {
  2462. svr.stop();
  2463. t.join();
  2464. ASSERT_FALSE(svr.is_running());
  2465. });
  2466. svr.wait_until_ready();
  2467. Client cli(HOST, port);
  2468. for (auto range : {"items=1-2", "none=x"}) {
  2469. auto res = cli.Get("/", Headers{{"Range", range}});
  2470. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2471. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2472. EXPECT_EQ("abcdefg", res->body) << range;
  2473. }
  2474. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2475. ASSERT_TRUE(res) << to_string(res.error());
  2476. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2477. }
  2478. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2479. auto host = "unresolvableaddress.local";
  2480. auto path = std::string{"/"};
  2481. #ifdef CPPHTTPLIB_SSL_ENABLED
  2482. auto port = 443;
  2483. SSLClient cli(host, port);
  2484. #else
  2485. auto port = 80;
  2486. Client cli(host, port);
  2487. #endif
  2488. cli.set_connection_timeout(1);
  2489. {
  2490. auto res = cli.Get(path);
  2491. ASSERT_FALSE(res);
  2492. }
  2493. std::this_thread::sleep_for(std::chrono::seconds(8));
  2494. }
  2495. #if defined(__linux__) && defined(__GLIBC__) && \
  2496. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2497. // Forward declaration: in split builds split.py strips `inline` and moves the
  2498. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2499. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2500. // against the symbol in both header-only and split builds.
  2501. namespace httplib {
  2502. namespace detail {
  2503. int getaddrinfo_with_timeout(const char *node, const char *service,
  2504. const struct addrinfo *hints,
  2505. struct addrinfo **res, time_t timeout_sec);
  2506. } // namespace detail
  2507. } // namespace httplib
  2508. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2509. //
  2510. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2511. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2512. // gai_suspend() call hits the connection timeout the function calls
  2513. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2514. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2515. // still alive and still references the now-destroyed stack frame.
  2516. //
  2517. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2518. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2519. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2520. // and runs them in a container.
  2521. namespace {
  2522. bool should_run_issue_2431_tests() {
  2523. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2524. return v && *v && std::string(v) != "0";
  2525. }
  2526. std::string unique_unresolvable_host(int n) {
  2527. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2528. // glibc still asks the configured nameserver — which is exactly the path
  2529. // we want to exercise. A unique label per call avoids the resolver cache.
  2530. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2531. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2532. std::to_string(n) + ".invalid";
  2533. }
  2534. } // namespace
  2535. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2536. if (!should_run_issue_2431_tests()) {
  2537. GTEST_SKIP()
  2538. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2539. }
  2540. for (int i = 0; i < 8; ++i) {
  2541. struct addrinfo hints;
  2542. memset(&hints, 0, sizeof(hints));
  2543. hints.ai_family = AF_UNSPEC;
  2544. hints.ai_socktype = SOCK_STREAM;
  2545. auto host = unique_unresolvable_host(i);
  2546. struct addrinfo *result = nullptr;
  2547. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2548. &result, /*timeout_sec=*/1);
  2549. if (rc == 0 && result) { freeaddrinfo(result); }
  2550. }
  2551. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2552. // stack region they still believe holds their gaicb.
  2553. std::this_thread::sleep_for(std::chrono::seconds(3));
  2554. }
  2555. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2556. if (!should_run_issue_2431_tests()) {
  2557. GTEST_SKIP()
  2558. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2559. }
  2560. std::atomic<bool> stop{false};
  2561. std::vector<std::thread> threads;
  2562. for (int t = 0; t < 8; ++t) {
  2563. threads.emplace_back([t, &stop] {
  2564. int i = 0;
  2565. while (!stop.load(std::memory_order_relaxed)) {
  2566. struct addrinfo hints;
  2567. memset(&hints, 0, sizeof(hints));
  2568. hints.ai_family = AF_UNSPEC;
  2569. hints.ai_socktype = SOCK_STREAM;
  2570. auto host = unique_unresolvable_host(t * 100000 + i++);
  2571. struct addrinfo *result = nullptr;
  2572. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2573. &result, /*timeout_sec=*/1);
  2574. if (rc == 0 && result) { freeaddrinfo(result); }
  2575. }
  2576. });
  2577. }
  2578. std::this_thread::sleep_for(std::chrono::seconds(8));
  2579. stop.store(true, std::memory_order_relaxed);
  2580. for (auto &th : threads) {
  2581. th.join();
  2582. }
  2583. std::this_thread::sleep_for(std::chrono::seconds(3));
  2584. }
  2585. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2586. if (!should_run_issue_2431_tests()) {
  2587. GTEST_SKIP()
  2588. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2589. }
  2590. std::atomic<bool> stop{false};
  2591. std::vector<std::thread> threads;
  2592. for (int t = 0; t < 8; ++t) {
  2593. threads.emplace_back([t, &stop] {
  2594. int i = 0;
  2595. while (!stop.load(std::memory_order_relaxed)) {
  2596. auto host = unique_unresolvable_host(t * 100000 + i++);
  2597. Client cli(host, 80);
  2598. cli.set_connection_timeout(1, 0);
  2599. cli.set_read_timeout(1, 0);
  2600. cli.set_write_timeout(1, 0);
  2601. (void)cli.Get("/");
  2602. }
  2603. });
  2604. }
  2605. std::this_thread::sleep_for(std::chrono::seconds(8));
  2606. stop.store(true, std::memory_order_relaxed);
  2607. for (auto &th : threads) {
  2608. th.join();
  2609. }
  2610. std::this_thread::sleep_for(std::chrono::seconds(3));
  2611. }
  2612. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2613. TEST(ConnectionErrorTest, InvalidHost) {
  2614. auto host = "-abcde.com";
  2615. #ifdef CPPHTTPLIB_SSL_ENABLED
  2616. auto port = 443;
  2617. SSLClient cli(host, port);
  2618. #else
  2619. auto port = 80;
  2620. Client cli(host, port);
  2621. #endif
  2622. cli.set_connection_timeout(std::chrono::seconds(2));
  2623. auto res = cli.Get("/");
  2624. ASSERT_TRUE(!res);
  2625. EXPECT_EQ(Error::Connection, res.error());
  2626. }
  2627. TEST(ConnectionErrorTest, InvalidHost2) {
  2628. auto host = "httpcan.org/";
  2629. #ifdef CPPHTTPLIB_SSL_ENABLED
  2630. SSLClient cli(host);
  2631. #else
  2632. Client cli(host);
  2633. #endif
  2634. cli.set_connection_timeout(std::chrono::seconds(2));
  2635. auto res = cli.Get("/");
  2636. ASSERT_TRUE(!res);
  2637. EXPECT_EQ(Error::Connection, res.error());
  2638. }
  2639. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2640. auto host = "httpcan.org/";
  2641. #ifdef CPPHTTPLIB_SSL_ENABLED
  2642. SSLClient cli(host);
  2643. #else
  2644. Client cli(host);
  2645. #endif
  2646. cli.set_connection_timeout(std::chrono::seconds(2));
  2647. auto res = cli.Get("/");
  2648. ASSERT_TRUE(!res);
  2649. stringstream s;
  2650. s << "error code: " << res.error();
  2651. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2652. }
  2653. TEST(ConnectionErrorTest, InvalidPort) {
  2654. auto host = "localhost";
  2655. auto port = 44380;
  2656. #ifdef CPPHTTPLIB_SSL_ENABLED
  2657. SSLClient cli(host, port);
  2658. #else
  2659. Client cli(host, port);
  2660. #endif
  2661. cli.set_connection_timeout(std::chrono::seconds(2));
  2662. auto res = cli.Get("/");
  2663. ASSERT_TRUE(!res);
  2664. EXPECT_TRUE(Error::Connection == res.error() ||
  2665. Error::ConnectionTimeout == res.error());
  2666. }
  2667. TEST(ConnectionErrorTest, Timeout_Online) {
  2668. auto host = "google.com";
  2669. #ifdef CPPHTTPLIB_SSL_ENABLED
  2670. auto port = 44380;
  2671. SSLClient cli(host, port);
  2672. #else
  2673. auto port = 8080;
  2674. Client cli(host, port);
  2675. #endif
  2676. cli.set_connection_timeout(std::chrono::seconds(2));
  2677. // only probe one address type so that the error reason
  2678. // correlates to the timed-out IPv4, not the unsupported
  2679. // IPv6 connection attempt
  2680. cli.set_address_family(AF_INET);
  2681. auto res = cli.Get("/");
  2682. ASSERT_TRUE(!res);
  2683. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2684. }
  2685. TEST(CancelTest, NoCancel_Online) {
  2686. auto host = "httpbingo.org";
  2687. auto path = std::string{"/range/32"};
  2688. #ifdef CPPHTTPLIB_SSL_ENABLED
  2689. auto port = 443;
  2690. SSLClient cli(host, port);
  2691. #else
  2692. auto port = 80;
  2693. Client cli(host, port);
  2694. #endif
  2695. cli.set_connection_timeout(std::chrono::seconds(5));
  2696. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2698. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2699. EXPECT_EQ(StatusCode::OK_200, res->status);
  2700. }
  2701. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2702. // Use /bytes with a large payload so that the DownloadProgress callback
  2703. // (which only fires for Content-Length responses) is invoked before the
  2704. // entire body is received, giving cancellation a chance to fire.
  2705. auto host = "httpbingo.org";
  2706. auto path = std::string{"/bytes/524288"};
  2707. #ifdef CPPHTTPLIB_SSL_ENABLED
  2708. auto port = 443;
  2709. SSLClient cli(host, port);
  2710. #else
  2711. auto port = 80;
  2712. Client cli(host, port);
  2713. #endif
  2714. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2715. cli.set_connection_timeout(std::chrono::seconds(5));
  2716. ASSERT_TRUE(!res);
  2717. EXPECT_EQ(Error::Canceled, res.error());
  2718. }
  2719. TEST(CancelTest, WithCancelLargePayload_Online) {
  2720. auto host = "httpbingo.org";
  2721. auto path = std::string{"/bytes/524288"};
  2722. #ifdef CPPHTTPLIB_SSL_ENABLED
  2723. auto port = 443;
  2724. SSLClient cli(host, port);
  2725. #else
  2726. auto port = 80;
  2727. Client cli(host, port);
  2728. #endif
  2729. cli.set_connection_timeout(std::chrono::seconds(5));
  2730. uint32_t count = 0;
  2731. auto res =
  2732. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2733. ASSERT_TRUE(!res);
  2734. EXPECT_EQ(Error::Canceled, res.error());
  2735. }
  2736. TEST(CancelTest, NoCancelPost) {
  2737. Server svr;
  2738. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2739. res.set_content("Hello World!", "text/plain");
  2740. });
  2741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2742. auto se = detail::scope_exit([&] {
  2743. svr.stop();
  2744. thread.join();
  2745. ASSERT_FALSE(svr.is_running());
  2746. });
  2747. svr.wait_until_ready();
  2748. Client cli(HOST, PORT);
  2749. cli.set_connection_timeout(std::chrono::seconds(5));
  2750. auto res =
  2751. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2752. "application/json", [](uint64_t, uint64_t) { return true; });
  2753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2754. EXPECT_EQ("Hello World!", res->body);
  2755. EXPECT_EQ(StatusCode::OK_200, res->status);
  2756. }
  2757. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2758. Server svr;
  2759. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2760. res.set_content("Hello World!", "text/plain");
  2761. });
  2762. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2763. auto se = detail::scope_exit([&] {
  2764. svr.stop();
  2765. thread.join();
  2766. ASSERT_FALSE(svr.is_running());
  2767. });
  2768. svr.wait_until_ready();
  2769. Client cli(HOST, PORT);
  2770. cli.set_connection_timeout(std::chrono::seconds(5));
  2771. auto res =
  2772. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2773. "application/json", [](uint64_t, uint64_t) { return false; });
  2774. ASSERT_TRUE(!res);
  2775. EXPECT_EQ(Error::Canceled, res.error());
  2776. }
  2777. TEST(CancelTest, WithCancelLargePayloadPost) {
  2778. Server svr;
  2779. svr.set_payload_max_length(200 * 1024 * 1024);
  2780. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2781. res.set_content(LARGE_DATA, "text/plain");
  2782. });
  2783. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2784. auto se = detail::scope_exit([&] {
  2785. svr.stop();
  2786. thread.join();
  2787. ASSERT_FALSE(svr.is_running());
  2788. });
  2789. svr.wait_until_ready();
  2790. Client cli(HOST, PORT);
  2791. cli.set_payload_max_length(200 * 1024 * 1024);
  2792. cli.set_connection_timeout(std::chrono::seconds(5));
  2793. auto res =
  2794. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2795. "application/json", [](uint64_t, uint64_t) { return false; });
  2796. ASSERT_TRUE(!res);
  2797. EXPECT_EQ(Error::Canceled, res.error());
  2798. }
  2799. TEST(CancelTest, NoCancelPut) {
  2800. Server svr;
  2801. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2802. res.set_content("Hello World!", "text/plain");
  2803. });
  2804. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2805. auto se = detail::scope_exit([&] {
  2806. svr.stop();
  2807. thread.join();
  2808. ASSERT_FALSE(svr.is_running());
  2809. });
  2810. svr.wait_until_ready();
  2811. Client cli(HOST, PORT);
  2812. cli.set_connection_timeout(std::chrono::seconds(5));
  2813. auto res =
  2814. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2815. "application/json", [](uint64_t, uint64_t) { return true; });
  2816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2817. EXPECT_EQ("Hello World!", res->body);
  2818. EXPECT_EQ(StatusCode::OK_200, res->status);
  2819. }
  2820. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2821. Server svr;
  2822. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2823. res.set_content("Hello World!", "text/plain");
  2824. });
  2825. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2826. auto se = detail::scope_exit([&] {
  2827. svr.stop();
  2828. thread.join();
  2829. ASSERT_FALSE(svr.is_running());
  2830. });
  2831. svr.wait_until_ready();
  2832. Client cli(HOST, PORT);
  2833. cli.set_connection_timeout(std::chrono::seconds(5));
  2834. auto res =
  2835. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2836. "application/json", [](uint64_t, uint64_t) { return false; });
  2837. ASSERT_TRUE(!res);
  2838. EXPECT_EQ(Error::Canceled, res.error());
  2839. }
  2840. TEST(CancelTest, WithCancelLargePayloadPut) {
  2841. Server svr;
  2842. svr.set_payload_max_length(200 * 1024 * 1024);
  2843. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2844. res.set_content(LARGE_DATA, "text/plain");
  2845. });
  2846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2847. auto se = detail::scope_exit([&] {
  2848. svr.stop();
  2849. thread.join();
  2850. ASSERT_FALSE(svr.is_running());
  2851. });
  2852. svr.wait_until_ready();
  2853. Client cli(HOST, PORT);
  2854. cli.set_payload_max_length(200 * 1024 * 1024);
  2855. cli.set_connection_timeout(std::chrono::seconds(5));
  2856. auto res =
  2857. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2858. "application/json", [](uint64_t, uint64_t) { return false; });
  2859. ASSERT_TRUE(!res);
  2860. EXPECT_EQ(Error::Canceled, res.error());
  2861. }
  2862. TEST(CancelTest, NoCancelPatch) {
  2863. Server svr;
  2864. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2865. res.set_content("Hello World!", "text/plain");
  2866. });
  2867. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2868. auto se = detail::scope_exit([&] {
  2869. svr.stop();
  2870. thread.join();
  2871. ASSERT_FALSE(svr.is_running());
  2872. });
  2873. svr.wait_until_ready();
  2874. Client cli(HOST, PORT);
  2875. cli.set_connection_timeout(std::chrono::seconds(5));
  2876. auto res =
  2877. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2878. "application/json", [](uint64_t, uint64_t) { return true; });
  2879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2880. EXPECT_EQ("Hello World!", res->body);
  2881. EXPECT_EQ(StatusCode::OK_200, res->status);
  2882. }
  2883. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2884. Server svr;
  2885. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2886. res.set_content("Hello World!", "text/plain");
  2887. });
  2888. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2889. auto se = detail::scope_exit([&] {
  2890. svr.stop();
  2891. thread.join();
  2892. ASSERT_FALSE(svr.is_running());
  2893. });
  2894. svr.wait_until_ready();
  2895. Client cli(HOST, PORT);
  2896. cli.set_connection_timeout(std::chrono::seconds(5));
  2897. auto res =
  2898. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2899. "application/json", [](uint64_t, uint64_t) { return false; });
  2900. ASSERT_TRUE(!res);
  2901. EXPECT_EQ(Error::Canceled, res.error());
  2902. }
  2903. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2904. Server svr;
  2905. svr.set_payload_max_length(200 * 1024 * 1024);
  2906. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2907. res.set_content(LARGE_DATA, "text/plain");
  2908. });
  2909. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2910. auto se = detail::scope_exit([&] {
  2911. svr.stop();
  2912. thread.join();
  2913. ASSERT_FALSE(svr.is_running());
  2914. });
  2915. svr.wait_until_ready();
  2916. Client cli(HOST, PORT);
  2917. cli.set_payload_max_length(200 * 1024 * 1024);
  2918. cli.set_connection_timeout(std::chrono::seconds(5));
  2919. auto res =
  2920. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2921. "application/json", [](uint64_t, uint64_t) { return false; });
  2922. ASSERT_TRUE(!res);
  2923. EXPECT_EQ(Error::Canceled, res.error());
  2924. }
  2925. TEST(CancelTest, NoCancelDelete) {
  2926. Server svr;
  2927. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2928. res.set_content("Hello World!", "text/plain");
  2929. });
  2930. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2931. auto se = detail::scope_exit([&] {
  2932. svr.stop();
  2933. thread.join();
  2934. ASSERT_FALSE(svr.is_running());
  2935. });
  2936. svr.wait_until_ready();
  2937. Client cli(HOST, PORT);
  2938. cli.set_connection_timeout(std::chrono::seconds(5));
  2939. auto res =
  2940. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2941. "application/json", [](uint64_t, uint64_t) { return true; });
  2942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2943. EXPECT_EQ("Hello World!", res->body);
  2944. EXPECT_EQ(StatusCode::OK_200, res->status);
  2945. }
  2946. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2947. Server svr;
  2948. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2949. res.set_content("Hello World!", "text/plain");
  2950. });
  2951. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2952. auto se = detail::scope_exit([&] {
  2953. svr.stop();
  2954. thread.join();
  2955. ASSERT_FALSE(svr.is_running());
  2956. });
  2957. svr.wait_until_ready();
  2958. Client cli(HOST, PORT);
  2959. cli.set_connection_timeout(std::chrono::seconds(5));
  2960. auto res =
  2961. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2962. "application/json", [](uint64_t, uint64_t) { return false; });
  2963. ASSERT_TRUE(!res);
  2964. EXPECT_EQ(Error::Canceled, res.error());
  2965. }
  2966. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2967. Server svr;
  2968. svr.set_payload_max_length(200 * 1024 * 1024);
  2969. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2970. res.set_content(LARGE_DATA, "text/plain");
  2971. });
  2972. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2973. auto se = detail::scope_exit([&] {
  2974. svr.stop();
  2975. thread.join();
  2976. ASSERT_FALSE(svr.is_running());
  2977. });
  2978. svr.wait_until_ready();
  2979. Client cli(HOST, PORT);
  2980. cli.set_payload_max_length(200 * 1024 * 1024);
  2981. cli.set_connection_timeout(std::chrono::seconds(5));
  2982. auto res =
  2983. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2984. "application/json", [](uint64_t, uint64_t) { return false; });
  2985. ASSERT_TRUE(!res);
  2986. EXPECT_EQ(Error::Canceled, res.error());
  2987. }
  2988. // One stop() from another thread ends a request that waits for the response
  2989. TEST(ClientStopTest, StopEndsWaitForResponse) {
  2990. Server svr;
  2991. std::atomic<bool> received{false};
  2992. std::atomic<bool> done{false};
  2993. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  2994. received.store(true);
  2995. while (!done.load()) {
  2996. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2997. }
  2998. res.set_content("Hello World!", "text/plain");
  2999. });
  3000. auto port = svr.bind_to_any_port(HOST);
  3001. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3002. Client cli(HOST, port);
  3003. cli.set_read_timeout(std::chrono::seconds(30));
  3004. std::future<Result> request;
  3005. auto se = detail::scope_exit([&] {
  3006. done.store(true);
  3007. svr.stop();
  3008. thread.join();
  3009. ASSERT_FALSE(svr.is_running());
  3010. });
  3011. svr.wait_until_ready();
  3012. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3013. for (int i = 0; i < 500 && !received.load(); ++i) {
  3014. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3015. }
  3016. ASSERT_TRUE(received.load());
  3017. // Let the client block in the wait for the response
  3018. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3019. auto start = std::chrono::steady_clock::now();
  3020. cli.stop();
  3021. ASSERT_EQ(std::future_status::ready,
  3022. request.wait_for(std::chrono::seconds(5)));
  3023. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3024. auto res = request.get();
  3025. ASSERT_TRUE(!res);
  3026. EXPECT_EQ(Error::Read, res.error());
  3027. }
  3028. // A listener whose backlog completes the TCP connections of clients, and that
  3029. // never answers them
  3030. struct SilentListener {
  3031. socket_t sock = INVALID_SOCKET;
  3032. sockaddr_in addr{};
  3033. int port = 0;
  3034. explicit SilentListener(int backlog = 1) {
  3035. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3036. addr.sin_family = AF_INET;
  3037. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3038. socklen_t len = sizeof(addr);
  3039. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3040. ::listen(sock, backlog) != 0 ||
  3041. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3042. detail::close_socket(sock);
  3043. sock = INVALID_SOCKET;
  3044. }
  3045. port = ntohs(addr.sin_port);
  3046. }
  3047. ~SilentListener() { detail::close_socket(sock); }
  3048. // The next connection, whose reads give up after 5 seconds
  3049. socket_t accept() const {
  3050. auto peer = ::accept(sock, nullptr, nullptr);
  3051. if (peer != INVALID_SOCKET) {
  3052. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3053. }
  3054. return peer;
  3055. }
  3056. };
  3057. static bool receives_a_byte(socket_t peer) {
  3058. char c = 0;
  3059. return detail::read_socket(peer, &c, 1, 0) == 1;
  3060. }
  3061. // Runs op, stops cli once the listener receives the first byte op sends, and
  3062. // expects op to end with error soon after
  3063. template <typename ClientType, typename Op>
  3064. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3065. Op op, Error error = Error::Canceled) {
  3066. auto ended = std::async(std::launch::async, op);
  3067. auto peer = listener.accept();
  3068. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3069. ASSERT_NE(INVALID_SOCKET, peer);
  3070. ASSERT_TRUE(receives_a_byte(peer));
  3071. cli.stop();
  3072. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3073. EXPECT_EQ(error, ended.get());
  3074. }
  3075. // Stops itself from another thread as the connection opens, the last moment a
  3076. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3077. // waits for the connection fails the test instead of hanging it.
  3078. class StoppedAsConnectedClient : public ClientImpl {
  3079. public:
  3080. using ClientImpl::ClientImpl;
  3081. protected:
  3082. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3083. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3084. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3085. stopper_.wait_for(std::chrono::seconds(1));
  3086. return true;
  3087. }
  3088. private:
  3089. std::future<void> stopper_;
  3090. };
  3091. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3092. SilentListener listener;
  3093. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3094. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3095. cli.set_read_timeout(std::chrono::seconds(3));
  3096. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3097. auto peer = listener.accept();
  3098. EXPECT_FALSE(receives_a_byte(peer));
  3099. detail::close_socket(peer);
  3100. auto handle = cli.open_stream("GET", "/");
  3101. EXPECT_FALSE(handle.is_valid());
  3102. EXPECT_EQ(Error::Canceled, handle.error);
  3103. peer = listener.accept();
  3104. EXPECT_FALSE(receives_a_byte(peer));
  3105. detail::close_socket(peer);
  3106. }
  3107. #ifdef __linux__
  3108. // A connect that a listener with a full backlog never completes
  3109. TEST(ClientStopTest, StopEndsAConnect) {
  3110. SilentListener listener(0);
  3111. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3112. std::vector<socket_t> backlog;
  3113. auto close_backlog = detail::scope_exit([&] {
  3114. for (auto sock : backlog) {
  3115. detail::close_socket(sock);
  3116. }
  3117. });
  3118. for (int i = 0; i < 8; i++) {
  3119. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3120. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3121. sizeof(listener.addr));
  3122. backlog.push_back(sock);
  3123. }
  3124. Client cli("127.0.0.1", listener.port);
  3125. cli.set_connection_timeout(std::chrono::seconds(3));
  3126. auto ended =
  3127. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3128. // A stop() before the request starts does not apply to it, so it repeats
  3129. auto status = std::future_status::timeout;
  3130. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3131. cli.stop();
  3132. status = ended.wait_for(std::chrono::milliseconds(10));
  3133. }
  3134. EXPECT_EQ(std::future_status::ready, status);
  3135. EXPECT_EQ(Error::Canceled, ended.get());
  3136. }
  3137. #endif
  3138. // The stream holds the socket while it waits for the head, out of the reach
  3139. // of shutdown()
  3140. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3141. SilentListener listener;
  3142. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3143. Client cli("127.0.0.1", listener.port);
  3144. cli.set_read_timeout(std::chrono::seconds(3));
  3145. expect_stop_ends(
  3146. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3147. Error::Read);
  3148. }
  3149. #ifdef CPPHTTPLIB_SSL_ENABLED
  3150. // A server that never answers the ClientHello
  3151. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3152. SilentListener listener;
  3153. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3154. SSLClient cli("127.0.0.1", listener.port);
  3155. cli.enable_server_certificate_verification(false);
  3156. cli.set_connection_timeout(std::chrono::seconds(3));
  3157. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3158. expect_stop_ends(cli, listener,
  3159. [&] { return cli.open_stream("GET", "/").error; });
  3160. }
  3161. // A proxy that takes the CONNECT and never answers it
  3162. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3163. SilentListener listener;
  3164. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3165. SSLClient cli("example.com", 443);
  3166. cli.set_proxy("127.0.0.1", listener.port);
  3167. cli.set_read_timeout(std::chrono::seconds(3));
  3168. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3169. }
  3170. #endif
  3171. // A read timeout past what the clock reaches waits for the response
  3172. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3173. SilentListener listener;
  3174. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3175. Client cli("127.0.0.1", listener.port);
  3176. cli.set_read_timeout(
  3177. static_cast<time_t>((std::min)(static_cast<long long>(
  3178. (std::numeric_limits<time_t>::max)()),
  3179. 10000000000LL)),
  3180. 0);
  3181. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3182. auto peer = listener.accept();
  3183. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3184. ASSERT_NE(INVALID_SOCKET, peer);
  3185. ASSERT_TRUE(receives_a_byte(peer));
  3186. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3187. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3188. "Connection: close\r\n\r\nok";
  3189. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3190. auto result = res.get();
  3191. ASSERT_TRUE(result);
  3192. EXPECT_EQ("ok", result->body);
  3193. }
  3194. static std::string remove_whitespace(const std::string &input) {
  3195. std::string output;
  3196. output.reserve(input.size());
  3197. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3198. [](unsigned char c) { return !std::isspace(c); });
  3199. return output;
  3200. }
  3201. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3202. auto host = "httpbingo.org";
  3203. auto path = std::string{"/basic-auth/hello/world"};
  3204. #ifdef CPPHTTPLIB_SSL_ENABLED
  3205. auto port = 443;
  3206. SSLClient cli(host, port);
  3207. #else
  3208. auto port = 80;
  3209. Client cli(host, port);
  3210. #endif
  3211. {
  3212. auto res = cli.Get(path);
  3213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3214. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3215. }
  3216. {
  3217. auto res = cli.Get(
  3218. path, Headers{make_basic_authentication_header("hello", "world")});
  3219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3220. auto body = remove_whitespace(res->body);
  3221. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3222. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3223. EXPECT_EQ(StatusCode::OK_200, res->status);
  3224. }
  3225. {
  3226. cli.set_basic_auth("hello", "world");
  3227. auto res = cli.Get(path);
  3228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3229. auto body = remove_whitespace(res->body);
  3230. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3231. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3232. EXPECT_EQ(StatusCode::OK_200, res->status);
  3233. }
  3234. {
  3235. cli.set_basic_auth("hello", "bad");
  3236. auto res = cli.Get(path);
  3237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3238. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3239. }
  3240. {
  3241. cli.set_basic_auth("bad", "world");
  3242. auto res = cli.Get(path);
  3243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3244. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3245. }
  3246. }
  3247. #ifdef CPPHTTPLIB_SSL_ENABLED
  3248. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3249. auto host = "httpbingo.org";
  3250. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3251. auto paths = std::vector<std::string>{
  3252. "/digest-auth/auth/hello/world/MD5",
  3253. "/digest-auth/auth/hello/world/SHA-256",
  3254. };
  3255. auto port = 443;
  3256. SSLClient cli(host, port);
  3257. {
  3258. auto res = cli.Get(unauth_path);
  3259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3260. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3261. }
  3262. {
  3263. cli.set_digest_auth("hello", "world");
  3264. for (const auto &path : paths) {
  3265. auto res = cli.Get(path.c_str());
  3266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3267. auto body = remove_whitespace(res->body);
  3268. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3269. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3270. EXPECT_EQ(StatusCode::OK_200, res->status);
  3271. }
  3272. cli.set_digest_auth("hello", "bad");
  3273. for (const auto &path : paths) {
  3274. auto res = cli.Get(path.c_str());
  3275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3276. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3277. }
  3278. }
  3279. }
  3280. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3281. // comma-separated list of challenges, and each challenge may itself carry a
  3282. // comma-separated auth-param list, so a server can legally offer Basic
  3283. // before Digest, either as two field lines or packed into one. Runs one 401
  3284. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3285. // value() joins them in receipt order) and checks that the retry carries a
  3286. // well-formed Digest Authorization header naming expected_realm.
  3287. static void
  3288. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3289. const std::string &expected_realm) {
  3290. std::atomic<int> hits{0};
  3291. Server svr;
  3292. svr.Get("/x", [&](const Request &req, Response &res) {
  3293. if (++hits == 1) {
  3294. res.status = StatusCode::Unauthorized_401;
  3295. for (const auto &challenge : challenges) {
  3296. res.set_header("WWW-Authenticate", challenge);
  3297. }
  3298. } else {
  3299. auto authorization = req.get_header_value("Authorization");
  3300. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3301. EXPECT_NE(std::string::npos,
  3302. authorization.find("realm=\"" + expected_realm + "\""));
  3303. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3304. res.set_content("ok", "text/plain");
  3305. }
  3306. });
  3307. auto port = svr.bind_to_any_port(HOST);
  3308. std::thread t([&]() { svr.listen_after_bind(); });
  3309. auto se = detail::scope_exit([&] {
  3310. svr.stop();
  3311. t.join();
  3312. });
  3313. svr.wait_until_ready();
  3314. Client cli(HOST, port);
  3315. cli.set_digest_auth("hello", "world");
  3316. auto res = cli.Get("/x");
  3317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3318. EXPECT_EQ(2, hits.load());
  3319. }
  3320. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3321. static const char *kDigestChallenge =
  3322. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3323. "algorithm=MD5";
  3324. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3325. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3326. "testrealm");
  3327. }
  3328. // Same challenge list with the schemes in the opposite order, to make sure
  3329. // the fix above didn't just special-case "Basic first".
  3330. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3331. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3332. "testrealm");
  3333. }
  3334. // A comma inside a quoted auth-param value must not be mistaken for the
  3335. // separator between two challenges (or two auth-params).
  3336. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3337. run_digest_challenge_list_test(
  3338. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3339. "algorithm=MD5"},
  3340. "test,realm");
  3341. }
  3342. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3343. // the params and leaves out the fragment.
  3344. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3345. Server svr;
  3346. std::string uri, target;
  3347. svr.Get("/a b", [&](const Request &req, Response &res) {
  3348. auto auth = req.get_header_value("Authorization");
  3349. if (auth.empty()) {
  3350. res.status = StatusCode::Unauthorized_401;
  3351. res.set_header("WWW-Authenticate",
  3352. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3353. return;
  3354. }
  3355. auto b = auth.find("uri=\"") + 5;
  3356. uri = auth.substr(b, auth.find('"', b) - b);
  3357. target = req.target;
  3358. });
  3359. auto port = svr.bind_to_any_port(HOST);
  3360. std::thread t([&]() { svr.listen_after_bind(); });
  3361. auto se = detail::scope_exit([&] {
  3362. svr.stop();
  3363. t.join();
  3364. });
  3365. svr.wait_until_ready();
  3366. Client cli(HOST, port);
  3367. cli.set_digest_auth("hello", "world");
  3368. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3370. EXPECT_EQ("/a%20b?x=1", target);
  3371. EXPECT_EQ(target, uri);
  3372. }
  3373. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3374. // make_digest_authentication_header() dereferences both unconditionally, so
  3375. // a server sending a challenge missing either one must not be treated as
  3376. // usable -- doing so used to crash the client with std::out_of_range.
  3377. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3378. Server svr;
  3379. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3380. res.status = StatusCode::Unauthorized_401;
  3381. res.set_header("WWW-Authenticate", challenge);
  3382. });
  3383. auto port = svr.bind_to_any_port(HOST);
  3384. std::thread t([&]() { svr.listen_after_bind(); });
  3385. auto se = detail::scope_exit([&] {
  3386. svr.stop();
  3387. t.join();
  3388. });
  3389. svr.wait_until_ready();
  3390. Client cli(HOST, port);
  3391. cli.set_digest_auth("hello", "world");
  3392. auto res = cli.Get("/x");
  3393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3394. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3395. }
  3396. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3397. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3398. }
  3399. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3400. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3401. }
  3402. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3403. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3404. }
  3405. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3406. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3407. // when storing the values, so the header builder has to re-escape them (and
  3408. // keep algorithm a bare token); otherwise the value breaks out of its
  3409. // quoted-string and injects extra auth-params into the client's Authorization.
  3410. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3411. std::atomic<int> hits{0};
  3412. std::string authorization;
  3413. Server svr;
  3414. svr.Get("/x", [&](const Request &req, Response &res) {
  3415. if (++hits == 1) {
  3416. res.status = StatusCode::Unauthorized_401;
  3417. // On the wire the quotes embedded in the values are backslash-escaped.
  3418. res.set_header("WWW-Authenticate",
  3419. "Digest realm=\"testrealm\", "
  3420. "nonce=\"n\\\"; injected=\\\"x\", "
  3421. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3422. } else {
  3423. authorization = req.get_header_value("Authorization");
  3424. res.set_content("ok", "text/plain");
  3425. }
  3426. });
  3427. auto port = svr.bind_to_any_port(HOST);
  3428. std::thread t([&]() { svr.listen_after_bind(); });
  3429. auto se = detail::scope_exit([&] {
  3430. svr.stop();
  3431. t.join();
  3432. });
  3433. svr.wait_until_ready();
  3434. Client cli(HOST, port);
  3435. cli.set_digest_auth("hello", "world");
  3436. auto res = cli.Get("/x");
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ(2, hits.load());
  3439. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3440. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3441. // inside its quoted-string rather than starting an "injected" auth-param.
  3442. EXPECT_NE(std::string::npos,
  3443. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3444. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3445. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3446. }
  3447. #endif
  3448. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3449. auto host = "google.com";
  3450. auto another_host = "example.com";
  3451. auto wrong_ip = "0.0.0.0";
  3452. #ifdef CPPHTTPLIB_SSL_ENABLED
  3453. SSLClient cli(host);
  3454. #else
  3455. Client cli(host);
  3456. #endif
  3457. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3458. auto res = cli.Get("/");
  3459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3460. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3461. }
  3462. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3463. auto host = "google.com";
  3464. auto wrong_ip = "0.0.0.0";
  3465. #ifdef CPPHTTPLIB_SSL_ENABLED
  3466. SSLClient cli(host);
  3467. #else
  3468. Client cli(host);
  3469. #endif
  3470. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3471. auto res = cli.Get("/");
  3472. ASSERT_TRUE(!res);
  3473. EXPECT_EQ(Error::Connection, res.error());
  3474. }
  3475. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3476. // A mapped value that is not an IP literal must be resolved. "localhost"
  3477. // resolves from the hosts file, so this test needs no external DNS.
  3478. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3479. auto host = "target.invalid";
  3480. Server svr;
  3481. std::string received_host;
  3482. svr.Get("/hi", [&](const Request &req, Response &res) {
  3483. received_host = req.get_header_value("Host");
  3484. res.set_content("Hello World!", "text/plain");
  3485. });
  3486. auto port = svr.bind_to_any_port(HOST);
  3487. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3488. auto se = detail::scope_exit([&] {
  3489. svr.stop();
  3490. thread.join();
  3491. ASSERT_FALSE(svr.is_running());
  3492. });
  3493. svr.wait_until_ready();
  3494. Client cli(host, port);
  3495. cli.set_direct_hostname_addr_map({{host, HOST}});
  3496. auto res = cli.Get("/hi");
  3497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3498. EXPECT_EQ(StatusCode::OK_200, res->status);
  3499. // The mapping only redirects the connection; the identity stays host_.
  3500. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3501. }
  3502. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3503. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3504. auto host = "target.invalid";
  3505. Server svr;
  3506. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3507. res.set_content("Hello World!", "text/plain");
  3508. });
  3509. auto port = svr.bind_to_any_port("127.0.0.1");
  3510. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3511. auto se = detail::scope_exit([&] {
  3512. svr.stop();
  3513. thread.join();
  3514. ASSERT_FALSE(svr.is_running());
  3515. });
  3516. svr.wait_until_ready();
  3517. Client cli(host, port);
  3518. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3519. auto res = cli.Get("/hi");
  3520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3521. EXPECT_EQ(StatusCode::OK_200, res->status);
  3522. }
  3523. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3524. // An empty mapped value must leave host_ as the connection target. Without
  3525. // that guard the empty value would become the host argument, getaddrinfo
  3526. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3527. // loopback - silently connecting somewhere the caller never asked for.
  3528. // The server listens on loopback, so such a fallback would succeed and is
  3529. // therefore observable as a failure of this test.
  3530. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3531. Server svr;
  3532. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3533. res.set_content("Hello World!", "text/plain");
  3534. });
  3535. auto port = svr.bind_to_any_port(HOST);
  3536. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3537. auto se = detail::scope_exit([&] {
  3538. svr.stop();
  3539. thread.join();
  3540. ASSERT_FALSE(svr.is_running());
  3541. });
  3542. svr.wait_until_ready();
  3543. Client cli(blackhole, port);
  3544. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3545. cli.set_connection_timeout(1);
  3546. auto res = cli.Get("/hi");
  3547. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3548. }
  3549. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3550. auto host = "target.invalid";
  3551. Server svr;
  3552. std::string received_host;
  3553. svr.Get("/hi", [&](const Request &req, Response &res) {
  3554. received_host = req.get_header_value("Host");
  3555. res.set_content("Hello World!", "text/plain");
  3556. });
  3557. auto port = svr.bind_to_any_port("127.0.0.1");
  3558. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3559. auto se = detail::scope_exit([&] {
  3560. svr.stop();
  3561. thread.join();
  3562. ASSERT_FALSE(svr.is_running());
  3563. });
  3564. svr.wait_until_ready();
  3565. Client cli(host, port);
  3566. #pragma GCC diagnostic push
  3567. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3568. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3569. #pragma GCC diagnostic pop
  3570. auto res = cli.Get("/hi");
  3571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3572. EXPECT_EQ(StatusCode::OK_200, res->status);
  3573. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3574. }
  3575. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3576. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3577. Server svr;
  3578. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3579. res.set_content("Hello World!", "text/plain");
  3580. });
  3581. auto port = svr.bind_to_any_port("127.0.0.1");
  3582. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3583. auto se = detail::scope_exit([&] {
  3584. svr.stop();
  3585. thread.join();
  3586. ASSERT_FALSE(svr.is_running());
  3587. });
  3588. svr.wait_until_ready();
  3589. Client cli("127.0.0.1", port);
  3590. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3591. cli.set_connection_timeout(1);
  3592. auto res = cli.Get("/hi");
  3593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3594. EXPECT_EQ(StatusCode::OK_200, res->status);
  3595. }
  3596. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3597. auto host = "httpbingo.org";
  3598. auto path = std::string{"/absolute-redirect/3"};
  3599. #ifdef CPPHTTPLIB_SSL_ENABLED
  3600. SSLClient cli(host);
  3601. #else
  3602. Client cli(host);
  3603. #endif
  3604. cli.set_follow_location(true);
  3605. auto res = cli.Get(path);
  3606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3607. EXPECT_EQ(StatusCode::OK_200, res->status);
  3608. }
  3609. TEST(RedirectTest, Redirect_Online) {
  3610. auto host = "httpbingo.org";
  3611. auto path = std::string{"/redirect/3"};
  3612. #ifdef CPPHTTPLIB_SSL_ENABLED
  3613. SSLClient cli(host);
  3614. #else
  3615. Client cli(host);
  3616. #endif
  3617. cli.set_follow_location(true);
  3618. auto res = cli.Get(path);
  3619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3620. EXPECT_EQ(StatusCode::OK_200, res->status);
  3621. }
  3622. TEST(RelativeRedirectTest, Redirect_Online) {
  3623. auto host = "httpbingo.org";
  3624. auto path = std::string{"/relative-redirect/3"};
  3625. #ifdef CPPHTTPLIB_SSL_ENABLED
  3626. SSLClient cli(host);
  3627. #else
  3628. Client cli(host);
  3629. #endif
  3630. cli.set_follow_location(true);
  3631. auto res = cli.Get(path);
  3632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3633. EXPECT_EQ(StatusCode::OK_200, res->status);
  3634. }
  3635. TEST(TooManyRedirectTest, Redirect_Online) {
  3636. auto host = "httpbingo.org";
  3637. auto path = std::string{"/redirect/21"};
  3638. #ifdef CPPHTTPLIB_SSL_ENABLED
  3639. SSLClient cli(host);
  3640. #else
  3641. Client cli(host);
  3642. #endif
  3643. cli.set_follow_location(true);
  3644. auto res = cli.Get(path);
  3645. ASSERT_TRUE(!res);
  3646. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3647. }
  3648. #ifdef CPPHTTPLIB_SSL_ENABLED
  3649. TEST(YahooRedirectTest, Redirect_Online) {
  3650. Client cli("yahoo.com");
  3651. auto res = cli.Get("/");
  3652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3653. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3654. cli.set_follow_location(true);
  3655. res = cli.Get("/");
  3656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3657. EXPECT_EQ(StatusCode::OK_200, res->status);
  3658. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3659. }
  3660. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3661. #define REDIR_HOST "httpbingo.org"
  3662. #define REDIR_PATH "/redirect-to"
  3663. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3664. SSLClient cli(REDIR_HOST);
  3665. cli.set_follow_location(true);
  3666. auto res =
  3667. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3669. EXPECT_EQ(StatusCode::OK_200, res->status);
  3670. }
  3671. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3672. SSLClient cli(REDIR_HOST);
  3673. cli.set_follow_location(true);
  3674. Params params;
  3675. params.emplace("url", "http://example.com");
  3676. params.emplace("status_code", "302");
  3677. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3679. EXPECT_EQ(StatusCode::OK_200, res->status);
  3680. }
  3681. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3682. SSLClient cli(REDIR_HOST);
  3683. cli.set_follow_location(true);
  3684. Params params;
  3685. params.emplace("url", "http://example.com");
  3686. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3688. EXPECT_EQ(StatusCode::OK_200, res->status);
  3689. }
  3690. TEST(UrlWithSpace, Redirect_Online) {
  3691. SSLClient cli("edge.forgecdn.net");
  3692. cli.set_follow_location(true);
  3693. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3695. EXPECT_EQ(StatusCode::OK_200, res->status);
  3696. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3697. }
  3698. #endif
  3699. #if !defined(_WIN32) && !defined(_WIN64)
  3700. TEST(ReceiveSignals, Signal) {
  3701. auto setupSignalHandlers = []() {
  3702. struct sigaction act;
  3703. sigemptyset(&act.sa_mask);
  3704. act.sa_flags = SA_SIGINFO;
  3705. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3706. switch (sig) {
  3707. case SIGINT:
  3708. default: break;
  3709. }
  3710. };
  3711. ::sigaction(SIGINT, &act, nullptr);
  3712. };
  3713. Server svr;
  3714. int port = 0;
  3715. auto thread = std::thread([&]() {
  3716. setupSignalHandlers();
  3717. port = svr.bind_to_any_port(HOST);
  3718. svr.listen_after_bind();
  3719. });
  3720. auto se = detail::scope_exit([&] {
  3721. svr.stop();
  3722. thread.join();
  3723. ASSERT_FALSE(svr.is_running());
  3724. });
  3725. svr.wait_until_ready();
  3726. ASSERT_TRUE(svr.is_running());
  3727. pthread_kill(thread.native_handle(), SIGINT);
  3728. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3729. ASSERT_TRUE(svr.is_running());
  3730. }
  3731. #endif
  3732. TEST(RedirectToDifferentPort, Redirect) {
  3733. Server svr1;
  3734. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3735. res.set_content("Hello World!", "text/plain");
  3736. });
  3737. int svr1_port = 0;
  3738. auto thread1 = std::thread([&]() {
  3739. svr1_port = svr1.bind_to_any_port(HOST);
  3740. svr1.listen_after_bind();
  3741. });
  3742. Server svr2;
  3743. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3744. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3745. });
  3746. int svr2_port = 0;
  3747. auto thread2 = std::thread([&]() {
  3748. svr2_port = svr2.bind_to_any_port(HOST);
  3749. svr2.listen_after_bind();
  3750. });
  3751. auto se = detail::scope_exit([&] {
  3752. svr2.stop();
  3753. thread2.join();
  3754. svr1.stop();
  3755. thread1.join();
  3756. ASSERT_FALSE(svr2.is_running());
  3757. ASSERT_FALSE(svr1.is_running());
  3758. });
  3759. svr1.wait_until_ready();
  3760. svr2.wait_until_ready();
  3761. Client cli("localhost", svr2_port);
  3762. cli.set_follow_location(true);
  3763. auto res = cli.Get("/2");
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ(StatusCode::OK_200, res->status);
  3766. EXPECT_EQ("Hello World!", res->body);
  3767. }
  3768. // GET /redir on one server redirects to /target on another port, so the
  3769. // client follows it with a new client.
  3770. static Result
  3771. GetThroughRedirectToDifferentPort(Server::Handler target,
  3772. const std::function<void(Client &)> &setup,
  3773. const Headers &headers = Headers()) {
  3774. Server target_svr;
  3775. target_svr.Get("/target", target);
  3776. int target_port = 0;
  3777. auto target_thread = std::thread([&]() {
  3778. target_port = target_svr.bind_to_any_port(HOST);
  3779. target_svr.listen_after_bind();
  3780. });
  3781. Server origin_svr;
  3782. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3783. res.set_redirect(
  3784. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3785. });
  3786. int origin_port = 0;
  3787. auto origin_thread = std::thread([&]() {
  3788. origin_port = origin_svr.bind_to_any_port(HOST);
  3789. origin_svr.listen_after_bind();
  3790. });
  3791. auto se = detail::scope_exit([&] {
  3792. origin_svr.stop();
  3793. origin_thread.join();
  3794. target_svr.stop();
  3795. target_thread.join();
  3796. });
  3797. target_svr.wait_until_ready();
  3798. origin_svr.wait_until_ready();
  3799. Client cli("localhost", origin_port);
  3800. cli.set_follow_location(true);
  3801. setup(cli);
  3802. return cli.Get("/redir", headers);
  3803. }
  3804. static void
  3805. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3806. std::string captured_authorization;
  3807. auto result = GetThroughRedirectToDifferentPort(
  3808. [&](const Request &req, Response &res) {
  3809. captured_authorization = req.get_header_value("Authorization");
  3810. res.set_content("OK", "text/plain");
  3811. },
  3812. set_auth);
  3813. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3814. EXPECT_EQ(StatusCode::OK_200, result->status);
  3815. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3816. EXPECT_TRUE(captured_authorization.empty());
  3817. }
  3818. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3819. TestDoNotForwardCredentialsOnRedirect(
  3820. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3821. }
  3822. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3823. TestDoNotForwardCredentialsOnRedirect(
  3824. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3825. }
  3826. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3827. std::string captured_cookie;
  3828. auto result = GetThroughRedirectToDifferentPort(
  3829. [&](const Request &req, Response &res) {
  3830. captured_cookie = req.get_header_value("Cookie");
  3831. res.set_content("OK", "text/plain");
  3832. },
  3833. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3834. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3835. EXPECT_EQ(StatusCode::OK_200, result->status);
  3836. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3837. EXPECT_TRUE(captured_cookie.empty());
  3838. }
  3839. TEST(RedirectToSamePort, ForwardCookie) {
  3840. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3841. // header so that ordinary session flows keep working.
  3842. Server svr;
  3843. std::string captured_cookie;
  3844. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3845. res.set_redirect("/target", 302);
  3846. });
  3847. svr.Get("/target", [&](const Request &req, Response &res) {
  3848. captured_cookie = req.get_header_value("Cookie");
  3849. res.set_content("OK", "text/plain");
  3850. });
  3851. auto port = svr.bind_to_any_port(HOST);
  3852. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3853. auto se = detail::scope_exit([&] {
  3854. svr.stop();
  3855. thread.join();
  3856. ASSERT_FALSE(svr.is_running());
  3857. });
  3858. svr.wait_until_ready();
  3859. Client cli(HOST, port);
  3860. cli.set_follow_location(true);
  3861. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3862. auto res = cli.Get("/redir", headers);
  3863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3864. EXPECT_EQ(StatusCode::OK_200, res->status);
  3865. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3866. }
  3867. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3868. // The Location alone names the next target, on any origin.
  3869. Server target_svr;
  3870. std::string cross_target;
  3871. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3872. cross_target = req.target;
  3873. res.set_content("OK", "text/plain");
  3874. });
  3875. auto target_port = target_svr.bind_to_any_port(HOST);
  3876. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3877. Server origin_svr;
  3878. std::string same_target;
  3879. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3880. res.set_redirect(
  3881. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3882. });
  3883. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3884. res.set_redirect("/landing", 302);
  3885. });
  3886. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3887. same_target = req.target;
  3888. res.set_content("OK", "text/plain");
  3889. });
  3890. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3891. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3892. auto se = detail::scope_exit([&] {
  3893. origin_svr.stop();
  3894. origin_thread.join();
  3895. target_svr.stop();
  3896. target_thread.join();
  3897. });
  3898. target_svr.wait_until_ready();
  3899. origin_svr.wait_until_ready();
  3900. Client cli("localhost", origin_port);
  3901. cli.set_follow_location(true);
  3902. Request req;
  3903. req.method = "GET";
  3904. req.params = {{"api_key", "SECRET"}};
  3905. req.path = "/cross";
  3906. auto res = cli.send(req);
  3907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3908. EXPECT_EQ("/landing", cross_target);
  3909. req.path = "/same";
  3910. res = cli.send(req);
  3911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3912. EXPECT_EQ("/landing", same_target);
  3913. }
  3914. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3915. std::string authorization;
  3916. std::string trace_id;
  3917. auto result = GetThroughRedirectToDifferentPort(
  3918. [&](const Request &req, Response &res) {
  3919. authorization = req.get_header_value("Authorization");
  3920. trace_id = req.get_header_value("X-Trace-Id");
  3921. res.set_content("OK", "text/plain");
  3922. },
  3923. [](Client &cli) {
  3924. cli.set_default_headers(
  3925. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3926. });
  3927. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3928. EXPECT_EQ(StatusCode::OK_200, result->status);
  3929. // Like a header given with the request, a default one goes along unless it
  3930. // carries credentials (RFC 9110 15.4).
  3931. EXPECT_TRUE(authorization.empty());
  3932. EXPECT_EQ("42", trace_id);
  3933. }
  3934. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3935. auto result = GetThroughRedirectToDifferentPort(
  3936. [](const Request &, Response &res) {
  3937. res.set_content(std::string(2048, 'x'), "text/plain");
  3938. },
  3939. [](Client &cli) { cli.set_payload_max_length(1024); });
  3940. EXPECT_FALSE(result);
  3941. }
  3942. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3943. auto result = GetThroughRedirectToDifferentPort(
  3944. [](const Request &req, Response &res) {
  3945. // Answer after a second, or once the client gives up.
  3946. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3947. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3948. }
  3949. res.set_content("late", "text/plain");
  3950. },
  3951. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3952. ASSERT_FALSE(result);
  3953. EXPECT_EQ(Error::Read, result.error());
  3954. }
  3955. #ifdef CPPHTTPLIB_SSL_ENABLED
  3956. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3957. auto result = GetThroughRedirectToDifferentPort(
  3958. [](const Request &, Response &res) {
  3959. res.status = StatusCode::Unauthorized_401;
  3960. res.set_header("WWW-Authenticate",
  3961. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3962. },
  3963. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3964. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3965. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3966. }
  3967. #endif
  3968. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3969. Server svr;
  3970. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3971. // Port number that overflows int — should not crash
  3972. res.set_redirect("http://localhost:99999999999999999999/target");
  3973. });
  3974. auto port = svr.bind_to_any_port(HOST);
  3975. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3976. auto se = detail::scope_exit([&] {
  3977. svr.stop();
  3978. thread.join();
  3979. ASSERT_FALSE(svr.is_running());
  3980. });
  3981. svr.wait_until_ready();
  3982. Client cli(HOST, port);
  3983. cli.set_follow_location(true);
  3984. auto res = cli.Get("/redir");
  3985. // Should fail gracefully, not crash (no valid response due to bad port)
  3986. EXPECT_FALSE(res);
  3987. }
  3988. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3989. Server svr;
  3990. auto port = svr.bind_to_any_port(HOST);
  3991. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3992. // The server's own port followed by junk must not be followed
  3993. res.set_redirect("http://" + std::string(HOST) + ":" +
  3994. std::to_string(port) + "junk/target");
  3995. });
  3996. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3997. res.set_content("target", "text/plain");
  3998. });
  3999. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4000. auto se = detail::scope_exit([&] {
  4001. svr.stop();
  4002. thread.join();
  4003. ASSERT_FALSE(svr.is_running());
  4004. });
  4005. svr.wait_until_ready();
  4006. Client cli(HOST, port);
  4007. cli.set_follow_location(true);
  4008. auto res = cli.Get("/redir");
  4009. EXPECT_FALSE(res);
  4010. }
  4011. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4012. Server target_svr;
  4013. std::atomic<int> target_hits{0};
  4014. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4015. target_hits++;
  4016. res.set_content("target", "text/plain");
  4017. });
  4018. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4019. res.set_content("target", "text/plain");
  4020. });
  4021. int target_port = 0;
  4022. auto target_thread = std::thread([&]() {
  4023. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4024. target_svr.listen_after_bind();
  4025. });
  4026. Server origin_svr;
  4027. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4028. res.set_redirect(req.get_param_value("to"));
  4029. });
  4030. int origin_port = 0;
  4031. auto origin_thread = std::thread([&]() {
  4032. origin_port = origin_svr.bind_to_any_port(HOST);
  4033. origin_svr.listen_after_bind();
  4034. });
  4035. auto se = detail::scope_exit([&] {
  4036. origin_svr.stop();
  4037. origin_thread.join();
  4038. target_svr.stop();
  4039. target_thread.join();
  4040. ASSERT_FALSE(origin_svr.is_running());
  4041. ASSERT_FALSE(target_svr.is_running());
  4042. });
  4043. target_svr.wait_until_ready();
  4044. origin_svr.wait_until_ready();
  4045. auto port = std::to_string(target_port);
  4046. for (const auto &to :
  4047. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4048. Client cli(HOST, origin_port);
  4049. cli.set_follow_location(true);
  4050. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4051. EXPECT_FALSE(res) << to;
  4052. }
  4053. EXPECT_EQ(0, target_hits);
  4054. Client cli(HOST, origin_port);
  4055. cli.set_follow_location(true);
  4056. auto res = cli.Get("/redir?to=" +
  4057. encode_query_component("//127.0.0.1:" + port + "/target"));
  4058. ASSERT_TRUE(res) << to_string(res.error());
  4059. EXPECT_EQ(StatusCode::OK_200, res->status);
  4060. EXPECT_EQ("target", res->body);
  4061. }
  4062. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4063. Server svr;
  4064. std::atomic<bool> followed{false};
  4065. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4066. res.status = StatusCode::NotModified_304;
  4067. res.set_header("Location", "/target");
  4068. });
  4069. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4070. res.status = StatusCode::UseProxy_305;
  4071. res.set_header("Location", "/target");
  4072. });
  4073. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4074. followed = true;
  4075. res.set_content("target", "text/plain");
  4076. });
  4077. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4078. auto se = detail::scope_exit([&] {
  4079. svr.stop();
  4080. th.join();
  4081. ASSERT_FALSE(svr.is_running());
  4082. });
  4083. svr.wait_until_ready();
  4084. Client cli("localhost", PORT);
  4085. cli.set_follow_location(true);
  4086. auto res = cli.Get("/304");
  4087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4088. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4089. res = cli.Get("/305");
  4090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4091. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4092. EXPECT_FALSE(followed);
  4093. }
  4094. TEST(RedirectFromPageWithContent, Redirect) {
  4095. Server svr;
  4096. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4097. res.set_content("___", "text/plain");
  4098. res.set_redirect("/2");
  4099. });
  4100. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4101. res.set_content("Hello World!", "text/plain");
  4102. });
  4103. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4104. auto se = detail::scope_exit([&] {
  4105. svr.stop();
  4106. th.join();
  4107. ASSERT_FALSE(svr.is_running());
  4108. });
  4109. svr.wait_until_ready();
  4110. {
  4111. Client cli("localhost", PORT);
  4112. cli.set_follow_location(true);
  4113. std::string body;
  4114. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4115. body.append(data, data_length);
  4116. return true;
  4117. });
  4118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4119. EXPECT_EQ(StatusCode::OK_200, res->status);
  4120. EXPECT_EQ("Hello World!", body);
  4121. }
  4122. {
  4123. Client cli("localhost", PORT);
  4124. std::string body;
  4125. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4126. body.append(data, data_length);
  4127. return true;
  4128. });
  4129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4130. EXPECT_EQ(StatusCode::Found_302, res->status);
  4131. EXPECT_EQ("___", body);
  4132. }
  4133. }
  4134. // A server can close the connection after a request with "Connection: close"
  4135. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4136. // redirected request must go out on a new connection.
  4137. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4138. #ifndef _WIN32
  4139. signal(SIGPIPE, SIG_IGN);
  4140. #endif
  4141. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4142. default_socket_options(srv);
  4143. sockaddr_in addr{};
  4144. addr.sin_family = AF_INET;
  4145. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4146. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4147. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4148. ASSERT_EQ(0, ::listen(srv, 2));
  4149. auto send_text = [](socket_t sock, const std::string &text) {
  4150. ::send(sock,
  4151. #ifdef _WIN32
  4152. static_cast<const char *>(text.c_str()),
  4153. static_cast<int>(text.size()),
  4154. #else
  4155. text.c_str(), text.size(),
  4156. #endif
  4157. 0);
  4158. };
  4159. auto reused = false;
  4160. auto server_thread = std::thread([&] {
  4161. char buf[4096];
  4162. auto first = ::accept(srv, nullptr, nullptr);
  4163. if (first == INVALID_SOCKET) { return; }
  4164. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4165. ::recv(first, buf, sizeof(buf), 0);
  4166. send_text(
  4167. first,
  4168. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4169. auto next = first;
  4170. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4171. reused = true;
  4172. } else {
  4173. detail::close_socket(first);
  4174. next = ::accept(srv, nullptr, nullptr);
  4175. if (next == INVALID_SOCKET) { return; }
  4176. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4177. ::recv(next, buf, sizeof(buf), 0);
  4178. }
  4179. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4180. "Connection: close\r\n\r\nok");
  4181. detail::close_socket(next);
  4182. });
  4183. Client cli("127.0.0.1", PORT + 2);
  4184. cli.set_follow_location(true);
  4185. cli.set_read_timeout(5, 0);
  4186. auto res = cli.Get("/1");
  4187. server_thread.join();
  4188. detail::close_socket(srv);
  4189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4190. EXPECT_EQ(StatusCode::OK_200, res->status);
  4191. EXPECT_EQ("ok", res->body);
  4192. EXPECT_FALSE(reused);
  4193. }
  4194. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4195. Server svr;
  4196. auto port_str = std::to_string(PORT);
  4197. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4198. auto expected_host = "[::1]:" + port_str;
  4199. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4200. res.set_content("___", "text/plain");
  4201. // res.set_redirect("/2");
  4202. res.set_redirect(redirect_url);
  4203. });
  4204. svr.Get("/2", [&](const Request &req, Response &res) {
  4205. auto host_header = req.headers.find("Host");
  4206. ASSERT_TRUE(host_header != req.headers.end());
  4207. EXPECT_EQ(expected_host, host_header->second);
  4208. res.set_content("Hello World!", "text/plain");
  4209. });
  4210. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4211. auto se = detail::scope_exit([&] {
  4212. svr.stop();
  4213. th.join();
  4214. ASSERT_FALSE(svr.is_running());
  4215. });
  4216. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4217. // actually starts anything, so the condition !svr.is_running() will
  4218. // always remain true, and the loop never stops.
  4219. // This basically counts how many milliseconds have passed since the
  4220. // call to svr.listen(), and if after 5 seconds nothing started yet
  4221. // aborts the test.
  4222. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4223. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4224. ASSERT_LT(milliseconds, 5000U);
  4225. }
  4226. {
  4227. Client cli("::1", PORT);
  4228. cli.set_follow_location(true);
  4229. std::string body;
  4230. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4231. body.append(data, data_length);
  4232. return true;
  4233. });
  4234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4235. EXPECT_EQ(StatusCode::OK_200, res->status);
  4236. EXPECT_EQ("Hello World!", body);
  4237. }
  4238. {
  4239. Client cli("::1", PORT);
  4240. std::string body;
  4241. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4242. body.append(data, data_length);
  4243. return true;
  4244. });
  4245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4246. EXPECT_EQ(StatusCode::Found_302, res->status);
  4247. EXPECT_EQ("___", body);
  4248. }
  4249. }
  4250. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4251. Server svr;
  4252. svr.Get("/foo", [](const Request &req, Response &res) {
  4253. auto a = req.params.find("a");
  4254. if (a != req.params.end()) {
  4255. res.set_content((*a).second, "text/plain");
  4256. res.status = StatusCode::OK_200;
  4257. } else {
  4258. res.status = StatusCode::BadRequest_400;
  4259. }
  4260. });
  4261. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4262. auto se = detail::scope_exit([&] {
  4263. svr.stop();
  4264. thread.join();
  4265. ASSERT_FALSE(svr.is_running());
  4266. });
  4267. svr.wait_until_ready();
  4268. {
  4269. Client cli(HOST, PORT);
  4270. cli.set_path_encode(false);
  4271. auto res = cli.Get("/foo?a=explicitly+encoded");
  4272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4273. EXPECT_EQ(StatusCode::OK_200, res->status);
  4274. // This expects it back with a space, as the `+` won't have been
  4275. // url-encoded, and server-side the params get decoded turning `+`
  4276. // into spaces.
  4277. EXPECT_EQ("explicitly encoded", res->body);
  4278. }
  4279. }
  4280. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4281. // When path encoding is disabled the client must transmit the supplied
  4282. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4283. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4284. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4285. // than a space (0x20). Assert on the raw wire target to catch this.
  4286. Server svr;
  4287. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4288. svr.Get("/foo", [&](const Request &req, Response &res) {
  4289. EXPECT_EQ(expected_target, req.target);
  4290. res.status = StatusCode::OK_200;
  4291. });
  4292. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4293. auto se = detail::scope_exit([&] {
  4294. svr.stop();
  4295. thread.join();
  4296. ASSERT_FALSE(svr.is_running());
  4297. });
  4298. svr.wait_until_ready();
  4299. {
  4300. Client cli(HOST, PORT);
  4301. cli.set_path_encode(false);
  4302. auto res = cli.Get(expected_target.c_str());
  4303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4304. EXPECT_EQ(StatusCode::OK_200, res->status);
  4305. }
  4306. }
  4307. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4308. // `open_stream()` used to skip the path encoding that the buffered send
  4309. // path applies, so the same `path` produced different bytes in the request
  4310. // line depending on which API was used. Assert the two agree.
  4311. Server svr;
  4312. std::string target;
  4313. svr.Get(".*", [&](const Request &req, Response &res) {
  4314. target = req.target;
  4315. res.status = StatusCode::OK_200;
  4316. });
  4317. auto port = svr.bind_to_any_port(HOST);
  4318. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4319. auto se = detail::scope_exit([&] {
  4320. svr.stop();
  4321. thread.join();
  4322. ASSERT_FALSE(svr.is_running());
  4323. });
  4324. svr.wait_until_ready();
  4325. struct {
  4326. const char *path;
  4327. const char *expected;
  4328. } cases[] = {
  4329. {"/a b?x=1", "/a%20b?x=1"},
  4330. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4331. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4332. };
  4333. for (const auto &c : cases) {
  4334. Client cli(HOST, port);
  4335. target.clear();
  4336. auto res = cli.Get(c.path);
  4337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4338. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4339. auto buffered_target = target;
  4340. target.clear();
  4341. auto handle = cli.open_stream("GET", c.path);
  4342. EXPECT_TRUE(handle.is_valid())
  4343. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4344. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4345. }
  4346. }
  4347. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4348. // The `set_path_encode(false)` contract — transmit the supplied target
  4349. // verbatim — must hold for the streaming API too.
  4350. Server svr;
  4351. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4352. std::string target;
  4353. svr.Get("/foo", [&](const Request &req, Response &res) {
  4354. target = req.target;
  4355. res.status = StatusCode::OK_200;
  4356. });
  4357. auto port = svr.bind_to_any_port(HOST);
  4358. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4359. auto se = detail::scope_exit([&] {
  4360. svr.stop();
  4361. thread.join();
  4362. ASSERT_FALSE(svr.is_running());
  4363. });
  4364. svr.wait_until_ready();
  4365. {
  4366. Client cli(HOST, port);
  4367. cli.set_path_encode(false);
  4368. auto handle = cli.open_stream("GET", expected_target);
  4369. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4370. EXPECT_EQ(expected_target, target);
  4371. }
  4372. }
  4373. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4374. // With path encoding enabled a CR/LF in the target is percent-encoded
  4375. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4376. // write_request_line still backstops `set_path_encode(false)`, which is
  4377. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4378. Server svr;
  4379. // Captured before routing: the decoded path contains a newline, which a
  4380. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4381. std::string target;
  4382. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4383. target = req.target;
  4384. res.status = StatusCode::OK_200;
  4385. return Server::HandlerResponse::Handled;
  4386. });
  4387. auto port = svr.bind_to_any_port(HOST);
  4388. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4389. auto se = detail::scope_exit([&] {
  4390. svr.stop();
  4391. thread.join();
  4392. ASSERT_FALSE(svr.is_running());
  4393. });
  4394. svr.wait_until_ready();
  4395. {
  4396. Client cli(HOST, port);
  4397. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4398. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4399. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4400. }
  4401. }
  4402. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4403. // Every control character is percent-encoded, not just CR/LF, so the target
  4404. // passes the request-target check in write_request_line.
  4405. Server svr;
  4406. std::string target;
  4407. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4408. target = req.target;
  4409. res.status = StatusCode::OK_200;
  4410. return Server::HandlerResponse::Handled;
  4411. });
  4412. auto port = svr.bind_to_any_port(HOST);
  4413. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4414. auto se = detail::scope_exit([&] {
  4415. svr.stop();
  4416. thread.join();
  4417. ASSERT_FALSE(svr.is_running());
  4418. });
  4419. svr.wait_until_ready();
  4420. {
  4421. Client cli(HOST, port);
  4422. auto res = cli.Get("/a\tb\x1b\x7f");
  4423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4424. EXPECT_EQ("/a%09b%1B%7F", target);
  4425. }
  4426. }
  4427. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4428. // Nothing may reach the wire: a raw CR/LF target would split the request
  4429. // line and inject headers.
  4430. Server svr;
  4431. // Pre-routing so that "not called" means nothing reached the server at all,
  4432. // rather than merely failing to match a handler pattern.
  4433. auto handler_called = false;
  4434. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4435. handler_called = true;
  4436. res.status = StatusCode::OK_200;
  4437. return Server::HandlerResponse::Handled;
  4438. });
  4439. auto port = svr.bind_to_any_port(HOST);
  4440. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4441. auto se = detail::scope_exit([&] {
  4442. svr.stop();
  4443. thread.join();
  4444. ASSERT_FALSE(svr.is_running());
  4445. });
  4446. svr.wait_until_ready();
  4447. {
  4448. Client cli(HOST, port);
  4449. cli.set_path_encode(false);
  4450. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4451. EXPECT_FALSE(handle.is_valid());
  4452. EXPECT_EQ(Error::Write, handle.error);
  4453. EXPECT_FALSE(handler_called);
  4454. }
  4455. }
  4456. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4457. // Which of the two branches runs is decided by whether the query component
  4458. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4459. // an empty query and must still fall back to building one from
  4460. // `req.params`, while a non-empty query must win over `req.params`.
  4461. Server svr;
  4462. std::string target;
  4463. svr.Get("/foo", [&](const Request &req, Response &res) {
  4464. target = req.target;
  4465. res.status = StatusCode::OK_200;
  4466. });
  4467. auto port = svr.bind_to_any_port(HOST);
  4468. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4469. auto se = detail::scope_exit([&] {
  4470. svr.stop();
  4471. thread.join();
  4472. ASSERT_FALSE(svr.is_running());
  4473. });
  4474. svr.wait_until_ready();
  4475. {
  4476. // Trailing `?` -> empty query component -> `req.params` is used.
  4477. Client cli(HOST, port);
  4478. Request req;
  4479. req.method = "GET";
  4480. req.path = "/foo?";
  4481. req.params.emplace("a", "1");
  4482. target.clear();
  4483. auto res = cli.send(req);
  4484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4485. EXPECT_EQ("/foo?a=1", target);
  4486. }
  4487. {
  4488. // Non-empty query in `req.path` -> `req.params` is not appended.
  4489. Client cli(HOST, port);
  4490. Request req;
  4491. req.method = "GET";
  4492. req.path = "/foo?b=2";
  4493. req.params.emplace("a", "1");
  4494. target.clear();
  4495. auto res = cli.send(req);
  4496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4497. EXPECT_EQ("/foo?b=2", target);
  4498. }
  4499. }
  4500. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4501. Server svr;
  4502. svr.Get("/", [](const Request &req, Response &) {
  4503. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4504. });
  4505. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4506. auto se = detail::scope_exit([&] {
  4507. svr.stop();
  4508. thread.join();
  4509. ASSERT_FALSE(svr.is_running());
  4510. });
  4511. svr.wait_until_ready();
  4512. {
  4513. Client cli(HOST, PORT);
  4514. cli.set_path_encode(false);
  4515. auto res = cli.Get("/?something=%0A");
  4516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4517. EXPECT_EQ(StatusCode::OK_200, res->status);
  4518. }
  4519. }
  4520. TEST(BindServerTest, BindDualStack) {
  4521. Server svr;
  4522. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4523. res.set_content("Hello World!", "text/plain");
  4524. });
  4525. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4526. auto se = detail::scope_exit([&] {
  4527. svr.stop();
  4528. thread.join();
  4529. ASSERT_FALSE(svr.is_running());
  4530. });
  4531. svr.wait_until_ready();
  4532. {
  4533. Client cli("127.0.0.1", PORT);
  4534. auto res = cli.Get("/1");
  4535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4536. EXPECT_EQ(StatusCode::OK_200, res->status);
  4537. EXPECT_EQ("Hello World!", res->body);
  4538. }
  4539. {
  4540. Client cli("::1", PORT);
  4541. auto res = cli.Get("/1");
  4542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4543. EXPECT_EQ(StatusCode::OK_200, res->status);
  4544. EXPECT_EQ("Hello World!", res->body);
  4545. }
  4546. }
  4547. TEST(BindServerTest, BindAndListenSeparately) {
  4548. Server svr;
  4549. int port = svr.bind_to_any_port("0.0.0.0");
  4550. ASSERT_TRUE(svr.is_valid());
  4551. ASSERT_TRUE(port > 0);
  4552. svr.stop();
  4553. }
  4554. // Reports whether anything is still listening on a loopback port. A plain
  4555. // connect() is used instead of a Client request because a socket left bound by
  4556. // mistake accepts the connection into its backlog and never answers, which
  4557. // would hang the test instead of failing it.
  4558. static bool is_loopback_port_accepting(int port) {
  4559. sockaddr_in addr{};
  4560. addr.sin_family = AF_INET;
  4561. addr.sin_port = htons(static_cast<uint16_t>(port));
  4562. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4563. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4564. EXPECT_NE(sock, INVALID_SOCKET);
  4565. if (sock == INVALID_SOCKET) { return false; }
  4566. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4567. static_cast<socklen_t>(sizeof(addr)));
  4568. detail::close_socket(sock);
  4569. return ret == 0;
  4570. }
  4571. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4572. Server svr;
  4573. auto port = svr.bind_to_any_port("127.0.0.1");
  4574. ASSERT_TRUE(port > 0);
  4575. svr.stop();
  4576. // bind_to_any_port() already called listen(2), so until stop() closed the
  4577. // descriptor the port kept accepting connections into the backlog. ASSERT
  4578. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4579. // below blocks forever in the accept loop.
  4580. ASSERT_FALSE(is_loopback_port_accepting(port));
  4581. // Nothing is left to accept on, so listen_after_bind() must report failure
  4582. // instead of returning success without ever serving.
  4583. EXPECT_FALSE(svr.listen_after_bind());
  4584. // The failed listen marks the server decommissioned, so a waiter returns
  4585. // instead of spinning forever.
  4586. svr.wait_until_ready();
  4587. }
  4588. #ifdef CPPHTTPLIB_SSL_ENABLED
  4589. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4591. CLIENT_CA_CERT_DIR);
  4592. int port = svr.bind_to_any_port("0.0.0.0");
  4593. ASSERT_TRUE(svr.is_valid());
  4594. ASSERT_TRUE(port > 0);
  4595. svr.stop();
  4596. }
  4597. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4598. // or a rejected CustomRoute() registration would not stop the server binding.
  4599. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4600. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4601. CLIENT_CA_CERT_DIR);
  4602. ASSERT_TRUE(svr.is_valid());
  4603. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4604. EXPECT_FALSE(svr.is_valid());
  4605. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4606. }
  4607. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4608. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4609. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4610. int port = svr.bind_to_any_port("0.0.0.0");
  4611. ASSERT_TRUE(svr.is_valid());
  4612. ASSERT_TRUE(port > 0);
  4613. svr.stop();
  4614. }
  4615. TEST(BindServerTest, UpdateCertsPem) {
  4616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4617. int port = svr.bind_to_any_port("0.0.0.0");
  4618. ASSERT_TRUE(svr.is_valid());
  4619. ASSERT_TRUE(port > 0);
  4620. // Read PEM files
  4621. std::string cert_pem, key_pem, ca_pem;
  4622. read_file(SERVER_CERT_FILE, cert_pem);
  4623. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4624. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4625. // Update server certificates using PEM API
  4626. ASSERT_TRUE(
  4627. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4628. ASSERT_TRUE(svr.is_valid());
  4629. svr.stop();
  4630. }
  4631. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4632. // Start server with client CA (enables client auth)
  4633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4634. ASSERT_TRUE(svr.is_valid());
  4635. bool handler_called = false;
  4636. svr.Get("/test", [&](const Request &req, Response &res) {
  4637. handler_called = true;
  4638. // Verify client certificate is present
  4639. auto cert = req.peer_cert();
  4640. EXPECT_TRUE(static_cast<bool>(cert));
  4641. res.set_content("ok", "text/plain");
  4642. });
  4643. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4644. auto se = detail::scope_exit([&] {
  4645. svr.stop();
  4646. t.join();
  4647. ASSERT_FALSE(svr.is_running());
  4648. });
  4649. svr.wait_until_ready();
  4650. // Read PEM files
  4651. std::string cert_pem, key_pem, ca_pem;
  4652. read_file(SERVER_CERT_FILE, cert_pem);
  4653. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4654. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4655. // Update server certificates and client CA using PEM API while server running
  4656. ASSERT_TRUE(
  4657. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4658. // Connect with client certificate
  4659. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4660. cli.enable_server_certificate_verification(false);
  4661. cli.set_connection_timeout(30);
  4662. auto res = cli.Get("/test");
  4663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4664. ASSERT_EQ(StatusCode::OK_200, res->status);
  4665. ASSERT_TRUE(handler_called);
  4666. EXPECT_EQ("ok", res->body);
  4667. }
  4668. // Puts a CA that did not sign the client's certificate in the old one's place.
  4669. static bool replace_client_ca(SSLServer &svr) {
  4670. std::string cert_pem, key_pem, ca_pem;
  4671. read_file(SERVER_CERT_FILE, cert_pem);
  4672. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4673. read_file(SERVER_CERT2_FILE, ca_pem);
  4674. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4675. ca_pem.c_str());
  4676. }
  4677. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4678. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4679. ASSERT_TRUE(svr.is_valid());
  4680. svr.Get("/test", [](const Request &, Response &res) {
  4681. res.set_content("ok", "text/plain");
  4682. });
  4683. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4684. auto se = detail::scope_exit([&] {
  4685. svr.stop();
  4686. t.join();
  4687. ASSERT_FALSE(svr.is_running());
  4688. });
  4689. svr.wait_until_ready();
  4690. auto get = [] {
  4691. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4692. cli.enable_server_certificate_verification(false);
  4693. return cli.Get("/test");
  4694. };
  4695. ASSERT_TRUE(get());
  4696. ASSERT_TRUE(replace_client_ca(svr));
  4697. EXPECT_FALSE(get());
  4698. }
  4699. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4700. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4702. ASSERT_TRUE(svr.is_valid());
  4703. tls::set_verify_callback(svr.tls_context(),
  4704. [](const tls::VerifyContext &) -> bool {
  4705. throw std::runtime_error("verify");
  4706. });
  4707. svr.Get("/test", [](const Request &, Response &res) {
  4708. res.set_content("ok", "text/plain");
  4709. });
  4710. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4711. auto se = detail::scope_exit([&] {
  4712. svr.stop();
  4713. t.join();
  4714. ASSERT_FALSE(svr.is_running());
  4715. });
  4716. svr.wait_until_ready();
  4717. auto get = [] {
  4718. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4719. cli.enable_server_certificate_verification(false);
  4720. return cli.Get("/test");
  4721. };
  4722. EXPECT_FALSE(get());
  4723. // The handshake is over, so an update does not wait for it.
  4724. std::string cert_pem, key_pem;
  4725. read_file(SERVER_CERT_FILE, cert_pem);
  4726. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4727. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4728. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4729. return v.preverify_ok;
  4730. });
  4731. auto res = get();
  4732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4733. EXPECT_EQ("ok", res->body);
  4734. }
  4735. #endif
  4736. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4737. // Sends each request over a new connection with a client certificate,
  4738. // resuming the session of the one before when there is one.
  4739. class ResumingClient {
  4740. public:
  4741. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4742. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4743. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4744. SSL_FILETYPE_PEM);
  4745. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4746. // callback, not through SSL_get1_session().
  4747. SSL_CTX_set_app_data(ctx_, this);
  4748. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4749. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4750. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4751. auto self = static_cast<ResumingClient *>(
  4752. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4753. SSL_SESSION_free(self->session_);
  4754. self->session_ = session;
  4755. return 1; // Keeps the reference
  4756. });
  4757. }
  4758. ~ResumingClient() {
  4759. SSL_SESSION_free(session_);
  4760. SSL_CTX_free(ctx_);
  4761. }
  4762. // Tells whether the request was answered.
  4763. bool get() {
  4764. auto error = Error::Success;
  4765. auto sock = detail::create_client_socket(
  4766. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4767. /*connection_timeout_sec=*/5, 0,
  4768. /*read_timeout_sec=*/5, 0,
  4769. /*write_timeout_sec=*/5, 0, std::string(), error);
  4770. if (sock == INVALID_SOCKET) { return false; }
  4771. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4772. auto ssl = SSL_new(ctx_);
  4773. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4774. SSL_set_fd(ssl, static_cast<int>(sock));
  4775. if (session_) { SSL_set_session(ssl, session_); }
  4776. if (SSL_connect(ssl) != 1) { return false; }
  4777. reused_ = SSL_session_reused(ssl) == 1;
  4778. // Reading the response also takes in a TLS 1.3 session ticket.
  4779. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4780. "Connection: close\r\n\r\n";
  4781. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4782. std::string res;
  4783. char buf[256];
  4784. int n;
  4785. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4786. res.append(buf, static_cast<size_t>(n));
  4787. }
  4788. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4789. SSL_shutdown(ssl);
  4790. return res.find("200 OK") != std::string::npos;
  4791. }
  4792. // Whether the last connection resumed a session
  4793. bool reused() const { return reused_; }
  4794. private:
  4795. SSL_CTX *ctx_;
  4796. SSL_SESSION *session_ = nullptr;
  4797. bool reused_ = false;
  4798. };
  4799. // A client that resumes its session gets through, but not once the client CA
  4800. // has changed, as a resumed session does not show the certificate again.
  4801. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4802. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4803. ASSERT_TRUE(svr.is_valid());
  4804. svr.Get("/test", [](const Request &, Response &res) {
  4805. res.set_content("ok", "text/plain");
  4806. });
  4807. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4808. auto se = detail::scope_exit([&] {
  4809. svr.stop();
  4810. t.join();
  4811. ASSERT_FALSE(svr.is_running());
  4812. });
  4813. svr.wait_until_ready();
  4814. ResumingClient cli;
  4815. ASSERT_TRUE(cli.get());
  4816. ASSERT_TRUE(cli.get());
  4817. EXPECT_TRUE(cli.reused());
  4818. ASSERT_TRUE(replace_client_ca(svr));
  4819. EXPECT_FALSE(cli.get());
  4820. }
  4821. // A resumed session does not show the certificate again, so the server does
  4822. // not resume one with a verify callback to run on it.
  4823. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4824. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4825. ASSERT_TRUE(svr.is_valid());
  4826. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4827. return v.preverify_ok;
  4828. });
  4829. svr.Get("/test", [](const Request &, Response &res) {
  4830. res.set_content("ok", "text/plain");
  4831. });
  4832. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4833. auto se = detail::scope_exit([&] {
  4834. svr.stop();
  4835. t.join();
  4836. ASSERT_FALSE(svr.is_running());
  4837. });
  4838. svr.wait_until_ready();
  4839. ResumingClient cli;
  4840. ASSERT_TRUE(cli.get());
  4841. ASSERT_TRUE(cli.get());
  4842. EXPECT_FALSE(cli.reused());
  4843. }
  4844. #endif
  4845. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4846. // wolfSSL shares its session cache between contexts, so a resumed session
  4847. // could carry a client certificate checked against another server's CA, or
  4848. // against a client CA since replaced.
  4849. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4851. ASSERT_TRUE(svr.is_valid());
  4852. // Trusts a CA that did not sign the client's certificate.
  4853. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4854. ASSERT_TRUE(other.is_valid());
  4855. for (auto s : {&svr, &other}) {
  4856. s->Get("/test", [](const Request &, Response &res) {
  4857. res.set_content("ok", "text/plain");
  4858. });
  4859. }
  4860. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4861. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4862. auto se = detail::scope_exit([&] {
  4863. other.stop();
  4864. svr.stop();
  4865. t2.join();
  4866. t.join();
  4867. });
  4868. svr.wait_until_ready();
  4869. other.wait_until_ready();
  4870. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4871. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4872. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4873. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4874. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4875. ASSERT_EQ(WOLFSSL_SUCCESS,
  4876. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4877. WOLFSSL_FILETYPE_PEM));
  4878. WOLFSSL_SESSION *session = nullptr;
  4879. auto session_se = detail::scope_exit([&] {
  4880. if (session) { wolfSSL_SESSION_free(session); }
  4881. });
  4882. // A request over a new connection, resuming `session` when there is one and
  4883. // keeping the connection's own in its place. Tells whether it was answered.
  4884. auto get = [&](int port) {
  4885. auto error = Error::Success;
  4886. auto sock = detail::create_client_socket(
  4887. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4888. /*connection_timeout_sec=*/5, 0,
  4889. /*read_timeout_sec=*/5, 0,
  4890. /*write_timeout_sec=*/5, 0, std::string(), error);
  4891. if (sock == INVALID_SOCKET) { return false; }
  4892. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4893. auto ssl = wolfSSL_new(ctx);
  4894. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4895. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4896. if (session) { wolfSSL_set_session(ssl, session); }
  4897. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4898. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4899. "Connection: close\r\n\r\n";
  4900. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4901. std::string res;
  4902. char buf[256];
  4903. int n;
  4904. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4905. res.append(buf, static_cast<size_t>(n));
  4906. }
  4907. wolfSSL_shutdown(ssl);
  4908. if (session) { wolfSSL_SESSION_free(session); }
  4909. session = wolfSSL_get1_session(ssl);
  4910. return res.find("200 OK") != std::string::npos;
  4911. };
  4912. ASSERT_TRUE(get(PORT));
  4913. EXPECT_FALSE(get(PORT + 1));
  4914. ASSERT_TRUE(get(PORT));
  4915. ASSERT_TRUE(replace_client_ca(svr));
  4916. EXPECT_FALSE(get(PORT));
  4917. }
  4918. #endif
  4919. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4920. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4921. ASSERT_TRUE(svr.is_valid());
  4922. svr.Get("/test", [](const Request &, Response &res) {
  4923. res.set_content("ok", "text/plain");
  4924. });
  4925. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4926. auto se = detail::scope_exit([&] {
  4927. svr.stop();
  4928. t.join();
  4929. ASSERT_FALSE(svr.is_running());
  4930. });
  4931. svr.wait_until_ready();
  4932. // A connection that sends no ClientHello keeps its handshake in progress,
  4933. // once the server has had a moment to start it.
  4934. auto error = Error::Success;
  4935. auto sock = detail::create_client_socket(
  4936. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4937. /*connection_timeout_sec=*/5, 0,
  4938. /*read_timeout_sec=*/5, 0,
  4939. /*write_timeout_sec=*/5, 0, std::string(), error);
  4940. ASSERT_NE(INVALID_SOCKET, sock);
  4941. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4942. std::string cert_pem, key_pem;
  4943. read_file(SERVER_CERT_FILE, cert_pem);
  4944. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4945. auto update = std::async(std::launch::async, [&]() {
  4946. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4947. });
  4948. EXPECT_EQ(std::future_status::timeout,
  4949. update.wait_for(std::chrono::milliseconds(200)));
  4950. detail::close_socket(sock);
  4951. EXPECT_TRUE(update.get());
  4952. SSLClient cli(HOST, PORT);
  4953. cli.enable_server_certificate_verification(false);
  4954. auto res = cli.Get("/test");
  4955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4956. EXPECT_EQ(StatusCode::OK_200, res->status);
  4957. }
  4958. #endif
  4959. TEST(ErrorHandlerTest, ContentLength) {
  4960. Server svr;
  4961. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4962. res.status = StatusCode::OK_200;
  4963. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4964. "text/html"); // <= Content-Length still 13
  4965. });
  4966. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4967. res.set_content("Hello World!\n", "text/plain");
  4968. res.status = 524;
  4969. });
  4970. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4971. auto se = detail::scope_exit([&] {
  4972. svr.stop();
  4973. thread.join();
  4974. ASSERT_FALSE(svr.is_running());
  4975. });
  4976. svr.wait_until_ready();
  4977. {
  4978. Client cli(HOST, PORT);
  4979. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4981. EXPECT_EQ(StatusCode::OK_200, res->status);
  4982. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4983. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4984. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4985. }
  4986. }
  4987. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4988. TEST(ExceptionTest, WithoutExceptionHandler) {
  4989. Server svr;
  4990. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4991. throw std::runtime_error("exception...");
  4992. });
  4993. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4994. throw std::runtime_error("exception\r\n...");
  4995. });
  4996. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4997. auto se = detail::scope_exit([&] {
  4998. svr.stop();
  4999. listen_thread.join();
  5000. ASSERT_FALSE(svr.is_running());
  5001. });
  5002. svr.wait_until_ready();
  5003. Client cli("localhost", PORT);
  5004. {
  5005. auto res = cli.Get("/exception");
  5006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5007. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5008. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5009. }
  5010. {
  5011. auto res = cli.Get("/unknown");
  5012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5013. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5014. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5015. }
  5016. }
  5017. TEST(ExceptionTest, WithExceptionHandler) {
  5018. Server svr;
  5019. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5020. std::exception_ptr ep) {
  5021. EXPECT_FALSE(ep == nullptr);
  5022. try {
  5023. std::rethrow_exception(ep);
  5024. } catch (std::exception &e) {
  5025. EXPECT_EQ("abc", std::string(e.what()));
  5026. } catch (...) {}
  5027. res.status = StatusCode::InternalServerError_500;
  5028. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5029. "text/html"); // <= Content-Length still 13 at this point
  5030. });
  5031. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5032. res.set_content("Hello World!\n", "text/plain");
  5033. throw std::runtime_error("abc");
  5034. });
  5035. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5036. auto se = detail::scope_exit([&] {
  5037. svr.stop();
  5038. thread.join();
  5039. ASSERT_FALSE(svr.is_running());
  5040. });
  5041. svr.wait_until_ready();
  5042. for (size_t i = 0; i < 10; i++) {
  5043. Client cli(HOST, PORT);
  5044. for (size_t j = 0; j < 100; j++) {
  5045. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5047. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5048. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5049. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5050. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5051. }
  5052. cli.set_keep_alive(true);
  5053. for (size_t j = 0; j < 100; j++) {
  5054. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5056. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5057. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5058. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5059. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5060. }
  5061. }
  5062. }
  5063. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5064. Server svr;
  5065. svr.set_exception_handler(
  5066. [](const Request &, Response &res, std::exception_ptr) {
  5067. res.set_content("oops", "text/plain");
  5068. });
  5069. svr.Get("/throw", [](const Request &, Response &) {
  5070. throw std::runtime_error("throw");
  5071. });
  5072. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5073. res.status = StatusCode::Created_201;
  5074. throw std::runtime_error("created-then-throw");
  5075. });
  5076. auto port = svr.bind_to_any_port(HOST);
  5077. ASSERT_GT(port, 0);
  5078. thread t = thread([&] { svr.listen_after_bind(); });
  5079. auto se = detail::scope_exit([&] {
  5080. svr.stop();
  5081. t.join();
  5082. ASSERT_FALSE(svr.is_running());
  5083. });
  5084. svr.wait_until_ready();
  5085. Client cli(HOST, port);
  5086. for (auto path : {"/throw", "/created-then-throw"}) {
  5087. auto res = cli.Get(path);
  5088. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5089. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5090. }
  5091. }
  5092. TEST(ExceptionTest, AndErrorHandler) {
  5093. Server svr;
  5094. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5095. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5096. });
  5097. svr.set_exception_handler(
  5098. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5099. EXPECT_FALSE(ep == nullptr);
  5100. try {
  5101. std::rethrow_exception(ep);
  5102. } catch (std::exception &e) {
  5103. res.set_content(e.what(), "text/html");
  5104. } catch (...) {}
  5105. res.status = StatusCode::InternalServerError_500;
  5106. });
  5107. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5108. throw std::runtime_error("EXCEPTION");
  5109. });
  5110. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5111. res.set_content("ERROR", "text/html");
  5112. res.status = StatusCode::InternalServerError_500;
  5113. });
  5114. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5115. auto se = detail::scope_exit([&] {
  5116. svr.stop();
  5117. thread.join();
  5118. ASSERT_FALSE(svr.is_running());
  5119. });
  5120. svr.wait_until_ready();
  5121. Client cli(HOST, PORT);
  5122. {
  5123. auto res = cli.Get("/exception");
  5124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5125. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5126. EXPECT_EQ("EXCEPTION", res->body);
  5127. }
  5128. {
  5129. auto res = cli.Get("/error");
  5130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5131. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5132. EXPECT_EQ("ERROR", res->body);
  5133. }
  5134. {
  5135. auto res = cli.Get("/invalid");
  5136. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5137. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5138. EXPECT_EQ("NOT_FOUND", res->body);
  5139. }
  5140. }
  5141. #endif
  5142. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5143. // An exception from a user callback outside process_request()'s try/catch
  5144. // used to unwind into the task queue - which does not catch - and terminate
  5145. // the process. Each test below runs the server on a single worker thread: a
  5146. // guard that catches the exception but still loses the thread would otherwise
  5147. // be hidden by a spare worker serving the follow-up request. Note that a
  5148. // regression here aborts the whole test binary rather than failing one test.
  5149. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5150. Server svr;
  5151. svr.new_task_queue = [] { return new ThreadPool(1); };
  5152. std::atomic<int> reported{0};
  5153. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5154. if (err == Error::UserCallbackException) { reported++; }
  5155. });
  5156. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5157. res.set_content_provider(
  5158. 1024, "text/plain",
  5159. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5160. sink.write("hello", 5);
  5161. throw std::runtime_error("from the content provider");
  5162. });
  5163. });
  5164. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5165. res.set_content("ok", "text/plain");
  5166. });
  5167. auto port = svr.bind_to_any_port(HOST);
  5168. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5169. auto se = detail::scope_exit([&] {
  5170. svr.stop();
  5171. listen_thread.join();
  5172. ASSERT_FALSE(svr.is_running());
  5173. });
  5174. svr.wait_until_ready();
  5175. {
  5176. Client cli(HOST, port);
  5177. cli.set_read_timeout(5, 0);
  5178. EXPECT_FALSE(cli.Get("/throw"));
  5179. }
  5180. EXPECT_TRUE(svr.is_running());
  5181. EXPECT_EQ(1, reported.load());
  5182. // A request on a fresh connection is still served.
  5183. {
  5184. Client cli(HOST, port);
  5185. auto res = cli.Get("/ok");
  5186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5187. EXPECT_EQ(StatusCode::OK_200, res->status);
  5188. EXPECT_EQ("ok", res->body);
  5189. }
  5190. }
  5191. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5192. Server svr;
  5193. svr.new_task_queue = [] { return new ThreadPool(1); };
  5194. std::atomic<bool> should_throw{true};
  5195. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5196. res.set_content("hi", "text/plain");
  5197. });
  5198. svr.set_post_routing_handler(
  5199. [&](const Request & /*req*/, Response & /*res*/) {
  5200. if (should_throw) {
  5201. throw std::runtime_error("from the post-routing handler");
  5202. }
  5203. });
  5204. auto port = svr.bind_to_any_port(HOST);
  5205. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5206. auto se = detail::scope_exit([&] {
  5207. svr.stop();
  5208. listen_thread.join();
  5209. ASSERT_FALSE(svr.is_running());
  5210. });
  5211. svr.wait_until_ready();
  5212. {
  5213. Client cli(HOST, port);
  5214. cli.set_read_timeout(5, 0);
  5215. EXPECT_FALSE(cli.Get("/hi"));
  5216. }
  5217. EXPECT_TRUE(svr.is_running());
  5218. should_throw = false;
  5219. {
  5220. Client cli(HOST, port);
  5221. auto res = cli.Get("/hi");
  5222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5223. EXPECT_EQ(StatusCode::OK_200, res->status);
  5224. EXPECT_EQ("hi", res->body);
  5225. }
  5226. }
  5227. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5228. // The guard reports the caught exception through the error logger, which is
  5229. // a user callback too. A logger that throws has to be contained as well, or
  5230. // the process would terminate from inside the catch.
  5231. Server svr;
  5232. svr.new_task_queue = [] { return new ThreadPool(1); };
  5233. std::atomic<int> reported{0};
  5234. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5235. if (err == Error::UserCallbackException) {
  5236. reported++;
  5237. throw std::runtime_error("from the error logger");
  5238. }
  5239. });
  5240. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5241. res.set_content_provider(
  5242. 1024, "text/plain",
  5243. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5244. sink.write("hello", 5);
  5245. throw std::runtime_error("from the content provider");
  5246. });
  5247. });
  5248. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5249. res.set_content("ok", "text/plain");
  5250. });
  5251. auto port = svr.bind_to_any_port(HOST);
  5252. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5253. auto se = detail::scope_exit([&] {
  5254. svr.stop();
  5255. listen_thread.join();
  5256. ASSERT_FALSE(svr.is_running());
  5257. });
  5258. svr.wait_until_ready();
  5259. {
  5260. Client cli(HOST, port);
  5261. cli.set_read_timeout(5, 0);
  5262. EXPECT_FALSE(cli.Get("/throw"));
  5263. }
  5264. EXPECT_TRUE(svr.is_running());
  5265. EXPECT_EQ(1, reported.load());
  5266. {
  5267. Client cli(HOST, port);
  5268. auto res = cli.Get("/ok");
  5269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5270. EXPECT_EQ(StatusCode::OK_200, res->status);
  5271. EXPECT_EQ("ok", res->body);
  5272. }
  5273. }
  5274. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5275. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5276. // so the exception unwinds through the ws::WebSocket object on its way to
  5277. // the guard. None of the HTTP cases above cross that.
  5278. Server svr;
  5279. svr.new_task_queue = [] { return new ThreadPool(1); };
  5280. std::atomic<int> reported{0};
  5281. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5282. if (err == Error::UserCallbackException) { reported++; }
  5283. });
  5284. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5285. throw std::runtime_error("from the WebSocket handler");
  5286. });
  5287. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5288. res.set_content("ok", "text/plain");
  5289. });
  5290. auto port = svr.bind_to_any_port(HOST);
  5291. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5292. auto se = detail::scope_exit([&] {
  5293. svr.stop();
  5294. listen_thread.join();
  5295. ASSERT_FALSE(svr.is_running());
  5296. });
  5297. svr.wait_until_ready();
  5298. {
  5299. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5300. "/ws");
  5301. auto res = client.connect();
  5302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5303. // The server dropped the connection instead of dying.
  5304. std::string msg;
  5305. EXPECT_FALSE(client.read(msg));
  5306. client.close();
  5307. }
  5308. EXPECT_TRUE(svr.is_running());
  5309. EXPECT_EQ(1, reported.load());
  5310. {
  5311. Client cli(HOST, port);
  5312. auto res = cli.Get("/ok");
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. EXPECT_EQ(StatusCode::OK_200, res->status);
  5315. EXPECT_EQ("ok", res->body);
  5316. }
  5317. }
  5318. #ifdef CPPHTTPLIB_SSL_ENABLED
  5319. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5320. // SSLServer::process_and_close_socket() is a separate overload with its own
  5321. // guard, so it is exercised on its own.
  5322. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5323. ASSERT_TRUE(svr.is_valid());
  5324. svr.new_task_queue = [] { return new ThreadPool(1); };
  5325. std::atomic<int> reported{0};
  5326. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5327. if (err == Error::UserCallbackException) { reported++; }
  5328. });
  5329. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5330. res.set_content_provider(
  5331. 1024, "text/plain",
  5332. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5333. sink.write("hello", 5);
  5334. throw std::runtime_error("from the content provider");
  5335. });
  5336. });
  5337. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5338. res.set_content("ok", "text/plain");
  5339. });
  5340. auto port = svr.bind_to_any_port(HOST);
  5341. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5342. auto se = detail::scope_exit([&] {
  5343. svr.stop();
  5344. listen_thread.join();
  5345. ASSERT_FALSE(svr.is_running());
  5346. });
  5347. svr.wait_until_ready();
  5348. {
  5349. SSLClient cli(HOST, port);
  5350. cli.enable_server_certificate_verification(false);
  5351. cli.set_read_timeout(5, 0);
  5352. EXPECT_FALSE(cli.Get("/throw"));
  5353. }
  5354. EXPECT_TRUE(svr.is_running());
  5355. EXPECT_EQ(1, reported.load());
  5356. {
  5357. SSLClient cli(HOST, port);
  5358. cli.enable_server_certificate_verification(false);
  5359. auto res = cli.Get("/ok");
  5360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5361. EXPECT_EQ(StatusCode::OK_200, res->status);
  5362. EXPECT_EQ("ok", res->body);
  5363. }
  5364. }
  5365. #endif
  5366. #endif
  5367. TEST(NoContentTest, ContentLength) {
  5368. Server svr;
  5369. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5370. res.status = StatusCode::NoContent_204;
  5371. });
  5372. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5373. auto se = detail::scope_exit([&] {
  5374. svr.stop();
  5375. thread.join();
  5376. ASSERT_FALSE(svr.is_running());
  5377. });
  5378. svr.wait_until_ready();
  5379. {
  5380. Client cli(HOST, PORT);
  5381. auto res = cli.Get("/hi");
  5382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5383. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5384. // RFC 9110 8.6: none in a 204 response
  5385. EXPECT_FALSE(res->has_header("Content-Length"));
  5386. }
  5387. }
  5388. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5389. Server svr;
  5390. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5391. res.set_header("Content-Length", "5");
  5392. res.set_content("hello world", "text/plain");
  5393. });
  5394. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5395. // A body that reads as the last chunk, were it taken as chunked
  5396. res.set_header("Transfer-Encoding", "chunked");
  5397. res.set_content("0\r\n\r\n", "text/plain");
  5398. });
  5399. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5400. res.set_header("Content-Length", "2");
  5401. res.set_content_provider(5, "text/plain",
  5402. [](size_t offset, size_t length, DataSink &sink) {
  5403. sink.write(&"hello"[offset], length);
  5404. return true;
  5405. });
  5406. });
  5407. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5408. res.set_header("Content-Length", "1234");
  5409. });
  5410. thread t = thread([&] { svr.listen(HOST, PORT); });
  5411. auto se = detail::scope_exit([&] {
  5412. svr.stop();
  5413. t.join();
  5414. ASSERT_FALSE(svr.is_running());
  5415. });
  5416. svr.wait_until_ready();
  5417. Client cli(HOST, PORT);
  5418. cli.set_read_timeout(1, 0);
  5419. auto expect_body = [&](const Result &res, const std::string &body) {
  5420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5421. EXPECT_EQ(body, res->body);
  5422. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5423. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5424. };
  5425. Headers identity{{"Accept-Encoding", ""}};
  5426. expect_body(cli.Get("/body", identity), "hello world");
  5427. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5428. expect_body(cli.Get("/body",
  5429. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5430. "he");
  5431. expect_body(cli.Get("/provider", identity), "hello");
  5432. expect_body(cli.Get("/empty", identity), "");
  5433. // A HEAD response may give the length of the body a GET would get.
  5434. auto res = cli.Head("/empty");
  5435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5436. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5437. }
  5438. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5439. Server svr;
  5440. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5441. res.set_content("short", "text/plain");
  5442. });
  5443. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5444. res.body += " with a footer";
  5445. res.set_header("Transfer-Encoding", "chunked");
  5446. });
  5447. thread t = thread([&] { svr.listen(HOST, PORT); });
  5448. auto se = detail::scope_exit([&] {
  5449. svr.stop();
  5450. t.join();
  5451. ASSERT_FALSE(svr.is_running());
  5452. });
  5453. svr.wait_until_ready();
  5454. Client cli(HOST, PORT);
  5455. cli.set_read_timeout(1, 0);
  5456. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5458. EXPECT_EQ("short with a footer", res->body);
  5459. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5460. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5461. }
  5462. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5463. Server svr;
  5464. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5465. res.set_header("Content-Length", "3");
  5466. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5467. sink.write("abc", 3);
  5468. sink.done();
  5469. return true;
  5470. });
  5471. });
  5472. thread t = thread([&] { svr.listen(HOST, PORT); });
  5473. auto se = detail::scope_exit([&] {
  5474. svr.stop();
  5475. t.join();
  5476. ASSERT_FALSE(svr.is_running());
  5477. });
  5478. svr.wait_until_ready();
  5479. Client cli(HOST, PORT);
  5480. cli.set_keep_alive(true);
  5481. auto res = cli.Get("/");
  5482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5483. EXPECT_EQ("abc", res->body);
  5484. EXPECT_FALSE(res->has_header("Content-Length"));
  5485. EXPECT_EQ("close", res->get_header_value("Connection"));
  5486. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5487. // No body to delimit
  5488. auto head = cli.Head("/");
  5489. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5490. EXPECT_FALSE(head->has_header("Connection"));
  5491. }
  5492. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5493. #ifdef CPPHTTPLIB_SSL_ENABLED
  5494. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5495. ASSERT_TRUE(svr.is_valid());
  5496. #else
  5497. Server svr;
  5498. #endif
  5499. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5500. if (req.path == "/routing_handler") {
  5501. res.set_header("PRE_ROUTING", "on");
  5502. res.set_content("Routing Handler", "text/plain");
  5503. return httplib::Server::HandlerResponse::Handled;
  5504. }
  5505. return httplib::Server::HandlerResponse::Unhandled;
  5506. });
  5507. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5508. res.set_content("Error", "text/html");
  5509. });
  5510. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5511. if (req.path == "/routing_handler") {
  5512. res.set_header("POST_ROUTING", "on");
  5513. }
  5514. });
  5515. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5516. res.set_content("Hello World!\n", "text/plain");
  5517. });
  5518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5519. auto se = detail::scope_exit([&] {
  5520. svr.stop();
  5521. thread.join();
  5522. ASSERT_FALSE(svr.is_running());
  5523. });
  5524. svr.wait_until_ready();
  5525. {
  5526. #ifdef CPPHTTPLIB_SSL_ENABLED
  5527. SSLClient cli(HOST, PORT);
  5528. cli.enable_server_certificate_verification(false);
  5529. #else
  5530. Client cli(HOST, PORT);
  5531. #endif
  5532. auto res = cli.Get("/routing_handler");
  5533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5534. EXPECT_EQ(StatusCode::OK_200, res->status);
  5535. EXPECT_EQ("Routing Handler", res->body);
  5536. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5537. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5538. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5539. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5540. }
  5541. {
  5542. #ifdef CPPHTTPLIB_SSL_ENABLED
  5543. SSLClient cli(HOST, PORT);
  5544. cli.enable_server_certificate_verification(false);
  5545. #else
  5546. Client cli(HOST, PORT);
  5547. #endif
  5548. auto res = cli.Get("/hi");
  5549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5550. EXPECT_EQ(StatusCode::OK_200, res->status);
  5551. EXPECT_EQ("Hello World!\n", res->body);
  5552. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5553. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5554. }
  5555. {
  5556. #ifdef CPPHTTPLIB_SSL_ENABLED
  5557. SSLClient cli(HOST, PORT);
  5558. cli.enable_server_certificate_verification(false);
  5559. #else
  5560. Client cli(HOST, PORT);
  5561. #endif
  5562. auto res = cli.Get("/aaa");
  5563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5564. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5565. EXPECT_EQ("Error", res->body);
  5566. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5567. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5568. }
  5569. }
  5570. TEST(RequestHandlerTest, PreRequestHandler) {
  5571. auto route_path = "/user/:user";
  5572. Server svr;
  5573. svr.Get("/hi", [](const Request &, Response &res) {
  5574. res.set_content("hi", "text/plain");
  5575. });
  5576. svr.Get(route_path, [](const Request &req, Response &res) {
  5577. res.set_content(req.path_params.at("user"), "text/plain");
  5578. });
  5579. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5580. if (req.matched_route == route_path) {
  5581. auto user = req.path_params.at("user");
  5582. if (user != "john") {
  5583. res.status = StatusCode::Forbidden_403;
  5584. res.set_content("error", "text/html");
  5585. return Server::HandlerResponse::Handled;
  5586. }
  5587. }
  5588. return Server::HandlerResponse::Unhandled;
  5589. });
  5590. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5591. auto se = detail::scope_exit([&] {
  5592. svr.stop();
  5593. thread.join();
  5594. ASSERT_FALSE(svr.is_running());
  5595. });
  5596. svr.wait_until_ready();
  5597. Client cli(HOST, PORT);
  5598. {
  5599. auto res = cli.Get("/hi");
  5600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5601. EXPECT_EQ(StatusCode::OK_200, res->status);
  5602. EXPECT_EQ("hi", res->body);
  5603. }
  5604. {
  5605. auto res = cli.Get("/user/john");
  5606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5607. EXPECT_EQ(StatusCode::OK_200, res->status);
  5608. EXPECT_EQ("john", res->body);
  5609. }
  5610. {
  5611. auto res = cli.Get("/user/invalid-user");
  5612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5613. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5614. EXPECT_EQ("error", res->body);
  5615. }
  5616. }
  5617. // The pre-request handler must run before the request body is read, so a
  5618. // rejected request never forces the server to buffer a (potentially large)
  5619. // body. Here the posted body is larger than the payload limit: if the body
  5620. // were read first the server would answer 413, but because the pre-request
  5621. // handler runs first it answers 403 and the body is never read.
  5622. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5623. Server svr;
  5624. svr.set_payload_max_length(8);
  5625. auto handler_ran = false;
  5626. svr.Post("/reject", [&](const Request &req, Response &res) {
  5627. handler_ran = true;
  5628. res.set_content(req.body, "text/plain");
  5629. });
  5630. svr.Post("/accept", [](const Request &req, Response &res) {
  5631. res.set_content(req.body, "text/plain");
  5632. });
  5633. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5634. if (req.matched_route == "/reject") {
  5635. res.status = StatusCode::Forbidden_403;
  5636. res.set_content("denied", "text/plain");
  5637. return Server::HandlerResponse::Handled;
  5638. }
  5639. return Server::HandlerResponse::Unhandled;
  5640. });
  5641. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5642. auto se = detail::scope_exit([&] {
  5643. svr.stop();
  5644. thread.join();
  5645. ASSERT_FALSE(svr.is_running());
  5646. });
  5647. svr.wait_until_ready();
  5648. Client cli(HOST, PORT);
  5649. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5650. // rejects with 403 before the body is read, so 413 is never reached.
  5651. {
  5652. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5654. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5655. EXPECT_EQ("denied", res->body);
  5656. EXPECT_FALSE(handler_ran);
  5657. }
  5658. // An approved route still reads the body and enforces the payload limit.
  5659. {
  5660. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5662. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5663. }
  5664. }
  5665. TEST(UserDataTest, BasicOperations) {
  5666. httplib::UserData ud;
  5667. // Initially empty
  5668. EXPECT_FALSE(ud.has("key"));
  5669. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5670. // set and get
  5671. ud.set("key", 42);
  5672. EXPECT_TRUE(ud.has("key"));
  5673. auto *p = ud.get<int>("key");
  5674. ASSERT_NE(nullptr, p);
  5675. EXPECT_EQ(42, *p);
  5676. // Type mismatch → nullptr
  5677. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5678. // Overwrite with different type
  5679. ud.set("key", std::string("hello"));
  5680. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5681. auto *s = ud.get<std::string>("key");
  5682. ASSERT_NE(nullptr, s);
  5683. EXPECT_EQ("hello", *s);
  5684. // erase
  5685. ud.erase("key");
  5686. EXPECT_FALSE(ud.has("key"));
  5687. // clear
  5688. ud.set("a", 1);
  5689. ud.set("b", 2);
  5690. ud.clear();
  5691. EXPECT_FALSE(ud.has("a"));
  5692. EXPECT_FALSE(ud.has("b"));
  5693. }
  5694. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5695. struct AuthCtx {
  5696. std::string user_id;
  5697. };
  5698. Server svr;
  5699. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5700. res.user_data.set("auth", AuthCtx{"alice"});
  5701. return Server::HandlerResponse::Unhandled;
  5702. });
  5703. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5704. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5705. ASSERT_NE(nullptr, ctx);
  5706. res.set_content("Hello " + ctx->user_id, "text/plain");
  5707. });
  5708. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5709. auto se = detail::scope_exit([&] {
  5710. svr.stop();
  5711. thread.join();
  5712. ASSERT_FALSE(svr.is_running());
  5713. });
  5714. svr.wait_until_ready();
  5715. Client cli(HOST, PORT);
  5716. auto res = cli.Get("/me");
  5717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5718. EXPECT_EQ(StatusCode::OK_200, res->status);
  5719. EXPECT_EQ("Hello alice", res->body);
  5720. }
  5721. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5722. struct RoleCtx {
  5723. std::string role;
  5724. };
  5725. Server svr;
  5726. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5727. res.user_data.set("role", RoleCtx{"admin"});
  5728. return Server::HandlerResponse::Unhandled;
  5729. });
  5730. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5731. auto *ctx = res.user_data.get<RoleCtx>("role");
  5732. ASSERT_NE(nullptr, ctx);
  5733. res.set_content(ctx->role, "text/plain");
  5734. });
  5735. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5736. auto se = detail::scope_exit([&] {
  5737. svr.stop();
  5738. thread.join();
  5739. ASSERT_FALSE(svr.is_running());
  5740. });
  5741. svr.wait_until_ready();
  5742. Client cli(HOST, PORT);
  5743. auto res = cli.Get("/role");
  5744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5745. EXPECT_EQ(StatusCode::OK_200, res->status);
  5746. EXPECT_EQ("admin", res->body);
  5747. }
  5748. TEST(InvalidFormatTest, StatusCode) {
  5749. Server svr;
  5750. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5751. res.set_content("Hello World!\n", "text/plain");
  5752. res.status = 9999; // Status should be a three-digit code...
  5753. });
  5754. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5755. auto se = detail::scope_exit([&] {
  5756. svr.stop();
  5757. thread.join();
  5758. ASSERT_FALSE(svr.is_running());
  5759. });
  5760. svr.wait_until_ready();
  5761. {
  5762. Client cli(HOST, PORT);
  5763. auto res = cli.Get("/hi");
  5764. ASSERT_FALSE(res);
  5765. }
  5766. }
  5767. TEST(URLFragmentTest, WithFragment) {
  5768. Server svr;
  5769. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5770. EXPECT_TRUE(req.target == "/hi");
  5771. });
  5772. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5773. auto se = detail::scope_exit([&] {
  5774. svr.stop();
  5775. thread.join();
  5776. ASSERT_FALSE(svr.is_running());
  5777. });
  5778. svr.wait_until_ready();
  5779. {
  5780. Client cli(HOST, PORT);
  5781. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5782. EXPECT_TRUE(res);
  5783. EXPECT_EQ(StatusCode::OK_200, res->status);
  5784. res = cli.Get("/hi%23key1=val1=key2=val2");
  5785. EXPECT_TRUE(res);
  5786. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5787. }
  5788. }
  5789. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5790. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5791. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5792. Server svr;
  5793. std::vector<std::string> targets;
  5794. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5795. targets.push_back(req.target);
  5796. });
  5797. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5798. auto se = detail::scope_exit([&] {
  5799. svr.stop();
  5800. thread.join();
  5801. ASSERT_FALSE(svr.is_running());
  5802. });
  5803. svr.wait_until_ready();
  5804. Client cli(HOST, PORT);
  5805. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5806. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5807. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5808. // A '?' after the '#' belongs to the fragment, not to the query.
  5809. Request req;
  5810. req.method = "GET";
  5811. req.path = "/hi#f?x=1";
  5812. req.params.emplace("a", "1");
  5813. Response res;
  5814. auto error = Error::Success;
  5815. EXPECT_TRUE(cli.send(req, res, error));
  5816. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5817. "/hi?a=1"}),
  5818. targets);
  5819. }
  5820. TEST(HeaderWriter, SetHeaderWriter) {
  5821. Server svr;
  5822. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5823. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5824. return detail::write_headers(strm, hdrs);
  5825. });
  5826. svr.Get("/hi", [](const Request &req, Response &res) {
  5827. auto it = req.headers.find("CustomClientHeader");
  5828. EXPECT_TRUE(it != req.headers.end());
  5829. EXPECT_EQ(it->second, "CustomClientValue");
  5830. res.set_content("Hello World!\n", "text/plain");
  5831. });
  5832. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5833. auto se = detail::scope_exit([&] {
  5834. svr.stop();
  5835. thread.join();
  5836. ASSERT_FALSE(svr.is_running());
  5837. });
  5838. svr.wait_until_ready();
  5839. {
  5840. Client cli(HOST, PORT);
  5841. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5842. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5843. return detail::write_headers(strm, hdrs);
  5844. });
  5845. auto res = cli.Get("/hi");
  5846. EXPECT_TRUE(res);
  5847. EXPECT_EQ(StatusCode::OK_200, res->status);
  5848. auto it = res->headers.find("CustomServerHeader");
  5849. EXPECT_TRUE(it != res->headers.end());
  5850. EXPECT_EQ(it->second, "CustomServerValue");
  5851. }
  5852. }
  5853. class ServerTest : public ::testing::Test {
  5854. protected:
  5855. ServerTest()
  5856. : cli_(HOST, PORT)
  5857. #ifdef CPPHTTPLIB_SSL_ENABLED
  5858. ,
  5859. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5860. #endif
  5861. {
  5862. #ifdef CPPHTTPLIB_SSL_ENABLED
  5863. cli_.enable_server_certificate_verification(false);
  5864. #endif
  5865. // Allow LARGE_DATA (100MB) responses
  5866. cli_.set_payload_max_length(200 * 1024 * 1024);
  5867. }
  5868. virtual void SetUp() {
  5869. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5870. svr_.set_payload_max_length(200 * 1024 * 1024);
  5871. svr_.set_mount_point("/", "./www");
  5872. svr_.set_mount_point("/mount", "./www2");
  5873. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5874. svr_.Get("/hi",
  5875. [&](const Request & /*req*/, Response &res) {
  5876. res.set_content("Hello World!", "text/plain");
  5877. })
  5878. .Get("/file_content",
  5879. [&](const Request & /*req*/, Response &res) {
  5880. res.set_file_content("./www/dir/test.html");
  5881. })
  5882. .Get("/file_content_with_content_type",
  5883. [&](const Request & /*req*/, Response &res) {
  5884. res.set_file_content("./www/file", "text/plain");
  5885. })
  5886. .Get("/invalid_file_content",
  5887. [&](const Request & /*req*/, Response &res) {
  5888. res.set_file_content("./www/dir/invalid_file_path");
  5889. })
  5890. .Get("/http_response_splitting",
  5891. [&](const Request & /*req*/, Response &res) {
  5892. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5893. EXPECT_EQ(0U, res.headers.size());
  5894. EXPECT_FALSE(res.has_header("a"));
  5895. res.set_header("a", "1\nSet-Cookie: a=1");
  5896. EXPECT_EQ(0U, res.headers.size());
  5897. EXPECT_FALSE(res.has_header("a"));
  5898. res.set_header("a", "1\rSet-Cookie: a=1");
  5899. EXPECT_EQ(0U, res.headers.size());
  5900. EXPECT_FALSE(res.has_header("a"));
  5901. res.set_header("a\r\nb", "0");
  5902. EXPECT_EQ(0U, res.headers.size());
  5903. EXPECT_FALSE(res.has_header("a"));
  5904. res.set_header("a\rb", "0");
  5905. EXPECT_EQ(0U, res.headers.size());
  5906. EXPECT_FALSE(res.has_header("a"));
  5907. res.set_header("a\nb", "0");
  5908. EXPECT_EQ(0U, res.headers.size());
  5909. EXPECT_FALSE(res.has_header("a"));
  5910. res.set_redirect("1\r\nSet-Cookie: a=1");
  5911. EXPECT_EQ(0U, res.headers.size());
  5912. EXPECT_FALSE(res.has_header("Location"));
  5913. })
  5914. .Get("/slow",
  5915. [&](const Request & /*req*/, Response &res) {
  5916. std::this_thread::sleep_for(std::chrono::seconds(4));
  5917. res.set_content("slow", "text/plain");
  5918. })
  5919. #if 0
  5920. .Post("/slowpost",
  5921. [&](const Request & /*req*/, Response &res) {
  5922. std::this_thread::sleep_for(std::chrono::seconds(2));
  5923. res.set_content("slow", "text/plain");
  5924. })
  5925. #endif
  5926. .Get("/remote_addr",
  5927. [&](const Request &req, Response &res) {
  5928. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5929. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5930. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5931. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5932. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5933. #endif
  5934. res.set_content(req.remote_addr, "text/plain");
  5935. })
  5936. .Get("/local_addr",
  5937. [&](const Request &req, Response &res) {
  5938. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5939. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5940. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5941. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5942. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5943. #endif
  5944. auto local_addr = req.local_addr;
  5945. auto local_port = std::to_string(req.local_port);
  5946. res.set_content(local_addr.append(":").append(local_port),
  5947. "text/plain");
  5948. })
  5949. .Get("/endwith%",
  5950. [&](const Request & /*req*/, Response &res) {
  5951. res.set_content("Hello World!", "text/plain");
  5952. })
  5953. .Get("/a\\+\\+b",
  5954. [&](const Request &req, Response &res) {
  5955. ASSERT_TRUE(req.has_param("a +b"));
  5956. auto val = req.get_param_value("a +b");
  5957. res.set_content(val, "text/plain");
  5958. })
  5959. .Get("/", [&](const Request & /*req*/,
  5960. Response &res) { res.set_redirect("/hi"); })
  5961. .Post("/1",
  5962. [](const Request & /*req*/, Response &res) {
  5963. res.set_redirect("/2", StatusCode::SeeOther_303);
  5964. })
  5965. .Get("/2",
  5966. [](const Request & /*req*/, Response &res) {
  5967. res.set_content("redirected.", "text/plain");
  5968. res.status = StatusCode::OK_200;
  5969. })
  5970. .Post("/person",
  5971. [&](const Request &req, Response &res) {
  5972. if (req.has_param("name") && req.has_param("note")) {
  5973. persons_[req.get_param_value("name")] =
  5974. req.get_param_value("note");
  5975. } else {
  5976. res.status = StatusCode::BadRequest_400;
  5977. }
  5978. })
  5979. .Put("/person",
  5980. [&](const Request &req, Response &res) {
  5981. if (req.has_param("name") && req.has_param("note")) {
  5982. persons_[req.get_param_value("name")] =
  5983. req.get_param_value("note");
  5984. } else {
  5985. res.status = StatusCode::BadRequest_400;
  5986. }
  5987. })
  5988. .Get("/person/(.*)",
  5989. [&](const Request &req, Response &res) {
  5990. string name = req.matches[1];
  5991. if (persons_.find(name) != persons_.end()) {
  5992. auto note = persons_[name];
  5993. res.set_content(note, "text/plain");
  5994. } else {
  5995. res.status = StatusCode::NotFound_404;
  5996. }
  5997. })
  5998. .Delete("/person",
  5999. [&](const Request &req, Response &res) {
  6000. if (req.has_param("name")) {
  6001. string name = req.get_param_value("name");
  6002. if (persons_.find(name) != persons_.end()) {
  6003. persons_.erase(name);
  6004. res.set_content("DELETED", "text/plain");
  6005. } else {
  6006. res.status = StatusCode::NotFound_404;
  6007. }
  6008. } else {
  6009. res.status = StatusCode::BadRequest_400;
  6010. }
  6011. })
  6012. .Post("/x-www-form-urlencoded-json",
  6013. [&](const Request &req, Response &res) {
  6014. auto json = req.get_param_value("json");
  6015. ASSERT_EQ(JSON_DATA, json);
  6016. res.set_content(json, "appliation/json");
  6017. res.status = StatusCode::OK_200;
  6018. })
  6019. .Get("/streamed-chunked",
  6020. [&](const Request & /*req*/, Response &res) {
  6021. res.set_chunked_content_provider(
  6022. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6023. sink.os << "123";
  6024. sink.os << "456";
  6025. sink.os << "789";
  6026. sink.done();
  6027. return true;
  6028. });
  6029. })
  6030. .Get("/streamed-chunked-with-prohibited-trailer",
  6031. [&](const Request & /*req*/, Response &res) {
  6032. auto i = new int(0);
  6033. // Declare both a prohibited trailer (Content-Length) and an
  6034. // allowed one
  6035. res.set_header("Trailer", "Content-Length, X-Allowed");
  6036. res.set_chunked_content_provider(
  6037. "text/plain",
  6038. [i](size_t /*offset*/, DataSink &sink) {
  6039. switch (*i) {
  6040. case 0: sink.os << "123"; break;
  6041. case 1: sink.os << "456"; break;
  6042. case 2: sink.os << "789"; break;
  6043. case 3: {
  6044. sink.done_with_trailer(
  6045. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6046. } break;
  6047. }
  6048. (*i)++;
  6049. return true;
  6050. },
  6051. [i](bool success) {
  6052. EXPECT_TRUE(success);
  6053. delete i;
  6054. });
  6055. })
  6056. .Get("/streamed-chunked2",
  6057. [&](const Request & /*req*/, Response &res) {
  6058. auto i = new int(0);
  6059. res.set_chunked_content_provider(
  6060. "text/plain",
  6061. [i](size_t /*offset*/, DataSink &sink) {
  6062. switch (*i) {
  6063. case 0: sink.os << "123"; break;
  6064. case 1: sink.os << "456"; break;
  6065. case 2: sink.os << "789"; break;
  6066. case 3: sink.done(); break;
  6067. }
  6068. (*i)++;
  6069. return true;
  6070. },
  6071. [i](bool success) {
  6072. EXPECT_TRUE(success);
  6073. delete i;
  6074. });
  6075. })
  6076. .Get("/streamed-chunked-with-trailer",
  6077. [&](const Request & /*req*/, Response &res) {
  6078. auto i = new int(0);
  6079. res.set_header("Trailer", "Dummy1, Dummy2");
  6080. res.set_chunked_content_provider(
  6081. "text/plain",
  6082. [i](size_t /*offset*/, DataSink &sink) {
  6083. switch (*i) {
  6084. case 0: sink.os << "123"; break;
  6085. case 1: sink.os << "456"; break;
  6086. case 2: sink.os << "789"; break;
  6087. case 3: {
  6088. sink.done_with_trailer(
  6089. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6090. } break;
  6091. }
  6092. (*i)++;
  6093. return true;
  6094. },
  6095. [i](bool success) {
  6096. EXPECT_TRUE(success);
  6097. delete i;
  6098. });
  6099. })
  6100. .Get("/streamed",
  6101. [&](const Request & /*req*/, Response &res) {
  6102. res.set_content_provider(
  6103. 6, "text/plain",
  6104. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6105. sink.os << (offset < 3 ? "a" : "b");
  6106. return true;
  6107. });
  6108. })
  6109. .Get("/streamed-without-length",
  6110. [&](const Request & /*req*/, Response &res) {
  6111. auto data = new std::string("abcdefg");
  6112. res.set_content_provider(
  6113. "text/plain",
  6114. [data](size_t offset, DataSink &sink) {
  6115. if (offset < data->size()) {
  6116. sink.os << data->substr(offset);
  6117. }
  6118. sink.done();
  6119. return true;
  6120. },
  6121. [data](bool success) {
  6122. EXPECT_TRUE(success);
  6123. delete data;
  6124. });
  6125. })
  6126. .Get("/streamed-with-range",
  6127. [&](const Request &req, Response &res) {
  6128. auto data = new std::string("abcdefg");
  6129. // An explicit status keeps the server from picking the 206 it
  6130. // would otherwise choose for a ranged request, so the response
  6131. // is not a partial representation.
  6132. auto status = req.get_param_value("status");
  6133. if (status == "200") {
  6134. res.status = StatusCode::OK_200;
  6135. } else if (status == "403") {
  6136. res.status = StatusCode::Forbidden_403;
  6137. }
  6138. res.set_content_provider(
  6139. data->size(), "text/plain",
  6140. [data](size_t offset, size_t length, DataSink &sink) {
  6141. size_t DATA_CHUNK_SIZE = 4;
  6142. const auto &d = *data;
  6143. auto out_len =
  6144. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6145. auto ret =
  6146. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6147. EXPECT_TRUE(ret);
  6148. return true;
  6149. },
  6150. [data, &req](bool success) {
  6151. EXPECT_EQ(success, !req.has_param("error"));
  6152. delete data;
  6153. });
  6154. })
  6155. .Get("/streamed-cancel",
  6156. [&](const Request & /*req*/, Response &res) {
  6157. res.set_content_provider(
  6158. size_t(-1), "text/plain",
  6159. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6160. sink.os << "data_chunk";
  6161. return true;
  6162. });
  6163. })
  6164. .Get("/regex-with-delimiter",
  6165. [&](const Request &req, Response & /*res*/) {
  6166. ASSERT_TRUE(req.has_param("key"));
  6167. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6168. })
  6169. .Get("/with-range",
  6170. [&](const Request & /*req*/, Response &res) {
  6171. res.set_content("abcdefg", "text/plain");
  6172. })
  6173. .Get("/test-start-time",
  6174. [&](const Request &req, Response & /*res*/) {
  6175. EXPECT_NE(req.start_time_,
  6176. std::chrono::steady_clock::time_point::min());
  6177. })
  6178. .Get("/with-range-customized-response",
  6179. [&](const Request & /*req*/, Response &res) {
  6180. res.status = StatusCode::BadRequest_400;
  6181. res.set_content(JSON_DATA, "application/json");
  6182. })
  6183. .Post("/chunked",
  6184. [&](const Request &req, Response & /*res*/) {
  6185. EXPECT_EQ(req.body, "dechunked post body");
  6186. })
  6187. .Post("/large-chunked",
  6188. [&](const Request &req, Response & /*res*/) {
  6189. std::string expected(6 * 30 * 1024u, 'a');
  6190. EXPECT_EQ(req.body, expected);
  6191. })
  6192. .Post("/multipart",
  6193. [&](const Request &req, Response & /*res*/) {
  6194. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6195. req.form.get_field_count("text2") +
  6196. req.form.get_field_count("file3") +
  6197. req.form.get_field_count("file4"));
  6198. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6199. req.form.get_file_count("file2"));
  6200. ASSERT_TRUE(!req.form.has_file("???"));
  6201. ASSERT_TRUE(!req.form.has_field("???"));
  6202. ASSERT_TRUE(req.body.empty());
  6203. {
  6204. const auto &text = req.form.get_field("text1");
  6205. EXPECT_EQ("text default", text);
  6206. }
  6207. {
  6208. const auto &text = req.form.get_field("text2");
  6209. EXPECT_EQ("aωb", text);
  6210. }
  6211. {
  6212. const auto &file = req.form.get_file("file1");
  6213. EXPECT_EQ("hello.txt", file.filename);
  6214. EXPECT_EQ("text/plain", file.content_type);
  6215. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6216. }
  6217. {
  6218. const auto &file = req.form.get_file("file2");
  6219. EXPECT_EQ("world.json", file.filename);
  6220. EXPECT_EQ("application/json", file.content_type);
  6221. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6222. }
  6223. {
  6224. const auto &text = req.form.get_field("file3");
  6225. EXPECT_EQ(0u, text.size());
  6226. }
  6227. {
  6228. const auto &text = req.form.get_field("file4");
  6229. EXPECT_EQ(0u, text.size());
  6230. }
  6231. })
  6232. .Post("/multipart/multi_file_values",
  6233. [&](const Request &req, Response & /*res*/) {
  6234. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6235. req.form.get_field_count("multi_text1"));
  6236. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6237. ASSERT_TRUE(!req.form.has_file("???"));
  6238. ASSERT_TRUE(!req.form.has_field("???"));
  6239. ASSERT_TRUE(req.body.empty());
  6240. {
  6241. const auto &text = req.form.get_field("text");
  6242. EXPECT_EQ("default text", text);
  6243. }
  6244. {
  6245. const auto &text1_values = req.form.get_fields("multi_text1");
  6246. EXPECT_EQ(2u, text1_values.size());
  6247. EXPECT_EQ("aaaaa", text1_values[0]);
  6248. EXPECT_EQ("bbbbb", text1_values[1]);
  6249. }
  6250. {
  6251. const auto &file1_values = req.form.get_files("multi_file1");
  6252. EXPECT_EQ(2u, file1_values.size());
  6253. auto file1 = file1_values[0];
  6254. EXPECT_EQ(file1.filename, "hello.txt");
  6255. EXPECT_EQ(file1.content_type, "text/plain");
  6256. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6257. auto file2 = file1_values[1];
  6258. EXPECT_EQ(file2.filename, "world.json");
  6259. EXPECT_EQ(file2.content_type, "application/json");
  6260. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6261. }
  6262. })
  6263. .Post("/empty",
  6264. [&](const Request &req, Response &res) {
  6265. EXPECT_EQ(req.body, "");
  6266. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6267. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6268. res.set_content("empty", "text/plain");
  6269. })
  6270. .Post("/empty-no-content-type",
  6271. [&](const Request &req, Response &res) {
  6272. EXPECT_EQ(req.body, "");
  6273. EXPECT_FALSE(req.has_header("Content-Type"));
  6274. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6275. res.set_content("empty-no-content-type", "text/plain");
  6276. })
  6277. .Post("/path-only",
  6278. [&](const Request &req, Response &res) {
  6279. EXPECT_EQ(req.body, "");
  6280. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6281. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6282. res.set_content("path-only", "text/plain");
  6283. })
  6284. .Post("/path-headers-only",
  6285. [&](const Request &req, Response &res) {
  6286. EXPECT_EQ(req.body, "");
  6287. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6288. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6289. EXPECT_EQ("world", req.get_header_value("hello"));
  6290. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6291. res.set_content("path-headers-only", "text/plain");
  6292. })
  6293. .Post("/post-large",
  6294. [&](const Request &req, Response &res) {
  6295. EXPECT_EQ(req.body, LARGE_DATA);
  6296. res.set_content(req.body, "text/plain");
  6297. })
  6298. .Post("/post-loopback",
  6299. [&](const Request &, Response &res,
  6300. ContentReader const &content_reader) {
  6301. std::string body;
  6302. content_reader([&](const char *data, size_t data_length) {
  6303. body.append(data, data_length);
  6304. return true;
  6305. });
  6306. res.set_content(body, "text/plain");
  6307. })
  6308. .Put("/put-loopback",
  6309. [&](const Request &, Response &res,
  6310. ContentReader const &content_reader) {
  6311. std::string body;
  6312. content_reader([&](const char *data, size_t data_length) {
  6313. body.append(data, data_length);
  6314. return true;
  6315. });
  6316. res.set_content(body, "text/plain");
  6317. })
  6318. .Patch("/patch-loopback",
  6319. [&](const Request &, Response &res,
  6320. ContentReader const &content_reader) {
  6321. std::string body;
  6322. content_reader([&](const char *data, size_t data_length) {
  6323. body.append(data, data_length);
  6324. return true;
  6325. });
  6326. res.set_content(body, "text/plain");
  6327. })
  6328. .Put("/empty-no-content-type",
  6329. [&](const Request &req, Response &res) {
  6330. EXPECT_EQ(req.body, "");
  6331. EXPECT_FALSE(req.has_header("Content-Type"));
  6332. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6333. res.set_content("empty-no-content-type", "text/plain");
  6334. })
  6335. .Put("/put",
  6336. [&](const Request &req, Response &res) {
  6337. EXPECT_EQ(req.body, "PUT");
  6338. res.set_content(req.body, "text/plain");
  6339. })
  6340. .Put("/put-large",
  6341. [&](const Request &req, Response &res) {
  6342. EXPECT_EQ(req.body, LARGE_DATA);
  6343. res.set_content(req.body, "text/plain");
  6344. })
  6345. .Patch("/patch",
  6346. [&](const Request &req, Response &res) {
  6347. EXPECT_EQ(req.body, "PATCH");
  6348. res.set_content(req.body, "text/plain");
  6349. })
  6350. .Delete("/delete",
  6351. [&](const Request & /*req*/, Response &res) {
  6352. res.set_content("DELETE", "text/plain");
  6353. })
  6354. .Delete("/delete-body",
  6355. [&](const Request &req, Response &res) {
  6356. EXPECT_EQ(req.body, "content");
  6357. res.set_content(req.body, "text/plain");
  6358. })
  6359. .Options(R"(\*)",
  6360. [&](const Request & /*req*/, Response &res) {
  6361. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6362. })
  6363. .CustomRoute("PROPFIND", "/dav/:id",
  6364. [&](const Request &req, Response &res) {
  6365. res.set_header("x-body-size",
  6366. std::to_string(req.body.size()));
  6367. res.set_header("x-matched-route", req.matched_route);
  6368. res.set_header("x-dav-id", req.path_params.at("id"));
  6369. res.status = StatusCode::MultiStatus_207;
  6370. res.set_content(req.body, "application/xml");
  6371. })
  6372. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6373. [&](const Request &req, Response &res) {
  6374. res.set_header("x-dav-match", req.matches[1]);
  6375. res.status = StatusCode::MultiStatus_207;
  6376. })
  6377. .CustomRoute("MKCOL", "/dav-mkcol",
  6378. [&](const Request &req, Response &res) {
  6379. EXPECT_TRUE(req.body.empty());
  6380. res.status = StatusCode::Created_201;
  6381. })
  6382. .CustomRoute(
  6383. "REPORT", "/dav-report",
  6384. [&](const Request & /*req*/, Response &res,
  6385. const ContentReader &content_reader) {
  6386. std::string body;
  6387. content_reader([&](const char *data, size_t data_length) {
  6388. body.append(data, data_length);
  6389. return true;
  6390. });
  6391. res.set_header("x-body-size", std::to_string(body.size()));
  6392. res.status = StatusCode::MultiStatus_207;
  6393. res.set_content(body, "application/xml");
  6394. })
  6395. .Get("/request-target",
  6396. [&](const Request &req, Response & /*res*/) {
  6397. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6398. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6399. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6400. })
  6401. .Get("/long-query-value",
  6402. [&](const Request &req, Response & /*res*/) {
  6403. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6404. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6405. })
  6406. .Get("/too-long-query-value",
  6407. [&](const Request &req, Response & /*res*/) {
  6408. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6409. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6410. })
  6411. .Get("/array-param",
  6412. [&](const Request &req, Response & /*res*/) {
  6413. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6414. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6415. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6416. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6417. })
  6418. .Get("/array-param-values",
  6419. [&](const Request &req, Response & /*res*/) {
  6420. auto values = req.get_param_values("array");
  6421. EXPECT_EQ(3u, values.size());
  6422. EXPECT_EQ("value1", values[0]);
  6423. EXPECT_EQ("value2", values[1]);
  6424. EXPECT_EQ("value3", values[2]);
  6425. auto empty = req.get_param_values("nonexistent");
  6426. EXPECT_TRUE(empty.empty());
  6427. })
  6428. .Post("/validate-no-multiple-headers",
  6429. [&](const Request &req, Response & /*res*/) {
  6430. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6431. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6432. })
  6433. .Post("/content_receiver",
  6434. [&](const Request &req, Response &res,
  6435. const ContentReader &content_reader) {
  6436. if (req.is_multipart_form_data()) {
  6437. std::vector<FormData> items;
  6438. content_reader(
  6439. [&](const FormData &file) {
  6440. items.push_back(file);
  6441. return true;
  6442. },
  6443. [&](const char *data, size_t data_length) {
  6444. items.back().content.append(data, data_length);
  6445. return true;
  6446. });
  6447. EXPECT_EQ(5u, items.size());
  6448. {
  6449. const auto &file = get_file_value(items, "text1");
  6450. EXPECT_TRUE(file.filename.empty());
  6451. EXPECT_EQ("text default", file.content);
  6452. }
  6453. {
  6454. const auto &file = get_file_value(items, "text2");
  6455. EXPECT_TRUE(file.filename.empty());
  6456. EXPECT_EQ("aωb", file.content);
  6457. }
  6458. {
  6459. const auto &file = get_file_value(items, "file1");
  6460. EXPECT_EQ("hello.txt", file.filename);
  6461. EXPECT_EQ("text/plain", file.content_type);
  6462. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6463. }
  6464. {
  6465. const auto &file = get_file_value(items, "file2");
  6466. EXPECT_EQ("world.json", file.filename);
  6467. EXPECT_EQ("application/json", file.content_type);
  6468. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6469. }
  6470. {
  6471. const auto &file = get_file_value(items, "file3");
  6472. EXPECT_TRUE(file.filename.empty());
  6473. EXPECT_EQ("application/octet-stream", file.content_type);
  6474. EXPECT_EQ(0u, file.content.size());
  6475. }
  6476. } else {
  6477. std::string body;
  6478. content_reader([&](const char *data, size_t data_length) {
  6479. EXPECT_EQ(7U, data_length);
  6480. body.append(data, data_length);
  6481. return true;
  6482. });
  6483. EXPECT_EQ(body, "content");
  6484. res.set_content(body, "text/plain");
  6485. }
  6486. })
  6487. .Put("/content_receiver",
  6488. [&](const Request & /*req*/, Response &res,
  6489. const ContentReader &content_reader) {
  6490. std::string body;
  6491. content_reader([&](const char *data, size_t 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. .Patch("/content_receiver",
  6499. [&](const Request & /*req*/, Response &res,
  6500. const ContentReader &content_reader) {
  6501. std::string body;
  6502. content_reader([&](const char *data, size_t data_length) {
  6503. body.append(data, data_length);
  6504. return true;
  6505. });
  6506. EXPECT_EQ(body, "content");
  6507. res.set_content(body, "text/plain");
  6508. })
  6509. .Post("/query-string-and-body",
  6510. [&](const Request &req, Response & /*res*/) {
  6511. ASSERT_TRUE(req.has_param("key"));
  6512. EXPECT_EQ(req.get_param_value("key"), "value");
  6513. EXPECT_EQ(req.body, "content");
  6514. })
  6515. .Get("/last-request",
  6516. [&](const Request &req, Response & /*res*/) {
  6517. EXPECT_EQ("close", req.get_header_value("Connection"));
  6518. })
  6519. .Get(R"(/redirect/(\d+))",
  6520. [&](const Request &req, Response &res) {
  6521. auto num = std::stoi(req.matches[1]) + 1;
  6522. std::string url = "/redirect/" + std::to_string(num);
  6523. res.set_redirect(url);
  6524. })
  6525. .Post("/binary",
  6526. [&](const Request &req, Response &res) {
  6527. EXPECT_EQ(4U, req.body.size());
  6528. EXPECT_EQ("application/octet-stream",
  6529. req.get_header_value("Content-Type"));
  6530. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6531. res.set_content(req.body, "application/octet-stream");
  6532. })
  6533. .Put("/binary",
  6534. [&](const Request &req, Response &res) {
  6535. EXPECT_EQ(4U, req.body.size());
  6536. EXPECT_EQ("application/octet-stream",
  6537. req.get_header_value("Content-Type"));
  6538. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6539. res.set_content(req.body, "application/octet-stream");
  6540. })
  6541. .Patch("/binary",
  6542. [&](const Request &req, Response &res) {
  6543. EXPECT_EQ(4U, req.body.size());
  6544. EXPECT_EQ("application/octet-stream",
  6545. req.get_header_value("Content-Type"));
  6546. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6547. res.set_content(req.body, "application/octet-stream");
  6548. })
  6549. .Delete("/binary",
  6550. [&](const Request &req, Response &res) {
  6551. EXPECT_EQ(4U, req.body.size());
  6552. EXPECT_EQ("application/octet-stream",
  6553. req.get_header_value("Content-Type"));
  6554. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6555. res.set_content(req.body, "application/octet-stream");
  6556. })
  6557. .Get("/issue1772",
  6558. [&](const Request & /*req*/, Response &res) {
  6559. res.status = 401;
  6560. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6561. })
  6562. .Delete("/issue609",
  6563. [](const httplib::Request &, httplib::Response &res,
  6564. const httplib::ContentReader &) {
  6565. res.set_content("ok", "text/plain");
  6566. })
  6567. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6568. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6569. .Get("/compress",
  6570. [&](const Request & /*req*/, Response &res) {
  6571. res.set_content(
  6572. "12345678901234567890123456789012345678901234567890123456789"
  6573. "01234567890123456789012345678901234567890",
  6574. "text/plain");
  6575. })
  6576. .Get("/compress-with-charset",
  6577. [&](const Request & /*req*/, Response &res) {
  6578. res.set_content(
  6579. "12345678901234567890123456789012345678901234567890123456789"
  6580. "01234567890123456789012345678901234567890",
  6581. "application/json; charset=utf-8");
  6582. })
  6583. .Get("/nocompress",
  6584. [&](const Request & /*req*/, Response &res) {
  6585. res.set_content(
  6586. "12345678901234567890123456789012345678901234567890123456789"
  6587. "01234567890123456789012345678901234567890",
  6588. "application/octet-stream");
  6589. })
  6590. .Post("/compress-multipart",
  6591. [&](const Request &req, Response & /*res*/) {
  6592. EXPECT_EQ(2u, req.form.fields.size());
  6593. ASSERT_TRUE(!req.form.has_field("???"));
  6594. {
  6595. const auto &text = req.form.get_field("key1");
  6596. EXPECT_EQ("test", text);
  6597. }
  6598. {
  6599. const auto &text = req.form.get_field("key2");
  6600. EXPECT_EQ("--abcdefg123", text);
  6601. }
  6602. })
  6603. #endif
  6604. ;
  6605. persons_["john"] = "programmer";
  6606. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6607. svr_.wait_until_ready();
  6608. }
  6609. virtual void TearDown() {
  6610. svr_.stop();
  6611. if (!request_threads_.empty()) {
  6612. std::this_thread::sleep_for(std::chrono::seconds(1));
  6613. for (auto &t : request_threads_) {
  6614. t.join();
  6615. }
  6616. }
  6617. t_.join();
  6618. }
  6619. map<string, string> persons_;
  6620. #ifdef CPPHTTPLIB_SSL_ENABLED
  6621. SSLClient cli_;
  6622. SSLServer svr_;
  6623. #else
  6624. Client cli_;
  6625. Server svr_;
  6626. #endif
  6627. thread t_;
  6628. std::vector<thread> request_threads_;
  6629. };
  6630. TEST_F(ServerTest, GetMethod200) {
  6631. auto res = cli_.Get("/hi");
  6632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6633. EXPECT_EQ("HTTP/1.1", res->version);
  6634. EXPECT_EQ(StatusCode::OK_200, res->status);
  6635. EXPECT_EQ("OK", res->reason);
  6636. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6637. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6638. EXPECT_EQ("Hello World!", res->body);
  6639. }
  6640. TEST_F(ServerTest, GetEmptyFile) {
  6641. auto res = cli_.Get("/empty_file");
  6642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6643. EXPECT_EQ(StatusCode::OK_200, res->status);
  6644. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6645. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6646. EXPECT_EQ("", res->body);
  6647. }
  6648. TEST_F(ServerTest, GetFileContent) {
  6649. auto res = cli_.Get("/file_content");
  6650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6651. EXPECT_EQ(StatusCode::OK_200, res->status);
  6652. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6653. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6654. EXPECT_EQ("test.html", res->body);
  6655. }
  6656. TEST_F(ServerTest, GetFileContentWithRange) {
  6657. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6659. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6660. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6661. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6662. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6663. EXPECT_EQ("est", res->body);
  6664. }
  6665. TEST_F(ServerTest, GetFileContentWithContentType) {
  6666. auto res = cli_.Get("/file_content_with_content_type");
  6667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6668. EXPECT_EQ(StatusCode::OK_200, res->status);
  6669. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6670. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6671. EXPECT_EQ("file\n", res->body);
  6672. }
  6673. TEST_F(ServerTest, GetInvalidFileContent) {
  6674. auto res = cli_.Get("/invalid_file_content");
  6675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6676. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6677. }
  6678. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6679. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6681. EXPECT_EQ("HTTP/1.1", res->version);
  6682. EXPECT_EQ(StatusCode::OK_200, res->status);
  6683. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6684. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6685. EXPECT_EQ("Hello World!", res->body);
  6686. }
  6687. TEST_F(ServerTest, GetMethod302) {
  6688. auto res = cli_.Get("/");
  6689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6690. EXPECT_EQ(StatusCode::Found_302, res->status);
  6691. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6692. }
  6693. TEST_F(ServerTest, GetMethod302Redirect) {
  6694. cli_.set_follow_location(true);
  6695. auto res = cli_.Get("/");
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::OK_200, res->status);
  6698. EXPECT_EQ("Hello World!", res->body);
  6699. EXPECT_EQ("/hi", res->location);
  6700. }
  6701. TEST_F(ServerTest, GetMethod404) {
  6702. auto res = cli_.Get("/invalid");
  6703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6704. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6705. }
  6706. TEST_F(ServerTest, HeadMethod200) {
  6707. auto res = cli_.Head("/hi");
  6708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6709. EXPECT_EQ(StatusCode::OK_200, res->status);
  6710. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6711. EXPECT_TRUE(res->body.empty());
  6712. }
  6713. TEST_F(ServerTest, HeadMethod200Static) {
  6714. auto res = cli_.Head("/mount/dir/index.html");
  6715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6716. EXPECT_EQ(StatusCode::OK_200, res->status);
  6717. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6718. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6719. EXPECT_TRUE(res->body.empty());
  6720. }
  6721. TEST_F(ServerTest, HeadMethod404) {
  6722. auto res = cli_.Head("/invalid");
  6723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6724. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6725. EXPECT_TRUE(res->body.empty());
  6726. }
  6727. TEST_F(ServerTest, GetMethodPersonJohn) {
  6728. auto res = cli_.Get("/person/john");
  6729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6730. EXPECT_EQ(StatusCode::OK_200, res->status);
  6731. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6732. EXPECT_EQ("programmer", res->body);
  6733. }
  6734. TEST_F(ServerTest, PostMethod1) {
  6735. auto res = cli_.Get("/person/john1");
  6736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6737. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6738. res = cli_.Post("/person", "name=john1&note=coder",
  6739. "application/x-www-form-urlencoded");
  6740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6741. ASSERT_EQ(StatusCode::OK_200, res->status);
  6742. res = cli_.Get("/person/john1");
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. ASSERT_EQ(StatusCode::OK_200, res->status);
  6745. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6746. ASSERT_EQ("coder", res->body);
  6747. }
  6748. TEST_F(ServerTest, PostMethod2) {
  6749. auto res = cli_.Get("/person/john2");
  6750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6751. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6752. Params params;
  6753. params.emplace("name", "john2");
  6754. params.emplace("note", "coder");
  6755. res = cli_.Post("/person", params);
  6756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6757. ASSERT_EQ(StatusCode::OK_200, res->status);
  6758. res = cli_.Get("/person/john2");
  6759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6760. ASSERT_EQ(StatusCode::OK_200, res->status);
  6761. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6762. ASSERT_EQ("coder", res->body);
  6763. }
  6764. TEST_F(ServerTest, PutMethod3) {
  6765. auto res = cli_.Get("/person/john3");
  6766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6767. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6768. Params params;
  6769. params.emplace("name", "john3");
  6770. params.emplace("note", "coder");
  6771. res = cli_.Put("/person", params);
  6772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6773. ASSERT_EQ(StatusCode::OK_200, res->status);
  6774. res = cli_.Get("/person/john3");
  6775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6776. ASSERT_EQ(StatusCode::OK_200, res->status);
  6777. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6778. ASSERT_EQ("coder", res->body);
  6779. }
  6780. TEST_F(ServerTest, DeleteMethod1) {
  6781. auto res = cli_.Get("/person/john4");
  6782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6783. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6784. Params params;
  6785. params.emplace("name", "john4");
  6786. params.emplace("note", "coder");
  6787. res = cli_.Post("/person", params);
  6788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6789. ASSERT_EQ(StatusCode::OK_200, res->status);
  6790. res = cli_.Get("/person/john4");
  6791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6792. ASSERT_EQ(StatusCode::OK_200, res->status);
  6793. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6794. ASSERT_EQ("coder", res->body);
  6795. Params delete_params;
  6796. delete_params.emplace("name", "john4");
  6797. res = cli_.Delete("/person", delete_params);
  6798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6799. ASSERT_EQ(StatusCode::OK_200, res->status);
  6800. ASSERT_EQ("DELETED", res->body);
  6801. res = cli_.Get("/person/john4");
  6802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6803. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6804. }
  6805. TEST_F(ServerTest, DeleteMethod2) {
  6806. auto res = cli_.Get("/person/john5");
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6809. Params params;
  6810. params.emplace("name", "john5");
  6811. params.emplace("note", "developer");
  6812. res = cli_.Post("/person", params);
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. ASSERT_EQ(StatusCode::OK_200, res->status);
  6815. res = cli_.Get("/person/john5");
  6816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6817. ASSERT_EQ(StatusCode::OK_200, res->status);
  6818. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6819. ASSERT_EQ("developer", res->body);
  6820. Params delete_params;
  6821. delete_params.emplace("name", "john5");
  6822. Headers headers;
  6823. headers.emplace("Custom-Header", "test-value");
  6824. res = cli_.Delete("/person", headers, delete_params);
  6825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6826. ASSERT_EQ(StatusCode::OK_200, res->status);
  6827. ASSERT_EQ("DELETED", res->body);
  6828. res = cli_.Get("/person/john5");
  6829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6830. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6831. }
  6832. TEST_F(ServerTest, DeleteMethod3) {
  6833. auto res = cli_.Get("/person/john6");
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6836. Params params;
  6837. params.emplace("name", "john6");
  6838. params.emplace("note", "tester");
  6839. res = cli_.Post("/person", params);
  6840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6841. ASSERT_EQ(StatusCode::OK_200, res->status);
  6842. res = cli_.Get("/person/john6");
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. ASSERT_EQ(StatusCode::OK_200, res->status);
  6845. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6846. ASSERT_EQ("tester", res->body);
  6847. Params delete_params;
  6848. delete_params.emplace("name", "john6");
  6849. Headers headers;
  6850. headers.emplace("Custom-Header", "test-value");
  6851. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6853. ASSERT_EQ(StatusCode::OK_200, res->status);
  6854. ASSERT_EQ("DELETED", res->body);
  6855. res = cli_.Get("/person/john6");
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6858. }
  6859. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6860. Params params;
  6861. params.emplace("json", JSON_DATA);
  6862. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6864. ASSERT_EQ(StatusCode::OK_200, res->status);
  6865. ASSERT_EQ(JSON_DATA, res->body);
  6866. }
  6867. TEST_F(ServerTest, PostEmptyContent) {
  6868. auto res = cli_.Post("/empty", "", "text/plain");
  6869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6870. ASSERT_EQ(StatusCode::OK_200, res->status);
  6871. ASSERT_EQ("empty", res->body);
  6872. }
  6873. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6874. auto res = cli_.Post("/empty-no-content-type");
  6875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6876. ASSERT_EQ(StatusCode::OK_200, res->status);
  6877. ASSERT_EQ("empty-no-content-type", res->body);
  6878. }
  6879. TEST_F(ServerTest, PostPathOnly) {
  6880. auto res = cli_.Post("/path-only");
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. ASSERT_EQ(StatusCode::OK_200, res->status);
  6883. ASSERT_EQ("path-only", res->body);
  6884. }
  6885. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6886. auto res = cli_.Post("/path-headers-only",
  6887. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6889. ASSERT_EQ(StatusCode::OK_200, res->status);
  6890. ASSERT_EQ("path-headers-only", res->body);
  6891. }
  6892. TEST_F(ServerTest, PostLarge) {
  6893. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6895. ASSERT_EQ(StatusCode::OK_200, res->status);
  6896. EXPECT_EQ(LARGE_DATA, res->body);
  6897. }
  6898. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6899. auto res = cli_.Put("/empty-no-content-type");
  6900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6901. ASSERT_EQ(StatusCode::OK_200, res->status);
  6902. ASSERT_EQ("empty-no-content-type", res->body);
  6903. }
  6904. TEST_F(ServerTest, GetMethodDir) {
  6905. auto res = cli_.Get("/dir/");
  6906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6907. EXPECT_EQ(StatusCode::OK_200, res->status);
  6908. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6909. auto body = R"(<html>
  6910. <head>
  6911. </head>
  6912. <body>
  6913. <a href="/dir/test.html">Test</a>
  6914. <a href="/hi">hi</a>
  6915. </body>
  6916. </html>
  6917. )";
  6918. EXPECT_EQ(body, res->body);
  6919. }
  6920. TEST_F(ServerTest, GetMethodDirTest) {
  6921. auto res = cli_.Get("/dir/test.html");
  6922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6923. EXPECT_EQ(StatusCode::OK_200, res->status);
  6924. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6925. EXPECT_EQ("test.html", res->body);
  6926. }
  6927. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6928. auto res = cli_.Get("/dir/../dir/test.html");
  6929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6930. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6931. }
  6932. TEST_F(ServerTest, GetMethodInvalidPath) {
  6933. auto res = cli_.Get("/dir/../test.html");
  6934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6935. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6936. }
  6937. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6938. auto res = cli_.Get("/../www/dir/test.html");
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6941. }
  6942. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6943. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6945. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6946. }
  6947. TEST_F(ServerTest, GetMethodDirMountTest) {
  6948. auto res = cli_.Get("/mount/dir/test.html");
  6949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6950. EXPECT_EQ(StatusCode::OK_200, res->status);
  6951. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6952. EXPECT_EQ("test.html", res->body);
  6953. }
  6954. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6955. auto res = cli_.Get("/mount/dir/../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, GetMethodInvalidMountPath) {
  6960. auto res = cli_.Get("/mount/dir/../test.html");
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6963. }
  6964. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6965. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6967. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6968. }
  6969. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6970. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6972. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6973. }
  6974. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6975. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6978. }
  6979. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6980. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6982. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6983. }
  6984. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6985. auto res = cli_.Get("/mount/dir");
  6986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6987. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6988. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6989. }
  6990. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6991. auto res = cli_.Get("//dir");
  6992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6993. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6994. EXPECT_FALSE(res->has_header("Location"));
  6995. }
  6996. TEST_F(ServerTest, PostMethod303) {
  6997. auto res = cli_.Post("/1", "body", "text/plain");
  6998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6999. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7000. EXPECT_EQ("/2", res->get_header_value("Location"));
  7001. }
  7002. TEST_F(ServerTest, PostMethod303Redirect) {
  7003. cli_.set_follow_location(true);
  7004. auto res = cli_.Post("/1", "body", "text/plain");
  7005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7006. EXPECT_EQ(StatusCode::OK_200, res->status);
  7007. EXPECT_EQ("redirected.", res->body);
  7008. EXPECT_EQ("/2", res->location);
  7009. }
  7010. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7011. auto res = cli_.Get("/dir/test.abcde");
  7012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7013. EXPECT_EQ(StatusCode::OK_200, res->status);
  7014. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7015. EXPECT_EQ("abcde", res->body);
  7016. }
  7017. TEST_F(ServerTest, StaticFileRange) {
  7018. auto res =
  7019. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7022. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7023. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7024. EXPECT_EQ(true, res->has_header("Content-Range"));
  7025. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7026. EXPECT_EQ(std::string("cd"), res->body);
  7027. }
  7028. TEST_F(ServerTest, StaticFileRanges) {
  7029. auto res = cli_.Get("/dir/test.abcde",
  7030. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7032. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7033. EXPECT_TRUE(
  7034. res->get_header_value("Content-Type")
  7035. .find(
  7036. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7037. 0);
  7038. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7039. }
  7040. TEST_F(ServerTest, StaticFileRangeHead) {
  7041. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7043. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7044. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7045. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7046. EXPECT_EQ(true, res->has_header("Content-Range"));
  7047. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7048. }
  7049. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7050. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7053. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7054. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7055. EXPECT_EQ(true, res->has_header("Content-Range"));
  7056. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7057. res->get_header_value("Content-Range"));
  7058. EXPECT_EQ("LAST\n", res->body);
  7059. }
  7060. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7061. auto res =
  7062. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  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("4097", res->get_header_value("Content-Length"));
  7067. EXPECT_EQ(true, res->has_header("Content-Range"));
  7068. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7069. }
  7070. TEST_F(ServerTest, StaticFileBigFile) {
  7071. auto res = cli_.Get("/dir/1MB.txt");
  7072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7073. EXPECT_EQ(StatusCode::OK_200, res->status);
  7074. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7075. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7076. }
  7077. TEST_F(ServerTest, InvalidBaseDirMount) {
  7078. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7079. }
  7080. TEST_F(ServerTest, Binary) {
  7081. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7082. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7083. "application/octet-stream");
  7084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7085. ASSERT_EQ(StatusCode::OK_200, res->status);
  7086. ASSERT_EQ(4U, res->body.size());
  7087. res = cli_.Put("/binary", binary.data(), binary.size(),
  7088. "application/octet-stream");
  7089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7090. ASSERT_EQ(StatusCode::OK_200, res->status);
  7091. ASSERT_EQ(4U, res->body.size());
  7092. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7093. "application/octet-stream");
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. ASSERT_EQ(StatusCode::OK_200, res->status);
  7096. ASSERT_EQ(4U, res->body.size());
  7097. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7098. "application/octet-stream");
  7099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7100. ASSERT_EQ(StatusCode::OK_200, res->status);
  7101. ASSERT_EQ(4U, res->body.size());
  7102. }
  7103. TEST_F(ServerTest, BinaryString) {
  7104. auto binary = std::string("\x00\x01\x02\x03", 4);
  7105. auto res = cli_.Post("/binary", binary, "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_.Put("/binary", binary, "application/octet-stream");
  7110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7111. ASSERT_EQ(StatusCode::OK_200, res->status);
  7112. ASSERT_EQ(4U, res->body.size());
  7113. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7115. ASSERT_EQ(StatusCode::OK_200, res->status);
  7116. ASSERT_EQ(4U, res->body.size());
  7117. res = cli_.Delete("/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. }
  7122. TEST_F(ServerTest, EmptyRequest) {
  7123. auto res = cli_.Get("");
  7124. ASSERT_TRUE(!res);
  7125. EXPECT_EQ(Error::Connection, res.error());
  7126. }
  7127. TEST_F(ServerTest, LongRequest) {
  7128. std::string request;
  7129. for (size_t i = 0; i < 545; i++) {
  7130. request += "/TooLongRequest";
  7131. }
  7132. request += "OK";
  7133. auto res = cli_.Get(request.c_str());
  7134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7135. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7136. }
  7137. TEST_F(ServerTest, TooLongRequest) {
  7138. std::string request;
  7139. for (size_t i = 0; i < 546; i++) {
  7140. request += "/TooLongRequest";
  7141. }
  7142. request += "_NG";
  7143. auto start = std::chrono::high_resolution_clock::now();
  7144. cli_.set_keep_alive(true);
  7145. auto res = cli_.Get(request.c_str());
  7146. auto end = std::chrono::high_resolution_clock::now();
  7147. auto elapsed =
  7148. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7149. .count();
  7150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7151. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7152. EXPECT_LE(elapsed, 1000);
  7153. EXPECT_EQ("close", res->get_header_value("Connection"));
  7154. EXPECT_FALSE(cli_.is_socket_open());
  7155. }
  7156. TEST_F(ServerTest, AlmostTooLongRequest) {
  7157. // test for #2046 - URI length check shouldn't include other content on req
  7158. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7159. // leading /, space, HTTP/1.1)
  7160. std::string request =
  7161. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7162. auto res = cli_.Get(request.c_str());
  7163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7164. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7165. }
  7166. TEST_F(ServerTest, LongHeader) {
  7167. Request req;
  7168. req.method = "GET";
  7169. req.path = "/hi";
  7170. std::string host_and_port;
  7171. host_and_port += HOST;
  7172. host_and_port += ":";
  7173. host_and_port += std::to_string(PORT);
  7174. req.headers.emplace("Host", host_and_port.c_str());
  7175. req.headers.emplace("Accept", "*/*");
  7176. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7177. req.headers.emplace(
  7178. "Header-Name",
  7179. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7180. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7181. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7182. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7183. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7184. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7185. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7186. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7187. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7188. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7189. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7190. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7191. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7192. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7193. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7194. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7195. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7196. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7197. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7198. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7199. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7200. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7201. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7202. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7203. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7204. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7205. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7206. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7207. "@@@@@@@@@@@@@@@@");
  7208. auto res = std::make_shared<Response>();
  7209. auto error = Error::Success;
  7210. auto ret = cli_.send(req, *res, error);
  7211. ASSERT_TRUE(ret);
  7212. EXPECT_EQ(StatusCode::OK_200, res->status);
  7213. }
  7214. TEST_F(ServerTest, LongQueryValue) {
  7215. auto start = std::chrono::high_resolution_clock::now();
  7216. cli_.set_keep_alive(true);
  7217. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7218. auto end = std::chrono::high_resolution_clock::now();
  7219. auto elapsed =
  7220. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7221. .count();
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7224. EXPECT_LE(elapsed, 1000);
  7225. EXPECT_EQ("close", res->get_header_value("Connection"));
  7226. EXPECT_FALSE(cli_.is_socket_open());
  7227. }
  7228. TEST_F(ServerTest, TooLongQueryValue) {
  7229. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7230. ASSERT_FALSE(res);
  7231. EXPECT_EQ(Error::Read, res.error());
  7232. }
  7233. TEST_F(ServerTest, TooLongHeader) {
  7234. Request req;
  7235. req.method = "GET";
  7236. req.path = "/hi";
  7237. std::string host_and_port;
  7238. host_and_port += HOST;
  7239. host_and_port += ":";
  7240. host_and_port += std::to_string(PORT);
  7241. req.headers.emplace("Host", host_and_port.c_str());
  7242. req.headers.emplace("Accept", "*/*");
  7243. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7244. req.headers.emplace(
  7245. "Header-Name",
  7246. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7247. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7248. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7249. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7250. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7251. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7252. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7253. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7254. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7255. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7256. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7257. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7274. "@@@@@@@@@@@@@@@@@");
  7275. auto res = std::make_shared<Response>();
  7276. auto error = Error::Success;
  7277. auto ret = cli_.send(req, *res, error);
  7278. ASSERT_TRUE(ret);
  7279. EXPECT_EQ(StatusCode::OK_200, res->status);
  7280. }
  7281. TEST_F(ServerTest, HeaderCountAtLimit) {
  7282. // Test with headers just under the 100 limit
  7283. httplib::Headers headers;
  7284. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7285. // This should keep us just under the 100 header limit
  7286. for (int i = 0; i < 95; i++) {
  7287. std::string name = "X-Test-Header-" + std::to_string(i);
  7288. std::string value = "value" + std::to_string(i);
  7289. headers.emplace(name, value);
  7290. }
  7291. // This should work fine as we're under the limit
  7292. auto res = cli_.Get("/hi", headers);
  7293. EXPECT_TRUE(res);
  7294. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7295. }
  7296. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7297. // Test with many headers to exceed the 100 limit
  7298. httplib::Headers headers;
  7299. // Add 150 headers to definitely exceed the 100 limit
  7300. for (int i = 0; i < 150; i++) {
  7301. std::string name = "X-Test-Header-" + std::to_string(i);
  7302. std::string value = "value" + std::to_string(i);
  7303. headers.emplace(name, value);
  7304. }
  7305. // This should fail due to exceeding header count limit
  7306. cli_.set_keep_alive(true);
  7307. auto res = cli_.Get("/hi", headers);
  7308. // The server should respond with 400 Bad Request
  7309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7310. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7311. EXPECT_EQ("close", res->get_header_value("Connection"));
  7312. EXPECT_FALSE(cli_.is_socket_open());
  7313. }
  7314. TEST_F(ServerTest, PercentEncoding) {
  7315. auto res = cli_.Get("/e%6edwith%");
  7316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7317. EXPECT_EQ(StatusCode::OK_200, res->status);
  7318. }
  7319. TEST_F(ServerTest, PercentEncodingUnicode) {
  7320. auto res = cli_.Get("/e%u006edwith%");
  7321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7322. EXPECT_EQ(StatusCode::OK_200, res->status);
  7323. }
  7324. TEST_F(ServerTest, InvalidPercentEncoding) {
  7325. auto res = cli_.Get("/%endwith%");
  7326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7327. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7328. }
  7329. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7330. auto res = cli_.Get("/%uendwith%");
  7331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7332. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7333. }
  7334. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7335. auto res = cli_.Get("/hello?aaa=bbb%");
  7336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7337. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7338. }
  7339. TEST_F(ServerTest, PlusSignEncoding) {
  7340. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7342. EXPECT_EQ(StatusCode::OK_200, res->status);
  7343. EXPECT_EQ("a +b", res->body);
  7344. }
  7345. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7346. // This test simulates a potential DoS attack using many headers
  7347. // to verify our security fix prevents memory exhaustion
  7348. httplib::Headers attack_headers;
  7349. // Attempt to add many headers like an attacker would (200 headers to far
  7350. // exceed limit)
  7351. for (int i = 0; i < 200; i++) {
  7352. std::string name = "X-Attack-Header-" + std::to_string(i);
  7353. std::string value = "attack_payload_" + std::to_string(i);
  7354. attack_headers.emplace(name, value);
  7355. }
  7356. // Try to POST with excessive headers
  7357. cli_.set_keep_alive(true);
  7358. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7359. // Should either fail or return 400 Bad Request due to security limit
  7360. if (res) {
  7361. // If we get a response, it should be 400 Bad Request
  7362. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7363. EXPECT_EQ("close", res->get_header_value("Connection"));
  7364. }
  7365. EXPECT_FALSE(cli_.is_socket_open());
  7366. }
  7367. TEST_F(ServerTest, MultipartFormData) {
  7368. UploadFormDataItems items = {
  7369. {"text1", "text default", "", ""},
  7370. {"text2", "aωb", "", ""},
  7371. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7372. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7373. {"file3", "", "", "application/octet-stream"},
  7374. {"file4", "", "", " application/json tmp-string "}};
  7375. auto res = cli_.Post("/multipart", items);
  7376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7377. EXPECT_EQ(StatusCode::OK_200, res->status);
  7378. }
  7379. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7380. UploadFormDataItems items = {
  7381. {"text", "default text", "", ""},
  7382. {"multi_text1", "aaaaa", "", ""},
  7383. {"multi_text1", "bbbbb", "", ""},
  7384. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7385. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7386. "application/json"},
  7387. };
  7388. auto res = cli_.Post("/multipart/multi_file_values", items);
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::OK_200, res->status);
  7391. }
  7392. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7393. auto res = cli_.Get("/hi");
  7394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7395. EXPECT_EQ(StatusCode::OK_200, res->status);
  7396. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7397. EXPECT_EQ("Hello World!", res->body);
  7398. }
  7399. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7400. Request req;
  7401. req.method = "POST";
  7402. req.path = "/chunked";
  7403. std::string host_and_port;
  7404. host_and_port += HOST;
  7405. host_and_port += ":";
  7406. host_and_port += std::to_string(PORT);
  7407. req.headers.emplace("Host", host_and_port.c_str());
  7408. req.headers.emplace("Accept", "*/*");
  7409. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7410. req.headers.emplace("Content-Type", "text/plain");
  7411. req.headers.emplace("Content-Length", "0");
  7412. req.headers.emplace(
  7413. "Transfer-Encoding",
  7414. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7415. // Client does not chunk, so make a chunked body manually.
  7416. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7417. auto res = std::make_shared<Response>();
  7418. auto error = Error::Success;
  7419. auto ret = cli_.send(req, *res, error);
  7420. ASSERT_TRUE(ret);
  7421. EXPECT_EQ(StatusCode::OK_200, res->status);
  7422. }
  7423. template <typename ClientT>
  7424. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7425. int expected_status) {
  7426. Request req;
  7427. req.method = "POST";
  7428. req.path = "/chunked";
  7429. std::string host_and_port;
  7430. host_and_port += HOST;
  7431. host_and_port += ":";
  7432. host_and_port += std::to_string(PORT);
  7433. req.headers.emplace("Host", host_and_port.c_str());
  7434. req.headers.emplace("Content-Length", "0");
  7435. req.headers.emplace("Transfer-Encoding", "chunked");
  7436. req.body = body;
  7437. auto res = std::make_shared<Response>();
  7438. auto error = Error::Success;
  7439. ASSERT_TRUE(cli.send(req, *res, error));
  7440. EXPECT_EQ(expected_status, res->status);
  7441. }
  7442. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7443. // rather than treat them as valid lengths.
  7444. template <typename ClientT>
  7445. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7446. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7447. }
  7448. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7449. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7450. }
  7451. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7452. expect_chunked_body_rejected(
  7453. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7454. }
  7455. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7456. // chunk-size line carries no CR, LF or other control character ahead of its
  7457. // terminator. Such a line must be refused rather than read as extension text.
  7458. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7459. expect_chunked_body_rejected(
  7460. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7461. }
  7462. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7463. expect_chunked_body_rejected(
  7464. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7465. }
  7466. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7467. expect_chunked_body_rejected(
  7468. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7469. }
  7470. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7471. // The literal stays split: a hex escape consumes every hex digit that
  7472. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7473. expect_chunked_body_rejected(
  7474. cli_, "4;a\x01"
  7475. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7476. }
  7477. // The bytes around chunk data are no payload, so they cannot ride on the
  7478. // payload limit
  7479. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7480. // Small enough that the whole request is sent before the server turns it
  7481. // down, yet past the limit by the last chunks
  7482. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7483. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7484. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7485. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7486. SCOPED_TRACE(size_line.substr(0, 2));
  7487. std::string body;
  7488. for (auto c : std::string("dechunked post body")) {
  7489. body += size_line + "\r\n" + c + "\r\n";
  7490. }
  7491. body += "0\r\n\r\n";
  7492. expect_chunked_body_rejected(cli_, body.c_str());
  7493. }
  7494. }
  7495. TEST_F(ServerTest, AcceptsChunkExtension) {
  7496. expect_chunked_body_status(cli_,
  7497. "4;name=value\r\ndech\r\n"
  7498. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7499. "0;last\r\n\r\n",
  7500. StatusCode::OK_200);
  7501. }
  7502. TEST_F(ServerTest, GetStreamed2) {
  7503. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7505. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7506. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7507. EXPECT_EQ(true, res->has_header("Content-Range"));
  7508. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7509. EXPECT_EQ(std::string("ab"), res->body);
  7510. }
  7511. TEST_F(ServerTest, GetStreamed) {
  7512. auto res = cli_.Get("/streamed");
  7513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7514. EXPECT_EQ(StatusCode::OK_200, res->status);
  7515. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7516. EXPECT_EQ(std::string("aaabbb"), res->body);
  7517. }
  7518. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7519. auto res = cli_.Get("/streamed-without-length",
  7520. Headers{make_range_header({{0, -1}})});
  7521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7522. EXPECT_EQ(StatusCode::OK_200, res->status);
  7523. EXPECT_EQ(false, res->has_header("Content-Length"));
  7524. EXPECT_EQ(false, res->has_header("Content-Range"));
  7525. EXPECT_EQ(std::string("abcdefg"), res->body);
  7526. }
  7527. TEST_F(ServerTest, GetStreamedWithRange1) {
  7528. auto res =
  7529. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7531. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7532. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7533. EXPECT_EQ(true, res->has_header("Content-Range"));
  7534. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7535. EXPECT_EQ(std::string("def"), res->body);
  7536. }
  7537. TEST_F(ServerTest, GetStreamedWithRange2) {
  7538. auto res =
  7539. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7541. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7542. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7543. EXPECT_EQ(true, res->has_header("Content-Range"));
  7544. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7545. EXPECT_EQ(std::string("bcdefg"), res->body);
  7546. }
  7547. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7548. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7550. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7551. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7552. EXPECT_EQ(true, res->has_header("Content-Range"));
  7553. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7554. EXPECT_EQ(std::string("efg"), res->body);
  7555. }
  7556. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7557. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7558. // the entire representation.
  7559. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7560. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7562. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7563. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7564. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7565. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7566. }
  7567. }
  7568. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7569. auto res =
  7570. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7573. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7574. EXPECT_EQ(false, res->has_header("Content-Range"));
  7575. EXPECT_EQ(0U, res->body.size());
  7576. }
  7577. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7578. // Only a 206 is served as a partial representation. Under any other status
  7579. // `apply_ranges()` reported the full content length, so the body must match
  7580. // that header, and the content provider must never be asked for an offset
  7581. // outside the representation.
  7582. auto check = [&](int status, const char *range) {
  7583. auto path =
  7584. std::string("/streamed-with-range?status=") + std::to_string(status);
  7585. auto ctx = path + " Range: " + range;
  7586. auto res = cli_.Get(path, Headers{{"Range", range}});
  7587. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7588. EXPECT_EQ(status, res->status) << ctx;
  7589. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7590. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7591. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7592. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7593. };
  7594. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7595. check(403, "bytes=3-5");
  7596. // The offset is far past the representation.
  7597. check(403, "bytes=100000-100200");
  7598. // `first_pos` is still -1 here, and the bounds asserts in
  7599. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7600. check(403, "bytes=-3");
  7601. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7602. // multipart branch would have written one that is empty.
  7603. check(403, "bytes=1-2, 4-5");
  7604. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7605. // covers the whole representation.
  7606. check(200, "bytes=3-5");
  7607. check(200, "bytes=1-2, 4-5");
  7608. }
  7609. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7610. auto res =
  7611. cli_.Get("/streamed-with-range",
  7612. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7613. "92233720368547758079223372036854775807"}});
  7614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7615. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7616. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7617. EXPECT_EQ(false, res->has_header("Content-Range"));
  7618. EXPECT_EQ(0U, res->body.size());
  7619. }
  7620. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7621. auto res = cli_.Get(
  7622. "/with-range",
  7623. Headers{{"Range",
  7624. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7625. {"Accept-Encoding", ""}});
  7626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7627. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7628. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7629. EXPECT_EQ(true, res->has_header("Content-Range"));
  7630. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7631. EXPECT_EQ(std::string("abcdefg"), res->body);
  7632. }
  7633. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7634. auto res = cli_.Get("/with-range", Headers{
  7635. {"Range", "bytes=0-"},
  7636. {"Accept-Encoding", ""},
  7637. });
  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, GetStreamedWithRangeMultipart) {
  7646. auto res = cli_.Get("/streamed-with-range",
  7647. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7649. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7650. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7651. EXPECT_EQ(false, res->has_header("Content-Range"));
  7652. EXPECT_EQ(267U, res->body.size());
  7653. // Check that both range contents are present
  7654. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7655. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7656. // Check that Content-Range headers are present for both ranges
  7657. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7658. std::string::npos);
  7659. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7660. std::string::npos);
  7661. }
  7662. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7663. Ranges ranges;
  7664. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7665. ranges.emplace_back(0, -1);
  7666. }
  7667. auto res = cli_.Get("/streamed-with-range?error",
  7668. Headers{{make_range_header(ranges)}});
  7669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7670. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7671. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7672. EXPECT_EQ(false, res->has_header("Content-Range"));
  7673. EXPECT_EQ(0U, res->body.size());
  7674. }
  7675. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7676. auto res = cli_.Get("/streamed-with-range",
  7677. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7679. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7680. EXPECT_EQ(5U, res->body.size());
  7681. // Check that overlapping ranges are coalesced into a single range
  7682. EXPECT_EQ("bcdef", res->body);
  7683. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7684. // Should be single range, not multipart
  7685. EXPECT_TRUE(res->has_header("Content-Range"));
  7686. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7687. }
  7688. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7689. auto res = cli_.Get("/streamed-with-range",
  7690. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7693. EXPECT_EQ(268U, res->body.size());
  7694. // Check that both range contents are present
  7695. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7696. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7697. // Check that Content-Range headers are present for both ranges
  7698. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7699. std::string::npos);
  7700. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7701. std::string::npos);
  7702. }
  7703. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7704. auto res = cli_.Get("/streamed-with-range",
  7705. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7707. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7708. EXPECT_EQ(269U, res->body.size());
  7709. // Check that both duplicate range contents are present
  7710. size_t first_abc = res->body.find("abc\r\n");
  7711. EXPECT_TRUE(first_abc != std::string::npos);
  7712. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7713. EXPECT_TRUE(second_abc != std::string::npos);
  7714. // Check that Content-Range headers are present for both ranges
  7715. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7716. EXPECT_TRUE(first_range != std::string::npos);
  7717. size_t second_range =
  7718. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7719. EXPECT_TRUE(second_range != std::string::npos);
  7720. }
  7721. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7722. auto res =
  7723. cli_.Get("/streamed-with-range?error",
  7724. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7727. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7728. EXPECT_EQ(false, res->has_header("Content-Range"));
  7729. EXPECT_EQ(0U, res->body.size());
  7730. }
  7731. TEST_F(ServerTest, GetStreamedEndless) {
  7732. uint64_t offset = 0;
  7733. auto res = cli_.Get("/streamed-cancel",
  7734. [&](const char * /*data*/, uint64_t data_length) {
  7735. if (offset < 100) {
  7736. offset += data_length;
  7737. return true;
  7738. }
  7739. return false;
  7740. });
  7741. ASSERT_TRUE(!res);
  7742. EXPECT_EQ(Error::Canceled, res.error());
  7743. }
  7744. TEST_F(ServerTest, ClientStop) {
  7745. std::atomic_size_t count{4};
  7746. std::vector<std::thread> threads;
  7747. for (auto i = count.load(); i != 0; --i) {
  7748. threads.emplace_back([&]() {
  7749. auto res = cli_.Get("/streamed-cancel",
  7750. [&](const char *, uint64_t) { return true; });
  7751. --count;
  7752. ASSERT_TRUE(!res);
  7753. EXPECT_TRUE(res.error() == Error::Canceled ||
  7754. res.error() == Error::Read || res.error() == Error::Write);
  7755. });
  7756. }
  7757. std::this_thread::sleep_for(std::chrono::seconds(2));
  7758. while (count != 0) {
  7759. cli_.stop();
  7760. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7761. }
  7762. for (auto &t : threads) {
  7763. t.join();
  7764. }
  7765. }
  7766. TEST_F(ServerTest, GetWithRange1) {
  7767. auto res = cli_.Get("/with-range", Headers{
  7768. make_range_header({{3, 5}}),
  7769. {"Accept-Encoding", ""},
  7770. });
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7773. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7774. EXPECT_EQ(true, res->has_header("Content-Range"));
  7775. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7776. EXPECT_EQ(std::string("def"), res->body);
  7777. }
  7778. TEST_F(ServerTest, GetWithRange2) {
  7779. auto res = cli_.Get("/with-range", Headers{
  7780. make_range_header({{1, -1}}),
  7781. {"Accept-Encoding", ""},
  7782. });
  7783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7785. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7786. EXPECT_EQ(true, res->has_header("Content-Range"));
  7787. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7788. EXPECT_EQ(std::string("bcdefg"), res->body);
  7789. }
  7790. TEST_F(ServerTest, GetWithRange3) {
  7791. auto res = cli_.Get("/with-range", Headers{
  7792. make_range_header({{0, 0}}),
  7793. {"Accept-Encoding", ""},
  7794. });
  7795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7796. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7797. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7798. EXPECT_EQ(true, res->has_header("Content-Range"));
  7799. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7800. EXPECT_EQ(std::string("a"), res->body);
  7801. }
  7802. TEST_F(ServerTest, GetWithRange4) {
  7803. auto res = cli_.Get("/with-range", Headers{
  7804. make_range_header({{-1, 2}}),
  7805. {"Accept-Encoding", ""},
  7806. });
  7807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7808. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7809. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7810. EXPECT_EQ(true, res->has_header("Content-Range"));
  7811. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7812. EXPECT_EQ(std::string("fg"), res->body);
  7813. }
  7814. TEST_F(ServerTest, GetWithRange5) {
  7815. auto res = cli_.Get("/with-range", Headers{
  7816. make_range_header({{0, 5}}),
  7817. {"Accept-Encoding", ""},
  7818. });
  7819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7820. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7821. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7822. EXPECT_EQ(true, res->has_header("Content-Range"));
  7823. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7824. EXPECT_EQ(std::string("abcdef"), res->body);
  7825. }
  7826. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7827. auto res =
  7828. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7830. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7831. }
  7832. TEST_F(ServerTest, GetWithRangeMultipart) {
  7833. auto res =
  7834. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7836. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7837. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7838. EXPECT_EQ(false, res->has_header("Content-Range"));
  7839. EXPECT_EQ(267U, res->body.size());
  7840. }
  7841. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7842. auto res = cli_.Get("/with-range",
  7843. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7845. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7846. }
  7847. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7848. auto res = cli_.Get("/with-range-customized-response",
  7849. Headers{{make_range_header({{1, 2}})}});
  7850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7851. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7852. EXPECT_EQ(true, res->has_header("Content-Length"));
  7853. EXPECT_EQ(false, res->has_header("Content-Range"));
  7854. EXPECT_EQ(JSON_DATA, res->body);
  7855. }
  7856. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7857. auto res = cli_.Get("/with-range-customized-response",
  7858. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7860. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7861. EXPECT_EQ(true, res->has_header("Content-Length"));
  7862. EXPECT_EQ(false, res->has_header("Content-Range"));
  7863. EXPECT_EQ(JSON_DATA, res->body);
  7864. }
  7865. TEST_F(ServerTest, Issue1772) {
  7866. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7868. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7869. }
  7870. TEST_F(ServerTest, Issue609) {
  7871. auto res = cli_.Delete("/issue609");
  7872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7873. EXPECT_EQ(StatusCode::OK_200, res->status);
  7874. EXPECT_EQ(std::string("ok"), res->body);
  7875. }
  7876. TEST_F(ServerTest, GetStreamedChunked) {
  7877. auto res = cli_.Get("/streamed-chunked");
  7878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7879. EXPECT_EQ(StatusCode::OK_200, res->status);
  7880. EXPECT_EQ(std::string("123456789"), res->body);
  7881. }
  7882. TEST_F(ServerTest, GetStreamedChunked2) {
  7883. auto res = cli_.Get("/streamed-chunked2");
  7884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7885. EXPECT_EQ(StatusCode::OK_200, res->status);
  7886. EXPECT_EQ(std::string("123456789"), res->body);
  7887. }
  7888. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7889. auto res = cli_.Get("/streamed-chunked-with-trailer");
  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. EXPECT_TRUE(res->has_header("Trailer"));
  7894. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7895. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7896. // Trailers are now stored separately from headers (security fix)
  7897. EXPECT_EQ(2U, res->trailers.size());
  7898. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7899. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7900. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7901. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7902. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7903. // Verify trailers are NOT in headers (security verification)
  7904. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7905. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7906. }
  7907. TEST_F(ServerTest, LargeChunkedPost) {
  7908. Request req;
  7909. req.method = "POST";
  7910. req.path = "/large-chunked";
  7911. std::string host_and_port;
  7912. host_and_port += HOST;
  7913. host_and_port += ":";
  7914. host_and_port += std::to_string(PORT);
  7915. req.headers.emplace("Host", host_and_port.c_str());
  7916. req.headers.emplace("Accept", "*/*");
  7917. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7918. req.headers.emplace("Content-Type", "text/plain");
  7919. req.headers.emplace("Content-Length", "0");
  7920. req.headers.emplace("Transfer-Encoding", "chunked");
  7921. std::string long_string(30 * 1024u, 'a');
  7922. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7923. // Attempt to make a large enough post to exceed OS buffers, to test that
  7924. // the server handles short reads if the full chunk data isn't available.
  7925. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7926. auto res = std::make_shared<Response>();
  7927. auto error = Error::Success;
  7928. auto ret = cli_.send(req, *res, error);
  7929. ASSERT_TRUE(ret);
  7930. EXPECT_EQ(StatusCode::OK_200, res->status);
  7931. }
  7932. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7933. auto res = cli_.Get("/remote_addr");
  7934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7935. EXPECT_EQ(StatusCode::OK_200, res->status);
  7936. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7937. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7938. }
  7939. TEST_F(ServerTest, GetMethodLocalAddr) {
  7940. auto res = cli_.Get("/local_addr");
  7941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7942. EXPECT_EQ(StatusCode::OK_200, res->status);
  7943. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7944. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7945. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7946. }
  7947. TEST_F(ServerTest, HTTPResponseSplitting) {
  7948. auto res = cli_.Get("/http_response_splitting");
  7949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7950. EXPECT_EQ(StatusCode::OK_200, res->status);
  7951. }
  7952. TEST_F(ServerTest, SlowRequest) {
  7953. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7954. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7955. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7956. }
  7957. #if 0
  7958. TEST_F(ServerTest, SlowPost) {
  7959. char buffer[64 * 1024];
  7960. memset(buffer, 0x42, sizeof(buffer));
  7961. auto res = cli_.Post(
  7962. "/slowpost", 64 * 1024 * 1024,
  7963. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7964. auto ret = sink.write(buffer, sizeof(buffer));
  7965. EXPECT_TRUE(ret);
  7966. return true;
  7967. },
  7968. "text/plain");
  7969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7970. EXPECT_EQ(StatusCode::OK_200, res->status);
  7971. }
  7972. TEST_F(ServerTest, SlowPostFail) {
  7973. char buffer[64 * 1024];
  7974. memset(buffer, 0x42, sizeof(buffer));
  7975. cli_.set_write_timeout(std::chrono::seconds(0));
  7976. auto res = cli_.Post(
  7977. "/slowpost", 64 * 1024 * 1024,
  7978. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7979. sink.write(buffer, sizeof(buffer));
  7980. return true;
  7981. },
  7982. "text/plain");
  7983. ASSERT_TRUE(!res);
  7984. EXPECT_EQ(Error::Write, res.error());
  7985. }
  7986. #endif
  7987. TEST_F(ServerTest, Put) {
  7988. auto res = cli_.Put("/put", "PUT", "text/plain");
  7989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7990. EXPECT_EQ(StatusCode::OK_200, res->status);
  7991. EXPECT_EQ("PUT", res->body);
  7992. }
  7993. TEST_F(ServerTest, PutWithContentProvider) {
  7994. auto res = cli_.Put(
  7995. "/put", 3,
  7996. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7997. sink.os << "PUT";
  7998. return true;
  7999. },
  8000. "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, PostWithContentProviderAbort) {
  8006. auto res = cli_.Post(
  8007. "/post", 42,
  8008. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8009. return false;
  8010. },
  8011. "text/plain");
  8012. ASSERT_TRUE(!res);
  8013. EXPECT_EQ(Error::Canceled, res.error());
  8014. }
  8015. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8016. auto res = cli_.Put(
  8017. "/put",
  8018. [](size_t /*offset*/, DataSink &sink) {
  8019. sink.os << "PUT";
  8020. sink.done();
  8021. return true;
  8022. },
  8023. "text/plain");
  8024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8025. EXPECT_EQ(StatusCode::OK_200, res->status);
  8026. EXPECT_EQ("PUT", res->body);
  8027. }
  8028. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8029. auto res = cli_.Post(
  8030. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8031. "text/plain");
  8032. ASSERT_TRUE(!res);
  8033. EXPECT_EQ(Error::Canceled, res.error());
  8034. }
  8035. TEST_F(ServerTest, PostLoopBack) {
  8036. std::string body;
  8037. auto res = cli_.Post(
  8038. "/post-loopback", 9,
  8039. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8040. EXPECT_EQ(9u, length);
  8041. sink.write("123", 3);
  8042. sink.write("456", 3);
  8043. sink.write("789", 3);
  8044. return true;
  8045. },
  8046. "text/plain",
  8047. [&body](const char *data, size_t data_length) {
  8048. body.append(data, data_length);
  8049. return true;
  8050. });
  8051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8052. EXPECT_EQ(StatusCode::OK_200, res->status);
  8053. EXPECT_EQ("123456789", body);
  8054. }
  8055. TEST_F(ServerTest, PutLoopBack) {
  8056. std::string body;
  8057. auto res = cli_.Put(
  8058. "/put-loopback", 9,
  8059. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8060. EXPECT_EQ(9u, length);
  8061. sink.write("123", 3);
  8062. sink.write("456", 3);
  8063. sink.write("789", 3);
  8064. return true;
  8065. },
  8066. "text/plain",
  8067. [&body](const char *data, size_t data_length) {
  8068. body.append(data, data_length);
  8069. return true;
  8070. });
  8071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8072. EXPECT_EQ(StatusCode::OK_200, res->status);
  8073. EXPECT_EQ("123456789", body);
  8074. }
  8075. TEST_F(ServerTest, PatchLoopBack) {
  8076. std::string body;
  8077. auto res = cli_.Patch(
  8078. "/patch-loopback", 9,
  8079. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8080. EXPECT_EQ(9u, length);
  8081. sink.write("123", 3);
  8082. sink.write("456", 3);
  8083. sink.write("789", 3);
  8084. return true;
  8085. },
  8086. "text/plain",
  8087. [&body](const char *data, size_t data_length) {
  8088. body.append(data, data_length);
  8089. return true;
  8090. });
  8091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8092. EXPECT_EQ(StatusCode::OK_200, res->status);
  8093. EXPECT_EQ("123456789", body);
  8094. }
  8095. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8096. std::string body;
  8097. auto res = cli_.Post(
  8098. "/post-loopback",
  8099. [](size_t /*offset*/, DataSink &sink) {
  8100. sink.write("123", 3);
  8101. sink.write("456", 3);
  8102. sink.write("789", 3);
  8103. sink.done();
  8104. return true;
  8105. },
  8106. "text/plain",
  8107. [&body](const char *data, size_t data_length) {
  8108. body.append(data, data_length);
  8109. return true;
  8110. });
  8111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8112. EXPECT_EQ(StatusCode::OK_200, res->status);
  8113. EXPECT_EQ("123456789", body);
  8114. }
  8115. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8116. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8117. cli_.set_compress(true);
  8118. auto res = cli_.Put(
  8119. "/put", 3,
  8120. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8121. sink.os << "PUT";
  8122. return true;
  8123. },
  8124. "text/plain");
  8125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8126. EXPECT_EQ(StatusCode::OK_200, res->status);
  8127. EXPECT_EQ("PUT", res->body);
  8128. }
  8129. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8130. cli_.set_compress(true);
  8131. auto res = cli_.Post(
  8132. "/post", 42,
  8133. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8134. return false;
  8135. },
  8136. "text/plain");
  8137. ASSERT_TRUE(!res);
  8138. EXPECT_EQ(Error::Canceled, res.error());
  8139. }
  8140. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8141. cli_.set_compress(true);
  8142. auto res = cli_.Put(
  8143. "/put",
  8144. [](size_t /*offset*/, DataSink &sink) {
  8145. sink.os << "PUT";
  8146. sink.done();
  8147. return true;
  8148. },
  8149. "text/plain");
  8150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8151. EXPECT_EQ(StatusCode::OK_200, res->status);
  8152. EXPECT_EQ("PUT", res->body);
  8153. }
  8154. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8155. cli_.set_compress(true);
  8156. auto res = cli_.Post(
  8157. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8158. "text/plain");
  8159. ASSERT_TRUE(!res);
  8160. EXPECT_EQ(Error::Canceled, res.error());
  8161. }
  8162. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8163. cli_.set_compress(true);
  8164. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8166. EXPECT_EQ(StatusCode::OK_200, res->status);
  8167. EXPECT_EQ(LARGE_DATA, res->body);
  8168. }
  8169. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8170. #ifdef CPPHTTPLIB_SSL_ENABLED
  8171. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8172. Client cli(s.c_str());
  8173. cli.enable_server_certificate_verification(false);
  8174. #else
  8175. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8176. Client cli(s.c_str());
  8177. #endif
  8178. cli.set_compress(true);
  8179. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8181. EXPECT_EQ(StatusCode::OK_200, res->status);
  8182. EXPECT_EQ(LARGE_DATA, res->body);
  8183. // The compressed size should be less than a 10th of the original. May vary
  8184. // depending on the zlib library.
  8185. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8186. static_cast<uint64_t>(10 * 1024 * 1024));
  8187. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8188. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8189. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8190. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8191. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8192. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8193. #endif
  8194. }
  8195. TEST_F(ServerTest, PutContentWithDeflate) {
  8196. cli_.set_compress(false);
  8197. Headers headers;
  8198. headers.emplace("Content-Encoding", "deflate");
  8199. // PUT in deflate format:
  8200. auto res = cli_.Put("/put", headers,
  8201. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8203. EXPECT_EQ(StatusCode::OK_200, res->status);
  8204. EXPECT_EQ("PUT", res->body);
  8205. }
  8206. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8207. Headers headers;
  8208. headers.emplace("Accept-Encoding", "gzip, deflate");
  8209. auto res = cli_.Get("/streamed-chunked", headers);
  8210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8211. EXPECT_EQ(StatusCode::OK_200, res->status);
  8212. EXPECT_EQ(std::string("123456789"), res->body);
  8213. }
  8214. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8215. Headers headers;
  8216. headers.emplace("Accept-Encoding", "gzip, deflate");
  8217. auto res = cli_.Get("/streamed-chunked2", headers);
  8218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8219. EXPECT_EQ(StatusCode::OK_200, res->status);
  8220. EXPECT_EQ(std::string("123456789"), res->body);
  8221. }
  8222. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8223. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ(StatusCode::OK_200, res->status);
  8226. }
  8227. TEST(GzipDecompressor, ChunkedDecompression) {
  8228. std::string data;
  8229. for (size_t i = 0; i < 32 * 1024; ++i) {
  8230. data.push_back(static_cast<char>('a' + i % 26));
  8231. }
  8232. std::string compressed_data;
  8233. {
  8234. httplib::detail::gzip_compressor compressor;
  8235. bool result = compressor.compress(
  8236. data.data(), data.size(),
  8237. /*last=*/true,
  8238. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8239. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8240. compressed_data_size);
  8241. return true;
  8242. });
  8243. ASSERT_TRUE(result);
  8244. }
  8245. std::string decompressed_data;
  8246. {
  8247. httplib::detail::gzip_decompressor decompressor;
  8248. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8249. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8250. size_t chunk_size = 130;
  8251. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8252. chunk_begin += chunk_size) {
  8253. size_t current_chunk_size =
  8254. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8255. bool result = decompressor.decompress(
  8256. compressed_data.data() + chunk_begin, current_chunk_size,
  8257. [&](const char *decompressed_data_chunk,
  8258. size_t decompressed_data_chunk_size) {
  8259. decompressed_data.insert(decompressed_data.size(),
  8260. decompressed_data_chunk,
  8261. decompressed_data_chunk_size);
  8262. return true;
  8263. });
  8264. ASSERT_TRUE(result);
  8265. }
  8266. }
  8267. ASSERT_EQ(data, decompressed_data);
  8268. }
  8269. TEST(GzipDecompressor, DeflateDecompression) {
  8270. std::string original_text = "Raw deflate without gzip";
  8271. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8272. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8273. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8274. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8275. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8276. std::string decompressed_data;
  8277. {
  8278. httplib::detail::gzip_decompressor decompressor;
  8279. bool result = decompressor.decompress(
  8280. compressed_data.data(), compressed_data.size(),
  8281. [&](const char *decompressed_data_chunk,
  8282. size_t decompressed_data_chunk_size) {
  8283. decompressed_data.insert(decompressed_data.size(),
  8284. decompressed_data_chunk,
  8285. decompressed_data_chunk_size);
  8286. return true;
  8287. });
  8288. ASSERT_TRUE(result);
  8289. }
  8290. ASSERT_EQ(original_text, decompressed_data);
  8291. }
  8292. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8293. std::string original_text = "Raw deflate without gzip";
  8294. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8295. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8296. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8297. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8298. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8299. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8300. std::string decompressed_data;
  8301. {
  8302. httplib::detail::gzip_decompressor decompressor;
  8303. bool result = decompressor.decompress(
  8304. compressed_data.data(), compressed_data.size(),
  8305. [&](const char *decompressed_data_chunk,
  8306. size_t decompressed_data_chunk_size) {
  8307. decompressed_data.insert(decompressed_data.size(),
  8308. decompressed_data_chunk,
  8309. decompressed_data_chunk_size);
  8310. return true;
  8311. });
  8312. ASSERT_TRUE(result);
  8313. }
  8314. ASSERT_EQ(original_text, decompressed_data);
  8315. }
  8316. #endif
  8317. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8318. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8319. Headers headers;
  8320. headers.emplace("Accept-Encoding", "br");
  8321. auto res = cli_.Get("/streamed-chunked", headers);
  8322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8323. EXPECT_EQ(StatusCode::OK_200, res->status);
  8324. EXPECT_EQ(std::string("123456789"), res->body);
  8325. }
  8326. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8327. Headers headers;
  8328. headers.emplace("Accept-Encoding", "br");
  8329. auto res = cli_.Get("/streamed-chunked2", headers);
  8330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8331. EXPECT_EQ(StatusCode::OK_200, res->status);
  8332. EXPECT_EQ(std::string("123456789"), res->body);
  8333. }
  8334. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8335. cli_.set_compress(true);
  8336. auto res = cli_.Put(
  8337. "/put", 3,
  8338. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8339. sink.os << "PUT";
  8340. return true;
  8341. },
  8342. "text/plain");
  8343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8344. EXPECT_EQ(StatusCode::OK_200, res->status);
  8345. EXPECT_EQ("PUT", res->body);
  8346. }
  8347. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8348. cli_.set_compress(true);
  8349. auto res = cli_.Put(
  8350. "/put",
  8351. [](size_t /*offset*/, DataSink &sink) {
  8352. sink.os << "PUT";
  8353. sink.done();
  8354. return true;
  8355. },
  8356. "text/plain");
  8357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8358. EXPECT_EQ(StatusCode::OK_200, res->status);
  8359. EXPECT_EQ("PUT", res->body);
  8360. }
  8361. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8362. cli_.set_compress(true);
  8363. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8365. EXPECT_EQ(StatusCode::OK_200, res->status);
  8366. EXPECT_EQ(LARGE_DATA, res->body);
  8367. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8368. }
  8369. #endif
  8370. TEST_F(ServerTest, Patch) {
  8371. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8373. EXPECT_EQ(StatusCode::OK_200, res->status);
  8374. EXPECT_EQ("PATCH", res->body);
  8375. }
  8376. TEST_F(ServerTest, Delete) {
  8377. auto res = cli_.Delete("/delete");
  8378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8379. EXPECT_EQ(StatusCode::OK_200, res->status);
  8380. EXPECT_EQ("DELETE", res->body);
  8381. }
  8382. TEST_F(ServerTest, DeleteContentReceiver) {
  8383. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8385. EXPECT_EQ(StatusCode::OK_200, res->status);
  8386. EXPECT_EQ("content", res->body);
  8387. }
  8388. TEST_F(ServerTest, Options) {
  8389. auto res = cli_.Options("*");
  8390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8391. EXPECT_EQ(StatusCode::OK_200, res->status);
  8392. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8393. EXPECT_TRUE(res->body.empty());
  8394. }
  8395. TEST_F(ServerTest, URL) {
  8396. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8398. EXPECT_EQ(StatusCode::OK_200, res->status);
  8399. }
  8400. TEST_F(ServerTest, ArrayParam) {
  8401. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8403. EXPECT_EQ(StatusCode::OK_200, res->status);
  8404. }
  8405. TEST_F(ServerTest, ArrayParamValues) {
  8406. auto res =
  8407. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8409. EXPECT_EQ(StatusCode::OK_200, res->status);
  8410. }
  8411. TEST_F(ServerTest, NoMultipleHeaders) {
  8412. Headers headers = {{"Content-Length", "5"}};
  8413. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8414. "text/plain");
  8415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8416. EXPECT_EQ(StatusCode::OK_200, res->status);
  8417. }
  8418. TEST_F(ServerTest, PostContentReceiver) {
  8419. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8421. ASSERT_EQ(StatusCode::OK_200, res->status);
  8422. ASSERT_EQ("content", res->body);
  8423. }
  8424. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8425. UploadFormDataItems items = {
  8426. {"text1", "text default", "", ""},
  8427. {"text2", "aωb", "", ""},
  8428. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8429. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8430. {"file3", "", "", "application/octet-stream"},
  8431. };
  8432. auto res = cli_.Post("/content_receiver", items);
  8433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8434. EXPECT_EQ(StatusCode::OK_200, res->status);
  8435. }
  8436. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  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 boundary = std::string("+++++");
  8445. std::string body;
  8446. for (const auto &item : items) {
  8447. body += "--" + boundary + "\r\n";
  8448. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8449. if (!item.filename.empty()) {
  8450. body += "; filename=\"" + item.filename + "\"";
  8451. }
  8452. body += "\r\n";
  8453. if (!item.content_type.empty()) {
  8454. body += "Content-Type: " + item.content_type + "\r\n";
  8455. }
  8456. body += "\r\n";
  8457. body += item.content + "\r\n";
  8458. }
  8459. body += "--" + boundary + "--\r\n";
  8460. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8461. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8463. EXPECT_EQ(StatusCode::OK_200, res->status);
  8464. }
  8465. TEST(MultipartFormDataTest, FieldEscaping) {
  8466. Server svr;
  8467. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8468. const ContentReader &content_reader) {
  8469. ASSERT_TRUE(req.is_multipart_form_data());
  8470. std::vector<FormData> received;
  8471. content_reader(
  8472. [&](const FormData &file) {
  8473. received.push_back(file);
  8474. return true;
  8475. },
  8476. [&](const char *data, size_t data_length) {
  8477. received.back().content.append(data, data_length);
  8478. return true;
  8479. });
  8480. // '"', CR and LF in names and filenames are escaped following the
  8481. // WHATWG HTML standard, so each part still parses as a single part
  8482. // with no injected headers. Content types get CR/LF escaped too,
  8483. // while '"' (legal there, e.g. quoted charset) is preserved.
  8484. ASSERT_EQ(4U, received.size());
  8485. EXPECT_EQ("na%22me", received[0].name);
  8486. EXPECT_EQ("quoted name", received[0].content);
  8487. EXPECT_EQ("file", received[1].name);
  8488. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8489. received[1].filename);
  8490. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8491. EXPECT_EQ("injected", received[1].content);
  8492. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8493. EXPECT_EQ("my%22file.txt", received[2].filename);
  8494. EXPECT_EQ("cr lf name", received[2].content);
  8495. EXPECT_EQ("typed", received[3].name);
  8496. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8497. received[3].content_type);
  8498. EXPECT_EQ("typed content", received[3].content);
  8499. });
  8500. auto port = svr.bind_to_any_port("localhost");
  8501. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8502. auto se = detail::scope_exit([&] {
  8503. svr.stop();
  8504. t.join();
  8505. ASSERT_FALSE(svr.is_running());
  8506. });
  8507. svr.wait_until_ready();
  8508. Client cli("localhost", port);
  8509. UploadFormDataItems items = {
  8510. {"na\"me", "quoted name", "", ""},
  8511. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8512. "application/octet-stream"},
  8513. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8514. {"typed", "typed content", "",
  8515. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8516. };
  8517. auto res = cli.Post("/post", items);
  8518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8519. EXPECT_EQ(StatusCode::OK_200, res->status);
  8520. }
  8521. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8522. const UploadFormDataItems items = {
  8523. {"name1", "Content 1", "", ""},
  8524. {"name2", "Content 2", "file2.txt", "text/plain"},
  8525. };
  8526. Server svr;
  8527. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8528. const ContentReader &content_reader) {
  8529. ASSERT_TRUE(req.is_multipart_form_data());
  8530. std::vector<FormData> received;
  8531. content_reader(
  8532. [&](const FormData &file) {
  8533. received.push_back(file);
  8534. return true;
  8535. },
  8536. [&](const char *data, size_t data_length) {
  8537. received.back().content.append(data, data_length);
  8538. return true;
  8539. });
  8540. ASSERT_EQ(2U, received.size());
  8541. EXPECT_EQ("name1", received[0].name);
  8542. EXPECT_EQ("Content 1", received[0].content);
  8543. EXPECT_EQ("name2", received[1].name);
  8544. EXPECT_EQ("Content 2", received[1].content);
  8545. EXPECT_EQ("file2.txt", received[1].filename);
  8546. EXPECT_EQ("text/plain", received[1].content_type);
  8547. });
  8548. auto port = svr.bind_to_any_port("localhost");
  8549. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8550. auto se = detail::scope_exit([&] {
  8551. svr.stop();
  8552. t.join();
  8553. ASSERT_FALSE(svr.is_running());
  8554. });
  8555. svr.wait_until_ready();
  8556. Client cli("localhost", port);
  8557. // Whole-body serialization with a generated boundary
  8558. {
  8559. MultipartFormDataWriter writer;
  8560. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8561. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8562. writer.content_type());
  8563. auto body = writer.serialize(items);
  8564. EXPECT_EQ(body.size(), writer.content_length(items));
  8565. auto res = cli.Post("/post", body, writer.content_type());
  8566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8567. EXPECT_EQ(StatusCode::OK_200, res->status);
  8568. }
  8569. // Per-part framing with a custom boundary via a content provider
  8570. {
  8571. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8572. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8573. MultipartFormDataWriter writer("custom-boundary_123");
  8574. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8575. std::string body;
  8576. for (const auto &item : items) {
  8577. body += writer.item_begin(item);
  8578. body += item.content;
  8579. body += MultipartFormDataWriter::item_end();
  8580. }
  8581. body += writer.finish();
  8582. EXPECT_EQ(body.size(), writer.content_length(items));
  8583. auto res = cli.Post(
  8584. "/post", body.size(),
  8585. [&](size_t offset, size_t length, DataSink &sink) {
  8586. sink.write(body.data() + offset, length);
  8587. return true;
  8588. },
  8589. writer.content_type());
  8590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8591. EXPECT_EQ(StatusCode::OK_200, res->status);
  8592. }
  8593. }
  8594. TEST_F(ServerTest, PostContentReceiverGzip) {
  8595. cli_.set_compress(true);
  8596. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8598. ASSERT_EQ(StatusCode::OK_200, res->status);
  8599. ASSERT_EQ("content", res->body);
  8600. }
  8601. TEST_F(ServerTest, PutContentReceiver) {
  8602. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8604. ASSERT_EQ(StatusCode::OK_200, res->status);
  8605. ASSERT_EQ("content", res->body);
  8606. }
  8607. TEST_F(ServerTest, PatchContentReceiver) {
  8608. auto res = cli_.Patch("/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. template <typename ClientType>
  8614. void TestWithHeadersAndContentReceiver(
  8615. ClientType &cli,
  8616. std::function<Result(ClientType &, const std::string &, const Headers &,
  8617. const std::string &, const std::string &,
  8618. ContentReceiver, DownloadProgress)>
  8619. request_func) {
  8620. Headers headers;
  8621. headers.emplace("X-Custom-Header", "test-value");
  8622. std::string received_body;
  8623. auto res = request_func(
  8624. cli, "/content_receiver", headers, "content", "application/json",
  8625. [&](const char *data, size_t data_length) {
  8626. received_body.append(data, data_length);
  8627. return true;
  8628. },
  8629. nullptr);
  8630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8631. EXPECT_EQ(StatusCode::OK_200, res->status);
  8632. EXPECT_EQ("content", received_body);
  8633. }
  8634. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8635. #ifdef CPPHTTPLIB_SSL_ENABLED
  8636. using ClientT = SSLClient;
  8637. #else
  8638. using ClientT = Client;
  8639. #endif
  8640. TestWithHeadersAndContentReceiver<ClientT>(
  8641. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8642. const std::string &body, const std::string &content_type,
  8643. ContentReceiver receiver, DownloadProgress progress) {
  8644. return cli.Post(path, headers, body, content_type, receiver, progress);
  8645. });
  8646. }
  8647. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8648. #ifdef CPPHTTPLIB_SSL_ENABLED
  8649. using ClientT = SSLClient;
  8650. #else
  8651. using ClientT = Client;
  8652. #endif
  8653. TestWithHeadersAndContentReceiver<ClientT>(
  8654. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8655. const std::string &body, const std::string &content_type,
  8656. ContentReceiver receiver, DownloadProgress progress) {
  8657. return cli.Put(path, headers, body, content_type, receiver, progress);
  8658. });
  8659. }
  8660. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8661. #ifdef CPPHTTPLIB_SSL_ENABLED
  8662. using ClientT = SSLClient;
  8663. #else
  8664. using ClientT = Client;
  8665. #endif
  8666. TestWithHeadersAndContentReceiver<ClientT>(
  8667. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8668. const std::string &body, const std::string &content_type,
  8669. ContentReceiver receiver, DownloadProgress progress) {
  8670. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8671. });
  8672. }
  8673. template <typename ClientType>
  8674. void TestWithHeadersAndContentReceiverWithProgress(
  8675. ClientType &cli,
  8676. std::function<Result(ClientType &, const std::string &, const Headers &,
  8677. const std::string &, const std::string &,
  8678. ContentReceiver, DownloadProgress)>
  8679. request_func) {
  8680. Headers headers;
  8681. headers.emplace("X-Test-Header", "progress-test");
  8682. std::string received_body;
  8683. auto progress_called = false;
  8684. auto res = request_func(
  8685. cli, "/content_receiver", headers, "content", "text/plain",
  8686. [&](const char *data, size_t data_length) {
  8687. received_body.append(data, data_length);
  8688. return true;
  8689. },
  8690. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8691. progress_called = true;
  8692. return true;
  8693. });
  8694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8695. EXPECT_EQ(StatusCode::OK_200, res->status);
  8696. EXPECT_EQ("content", received_body);
  8697. EXPECT_TRUE(progress_called);
  8698. }
  8699. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8700. #ifdef CPPHTTPLIB_SSL_ENABLED
  8701. using ClientT = SSLClient;
  8702. #else
  8703. using ClientT = Client;
  8704. #endif
  8705. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8706. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8707. const std::string &body, const std::string &content_type,
  8708. ContentReceiver receiver, DownloadProgress progress) {
  8709. return cli.Post(path, headers, body, content_type, receiver, progress);
  8710. });
  8711. }
  8712. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8713. #ifdef CPPHTTPLIB_SSL_ENABLED
  8714. using ClientT = SSLClient;
  8715. #else
  8716. using ClientT = Client;
  8717. #endif
  8718. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8719. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8720. const std::string &body, const std::string &content_type,
  8721. ContentReceiver receiver, DownloadProgress progress) {
  8722. return cli.Put(path, headers, body, content_type, receiver, progress);
  8723. });
  8724. }
  8725. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8726. #ifdef CPPHTTPLIB_SSL_ENABLED
  8727. using ClientT = SSLClient;
  8728. #else
  8729. using ClientT = Client;
  8730. #endif
  8731. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8732. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8733. const std::string &body, const std::string &content_type,
  8734. ContentReceiver receiver, DownloadProgress progress) {
  8735. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8736. });
  8737. }
  8738. template <typename ClientType>
  8739. void TestWithHeadersAndContentReceiverError(
  8740. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8741. const Headers &, const std::string &,
  8742. const std::string &, ContentReceiver)>
  8743. request_func) {
  8744. Headers headers;
  8745. headers.emplace("X-Error-Test", "true");
  8746. std::string received_body;
  8747. auto receiver_failed = false;
  8748. auto res =
  8749. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8750. [&](const char *data, size_t data_length) {
  8751. received_body.append(data, data_length);
  8752. receiver_failed = true;
  8753. return false;
  8754. });
  8755. ASSERT_FALSE(res);
  8756. EXPECT_TRUE(receiver_failed);
  8757. }
  8758. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8759. #ifdef CPPHTTPLIB_SSL_ENABLED
  8760. using ClientT = SSLClient;
  8761. #else
  8762. using ClientT = Client;
  8763. #endif
  8764. TestWithHeadersAndContentReceiverError<ClientT>(
  8765. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8766. const std::string &body, const std::string &content_type,
  8767. ContentReceiver receiver) {
  8768. return cli.Post(path, headers, body, content_type, receiver);
  8769. });
  8770. }
  8771. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8772. #ifdef CPPHTTPLIB_SSL_ENABLED
  8773. using ClientT = SSLClient;
  8774. #else
  8775. using ClientT = Client;
  8776. #endif
  8777. TestWithHeadersAndContentReceiverError<ClientT>(
  8778. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8779. const std::string &body, const std::string &content_type,
  8780. ContentReceiver receiver) {
  8781. return cli.Put(path, headers, body, content_type, receiver);
  8782. });
  8783. }
  8784. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8785. #ifdef CPPHTTPLIB_SSL_ENABLED
  8786. using ClientT = SSLClient;
  8787. #else
  8788. using ClientT = Client;
  8789. #endif
  8790. TestWithHeadersAndContentReceiverError<ClientT>(
  8791. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8792. const std::string &body, const std::string &content_type,
  8793. ContentReceiver receiver) {
  8794. return cli.Patch(path, headers, body, content_type, receiver);
  8795. });
  8796. }
  8797. TEST_F(ServerTest, PostQueryStringAndBody) {
  8798. auto res =
  8799. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8801. ASSERT_EQ(StatusCode::OK_200, res->status);
  8802. }
  8803. TEST_F(ServerTest, HTTP2Magic) {
  8804. Request req;
  8805. req.method = "PRI";
  8806. req.path = "*";
  8807. req.body = "SM";
  8808. auto res = std::make_shared<Response>();
  8809. auto error = Error::Success;
  8810. auto ret = cli_.send(req, *res, error);
  8811. ASSERT_TRUE(ret);
  8812. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8813. }
  8814. TEST_F(ServerTest, KeepAlive) {
  8815. auto res = cli_.Get("/hi");
  8816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8817. EXPECT_EQ(StatusCode::OK_200, res->status);
  8818. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8819. EXPECT_EQ("Hello World!", res->body);
  8820. res = cli_.Get("/hi");
  8821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8822. EXPECT_EQ(StatusCode::OK_200, res->status);
  8823. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8824. EXPECT_EQ("Hello World!", res->body);
  8825. res = cli_.Get("/hi");
  8826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8827. EXPECT_EQ(StatusCode::OK_200, res->status);
  8828. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8829. EXPECT_EQ("Hello World!", res->body);
  8830. res = cli_.Get("/not-exist");
  8831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8832. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8833. res = cli_.Post("/empty", "", "text/plain");
  8834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8835. EXPECT_EQ(StatusCode::OK_200, res->status);
  8836. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8837. EXPECT_EQ("empty", res->body);
  8838. EXPECT_EQ("close", res->get_header_value("Connection"));
  8839. res = cli_.Post(
  8840. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8841. "text/plain");
  8842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8843. EXPECT_EQ(StatusCode::OK_200, res->status);
  8844. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8845. EXPECT_EQ("empty", res->body);
  8846. cli_.set_keep_alive(false);
  8847. res = cli_.Get("/last-request");
  8848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8849. EXPECT_EQ(StatusCode::OK_200, res->status);
  8850. EXPECT_EQ("close", res->get_header_value("Connection"));
  8851. }
  8852. TEST_F(ServerTest, TooManyRedirect) {
  8853. cli_.set_follow_location(true);
  8854. auto res = cli_.Get("/redirect/0");
  8855. ASSERT_TRUE(!res);
  8856. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8857. }
  8858. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8859. Request req;
  8860. req.method = "FOOBAR";
  8861. req.path = "/hi";
  8862. cli_.set_keep_alive(true);
  8863. auto res = cli_.send(req);
  8864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8865. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8866. EXPECT_EQ("close", res->get_header_value("Connection"));
  8867. EXPECT_FALSE(cli_.is_socket_open());
  8868. }
  8869. TEST_F(ServerTest, CustomRouteReadsBody) {
  8870. const std::string xml =
  8871. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8872. Request req;
  8873. req.method = "PROPFIND";
  8874. req.path = "/dav/dir";
  8875. req.set_header("Depth", "1");
  8876. req.body = xml;
  8877. auto res = cli_.send(req);
  8878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8879. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8880. EXPECT_EQ(xml, res->body);
  8881. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8882. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8883. }
  8884. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8885. Request req;
  8886. req.method = "PROPFIND";
  8887. req.path = "/dav/42";
  8888. auto res = cli_.send(req);
  8889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8890. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8891. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8892. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8893. }
  8894. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8895. Request req;
  8896. req.method = "PROPFIND";
  8897. req.path = "/dav-re/123";
  8898. auto res = cli_.send(req);
  8899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8900. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8901. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8902. }
  8903. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8904. Request req;
  8905. req.method = "MKCOL";
  8906. req.path = "/dav-mkcol";
  8907. auto res = cli_.send(req);
  8908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8909. EXPECT_EQ(StatusCode::Created_201, res->status);
  8910. }
  8911. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8912. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8913. Request req;
  8914. req.method = "REPORT";
  8915. req.path = "/dav-report";
  8916. req.body = xml;
  8917. auto res = cli_.send(req);
  8918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8919. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8920. EXPECT_EQ(xml, res->body);
  8921. }
  8922. // A content reader route must fire even when the request carries no body,
  8923. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8924. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8925. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8926. Request req;
  8927. req.method = "REPORT";
  8928. req.path = "/dav-report";
  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("0", res->get_header_value("x-body-size"));
  8933. }
  8934. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8935. Request req;
  8936. req.method = "PROPFIND";
  8937. req.path = "/not-dav";
  8938. auto res = cli_.send(req);
  8939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8940. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8941. }
  8942. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8943. Request req;
  8944. req.method = "UNLOCK";
  8945. req.path = "/dav/dir";
  8946. cli_.set_keep_alive(true);
  8947. auto res = cli_.send(req);
  8948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8949. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8950. EXPECT_EQ("close", res->get_header_value("Connection"));
  8951. EXPECT_FALSE(cli_.is_socket_open());
  8952. }
  8953. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8954. // The mount point serves this path, but only for GET and HEAD.
  8955. auto get_res = cli_.Get("/dir/index.html");
  8956. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8957. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8958. Request req;
  8959. req.method = "PROPFIND";
  8960. req.path = "/dir/index.html";
  8961. auto res = cli_.send(req);
  8962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8963. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8964. }
  8965. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8966. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8967. cli_.set_keep_alive(true);
  8968. for (auto i = 0; i < 2; i++) {
  8969. Request req;
  8970. req.method = "PROPFIND";
  8971. req.path = "/dav/dir";
  8972. req.body = xml;
  8973. auto res = cli_.send(req);
  8974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8975. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8976. EXPECT_EQ(xml, res->body);
  8977. EXPECT_TRUE(cli_.is_socket_open());
  8978. }
  8979. // A built-in method must still be served on the same connection.
  8980. cli_.set_keep_alive(false);
  8981. auto res = cli_.Get("/hi");
  8982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8983. EXPECT_EQ(StatusCode::OK_200, res->status);
  8984. EXPECT_EQ("close", res->get_header_value("Connection"));
  8985. }
  8986. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8987. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8988. Request req;
  8989. req.method = "PROPFIND";
  8990. req.path = "/dav/dir";
  8991. req.set_header("Expect", "100-continue");
  8992. req.body = xml;
  8993. auto res = cli_.send(req);
  8994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8995. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8996. EXPECT_EQ(xml, res->body);
  8997. }
  8998. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8999. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9000. TEST_F(ServerTest, Gzip) {
  9001. Headers headers;
  9002. headers.emplace("Accept-Encoding", "gzip, deflate");
  9003. auto res = cli_.Get("/compress", headers);
  9004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9005. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9006. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9007. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9008. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9009. "7890123456789012345678901234567890",
  9010. res->body);
  9011. EXPECT_EQ(StatusCode::OK_200, res->status);
  9012. }
  9013. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9014. Headers headers;
  9015. headers.emplace("Accept-Encoding", "gzip, deflate");
  9016. auto res = cli_.Get("/compress-with-charset", headers);
  9017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9018. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9019. EXPECT_EQ("application/json; charset=utf-8",
  9020. res->get_header_value("Content-Type"));
  9021. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9022. "7890123456789012345678901234567890",
  9023. res->body);
  9024. EXPECT_EQ(StatusCode::OK_200, res->status);
  9025. }
  9026. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9027. Headers headers;
  9028. headers.emplace("Accept-Encoding", "");
  9029. auto res = cli_.Get("/compress", headers);
  9030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9031. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9032. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9033. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9034. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9035. "7890123456789012345678901234567890",
  9036. res->body);
  9037. EXPECT_EQ(StatusCode::OK_200, res->status);
  9038. }
  9039. TEST_F(ServerTest, GzipWithContentReceiver) {
  9040. Headers headers;
  9041. headers.emplace("Accept-Encoding", "gzip, deflate");
  9042. std::string body;
  9043. auto res =
  9044. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9045. EXPECT_EQ(100U, data_length);
  9046. body.append(data, data_length);
  9047. return true;
  9048. });
  9049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9050. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9051. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9052. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9053. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9054. "7890123456789012345678901234567890",
  9055. body);
  9056. EXPECT_EQ(StatusCode::OK_200, res->status);
  9057. }
  9058. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9059. Headers headers;
  9060. headers.emplace("Accept-Encoding", "gzip, deflate");
  9061. cli_.set_decompress(false);
  9062. auto res = cli_.Get("/compress", headers);
  9063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9064. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9065. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9066. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9067. EXPECT_EQ(33U, res->body.size());
  9068. EXPECT_EQ(StatusCode::OK_200, res->status);
  9069. }
  9070. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9071. Headers headers;
  9072. headers.emplace("Accept-Encoding", "");
  9073. std::string body;
  9074. auto res =
  9075. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9076. EXPECT_EQ(100U, data_length);
  9077. body.append(data, data_length);
  9078. return true;
  9079. });
  9080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9081. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9082. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9083. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9084. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9085. "7890123456789012345678901234567890",
  9086. body);
  9087. EXPECT_EQ(StatusCode::OK_200, res->status);
  9088. }
  9089. TEST_F(ServerTest, NoGzip) {
  9090. Headers headers;
  9091. headers.emplace("Accept-Encoding", "gzip, deflate");
  9092. auto res = cli_.Get("/nocompress", headers);
  9093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9094. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9095. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9096. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9097. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9098. "7890123456789012345678901234567890",
  9099. res->body);
  9100. EXPECT_EQ(StatusCode::OK_200, res->status);
  9101. }
  9102. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9103. Headers headers;
  9104. headers.emplace("Accept-Encoding", "gzip, deflate");
  9105. std::string body;
  9106. auto res = cli_.Get("/nocompress", headers,
  9107. [&](const char *data, size_t data_length) {
  9108. EXPECT_EQ(100U, data_length);
  9109. body.append(data, data_length);
  9110. return true;
  9111. });
  9112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9113. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9114. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9115. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9116. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9117. "7890123456789012345678901234567890",
  9118. body);
  9119. EXPECT_EQ(StatusCode::OK_200, res->status);
  9120. }
  9121. TEST_F(ServerTest, MultipartFormDataGzip) {
  9122. UploadFormDataItems items = {
  9123. {"key1", "test", "", ""},
  9124. {"key2", "--abcdefg123", "", ""},
  9125. };
  9126. cli_.set_compress(true);
  9127. auto res = cli_.Post("/compress-multipart", items);
  9128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9129. EXPECT_EQ(StatusCode::OK_200, res->status);
  9130. }
  9131. #endif
  9132. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9133. // Static file compression is opt-in, so these run their own server rather than
  9134. // flipping it on for the shared ServerTest fixture, which would silently
  9135. // rewrite what every other static file test is asserting.
  9136. class StaticFileCompressionTest : public ::testing::Test {
  9137. protected:
  9138. void TearDown() override {
  9139. if (t_.joinable()) {
  9140. svr_.stop();
  9141. t_.join();
  9142. }
  9143. }
  9144. int start(const std::function<void(Server &)> &configure = nullptr) {
  9145. // Serves the same tree as a directory of build-time compressed assets
  9146. // would be served: the mount point names the coding the files are already
  9147. // stored in. Registered before "/" so it is the one that matches.
  9148. svr_.set_mount_point("/pre-encoded", "./www",
  9149. {{"Content-Encoding", "gzip"}});
  9150. svr_.set_mount_point("/", "./www");
  9151. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9152. res.set_file_content("./www/dir/index.html", "text/html");
  9153. });
  9154. svr_.Get("/pre-encoded-file-content",
  9155. [](const Request & /*req*/, Response &res) {
  9156. res.set_header("Content-Encoding", "gzip");
  9157. res.set_file_content("./www/dir/index.html", "text/html");
  9158. });
  9159. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9160. res.set_content_provider(
  9161. 6, "text/plain",
  9162. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9163. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9164. return true;
  9165. });
  9166. });
  9167. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9168. res.set_content_provider(
  9169. 1000, "text/plain",
  9170. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9171. if (offset < 100) {
  9172. std::string data(100, 'A');
  9173. sink.write(data.data(), data.size());
  9174. return true;
  9175. }
  9176. std::this_thread::sleep_for(std::chrono::seconds(2));
  9177. std::string data(900, 'B');
  9178. sink.write(data.data(), data.size());
  9179. return true;
  9180. });
  9181. });
  9182. if (configure) { configure(svr_); }
  9183. auto port = svr_.bind_to_any_port(HOST);
  9184. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9185. svr_.wait_until_ready();
  9186. return port;
  9187. }
  9188. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9189. // Every file under ./www except 1MB.txt is smaller than the default
  9190. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9191. // it out of the way.
  9192. static void enable_without_floor(Server &svr) {
  9193. svr.set_static_file_compression(true);
  9194. svr.set_static_file_compression_min_length(0);
  9195. }
  9196. Server svr_;
  9197. std::thread t_;
  9198. };
  9199. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9200. auto port = start();
  9201. Client cli(HOST, port);
  9202. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9204. EXPECT_EQ(StatusCode::OK_200, res->status);
  9205. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9206. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9207. EXPECT_EQ(1048576U, res->body.size());
  9208. }
  9209. TEST_F(StaticFileCompressionTest, MountPoint) {
  9210. auto port = start(enable);
  9211. Client cli(HOST, port);
  9212. cli.set_decompress(false);
  9213. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9215. EXPECT_EQ(StatusCode::OK_200, res->status);
  9216. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9217. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9218. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9219. // The response stays self-delimiting: a length, not a chunked body.
  9220. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9221. EXPECT_EQ(std::to_string(res->body.size()),
  9222. res->get_header_value("Content-Length"));
  9223. EXPECT_LT(res->body.size(), 1048576U);
  9224. EXPECT_FALSE(res->body.empty());
  9225. }
  9226. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9227. auto port = start(enable);
  9228. Client cli(HOST, port);
  9229. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9231. EXPECT_EQ(StatusCode::OK_200, res->status);
  9232. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9233. EXPECT_EQ(1048576U, res->body.size());
  9234. }
  9235. TEST_F(StaticFileCompressionTest, FileContent) {
  9236. auto port = start(enable_without_floor);
  9237. Client cli(HOST, port);
  9238. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9240. EXPECT_EQ(StatusCode::OK_200, res->status);
  9241. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9242. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9243. EXPECT_EQ(104U, res->body.size());
  9244. }
  9245. // A handler that serves an already-encoded file names the coding itself. The
  9246. // file-backed path decided its coding from Accept-Encoding and the content
  9247. // type alone, so it compressed the stored bytes a second time and appended a
  9248. // second Content-Encoding field line.
  9249. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9250. auto port = start(enable_without_floor);
  9251. Client cli(HOST, port);
  9252. cli.set_decompress(false);
  9253. auto res = cli.Get("/pre-encoded-file-content",
  9254. Headers{{"Accept-Encoding", "gzip"}});
  9255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9256. EXPECT_EQ(StatusCode::OK_200, res->status);
  9257. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9258. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9259. // Vary belongs to a coding the server chose, and it chose none here.
  9260. EXPECT_FALSE(res->has_header("Vary"));
  9261. // The file travels exactly as it is stored on disk.
  9262. EXPECT_EQ(104U, res->body.size());
  9263. }
  9264. // The 1MB file clears the default floor, so this one runs the configuration a
  9265. // deployment would actually have.
  9266. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9267. auto port = start(enable);
  9268. Client cli(HOST, port);
  9269. cli.set_decompress(false);
  9270. auto res =
  9271. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9273. EXPECT_EQ(StatusCode::OK_200, res->status);
  9274. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9275. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9276. EXPECT_FALSE(res->has_header("Vary"));
  9277. EXPECT_EQ(1048576U, res->body.size());
  9278. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9279. }
  9280. TEST_F(StaticFileCompressionTest, Head) {
  9281. auto port = start(enable);
  9282. Client cli(HOST, port);
  9283. cli.set_decompress(false);
  9284. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9285. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9286. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9288. EXPECT_EQ(StatusCode::OK_200, res->status);
  9289. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9290. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9291. // HEAD still reports the size a GET would return.
  9292. EXPECT_EQ(get->get_header_value("Content-Length"),
  9293. res->get_header_value("Content-Length"));
  9294. EXPECT_TRUE(res->body.empty());
  9295. }
  9296. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9297. auto port = start(enable);
  9298. Client cli(HOST, port);
  9299. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9300. {"Accept-Encoding", "gzip"}});
  9301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9302. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9303. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9304. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9305. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9306. EXPECT_EQ("cd", res->body);
  9307. }
  9308. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9309. auto port = start(enable);
  9310. Client cli(HOST, port);
  9311. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9313. EXPECT_EQ(StatusCode::OK_200, res->status);
  9314. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9315. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9316. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9317. }
  9318. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9319. auto port = start(enable);
  9320. Client cli(HOST, port);
  9321. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9323. EXPECT_EQ(StatusCode::OK_200, res->status);
  9324. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9325. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9326. EXPECT_TRUE(res->body.empty());
  9327. }
  9328. TEST_F(StaticFileCompressionTest, MinLength) {
  9329. auto port = start(enable);
  9330. Client cli(HOST, port);
  9331. // 104 bytes, well under the default floor. Compressing it would add the
  9332. // gzip header and trailer to a body that already fits in one packet.
  9333. auto res = cli.Get("/dir/index.html", 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("104", res->get_header_value("Content-Length"));
  9338. }
  9339. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9340. auto port = start([](Server &svr) {
  9341. svr.set_static_file_compression(true);
  9342. svr.set_static_file_compression_min_length(1);
  9343. });
  9344. Client cli(HOST, port);
  9345. cli.set_decompress(false);
  9346. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9348. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9349. // A 9-byte file comes back larger than it went in, because gzip's header and
  9350. // trailer outweigh anything deflate can save. That is the end of the range
  9351. // the floor exists to keep out.
  9352. EXPECT_GT(res->body.size(), 9U);
  9353. }
  9354. TEST_F(StaticFileCompressionTest, MaxLength) {
  9355. auto port = start([](Server &svr) {
  9356. svr.set_static_file_compression(true);
  9357. svr.set_static_file_compression_min_length(0);
  9358. svr.set_static_file_compression_max_length(1024);
  9359. });
  9360. Client cli(HOST, port);
  9361. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9362. // defines `small` as a macro on Windows.
  9363. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9364. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9365. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9366. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9367. // Under it: compressed.
  9368. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9369. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9370. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9371. }
  9372. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9373. auto port = start(enable_without_floor);
  9374. Client cli(HOST, port);
  9375. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9376. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9377. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9378. auto identity_etag = identity->get_header_value("ETag");
  9379. ASSERT_FALSE(identity_etag.empty());
  9380. auto gzipped =
  9381. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9382. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9383. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9384. auto gzip_etag = gzipped->get_header_value("ETag");
  9385. ASSERT_FALSE(gzip_etag.empty());
  9386. // Two representations, two validators.
  9387. EXPECT_NE(identity_etag, gzip_etag);
  9388. // Each one revalidates against the request that would produce it...
  9389. auto fresh =
  9390. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9391. {"If-None-Match", gzip_etag}});
  9392. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9393. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9394. auto fresh_identity =
  9395. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9396. {"If-None-Match", identity_etag}});
  9397. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9398. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9399. // ...and not against the other representation.
  9400. auto crossed =
  9401. cli.Get("/dir/index.html",
  9402. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9403. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9404. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9405. }
  9406. // The opt-in covers responses the server reads off disk itself. A caller's own
  9407. // known-length provider keeps its Content-Length and, more importantly, keeps
  9408. // delivering incrementally: routing it through a compressor would hold every
  9409. // write back until zlib's window filled.
  9410. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9411. auto port = start(enable);
  9412. Client cli(HOST, port);
  9413. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9415. EXPECT_EQ(StatusCode::OK_200, res->status);
  9416. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9417. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9418. EXPECT_EQ("aaabbb", res->body);
  9419. }
  9420. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9421. auto port = start(enable);
  9422. Client cli(HOST, port);
  9423. cli.set_read_timeout(1, 0);
  9424. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9425. Headers{{"Accept-Encoding", "gzip"}});
  9426. ASSERT_TRUE(handle.is_valid());
  9427. // The provider writes 100 bytes and then stalls for longer than the read
  9428. // timeout. Those first bytes have to arrive anyway: run the response through
  9429. // a compressor and zlib holds them until its window fills, so the read would
  9430. // come back empty instead.
  9431. char buf[256];
  9432. auto n = handle.read(buf, sizeof(buf));
  9433. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9434. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9435. }
  9436. #endif
  9437. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9438. TEST_F(ServerTest, Brotli) {
  9439. Headers headers;
  9440. headers.emplace("Accept-Encoding", "br");
  9441. auto res = cli_.Get("/compress", headers);
  9442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9443. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9444. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9445. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9446. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9447. "7890123456789012345678901234567890",
  9448. res->body);
  9449. EXPECT_EQ(StatusCode::OK_200, res->status);
  9450. }
  9451. #endif
  9452. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9453. TEST_F(ServerTest, Zstd) {
  9454. Headers headers;
  9455. headers.emplace("Accept-Encoding", "zstd");
  9456. auto res = cli_.Get("/compress", headers);
  9457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9458. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9459. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9460. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9461. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9462. "7890123456789012345678901234567890",
  9463. res->body);
  9464. EXPECT_EQ(StatusCode::OK_200, res->status);
  9465. }
  9466. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9467. Headers headers;
  9468. headers.emplace("Accept-Encoding", "");
  9469. auto res = cli_.Get("/compress", headers);
  9470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9471. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9472. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9473. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9474. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9475. "7890123456789012345678901234567890",
  9476. res->body);
  9477. EXPECT_EQ(StatusCode::OK_200, res->status);
  9478. }
  9479. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9480. Headers headers;
  9481. headers.emplace("Accept-Encoding", "zstd");
  9482. std::string body;
  9483. auto res =
  9484. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9485. EXPECT_EQ(100U, data_length);
  9486. body.append(data, data_length);
  9487. return true;
  9488. });
  9489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9490. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9492. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9493. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9494. "7890123456789012345678901234567890",
  9495. body);
  9496. EXPECT_EQ(StatusCode::OK_200, res->status);
  9497. }
  9498. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9499. Headers headers;
  9500. headers.emplace("Accept-Encoding", "zstd");
  9501. cli_.set_decompress(false);
  9502. auto res = cli_.Get("/compress", headers);
  9503. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9504. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9505. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9506. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9508. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9509. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9510. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9511. EXPECT_EQ(StatusCode::OK_200, res->status);
  9512. ASSERT_EQ(26U, res->body.size());
  9513. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9514. 0);
  9515. }
  9516. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9517. Headers headers;
  9518. headers.emplace("Accept-Encoding", "");
  9519. std::string body;
  9520. auto res =
  9521. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9522. EXPECT_EQ(100U, data_length);
  9523. body.append(data, data_length);
  9524. return true;
  9525. });
  9526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9527. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9528. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9529. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9530. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9531. "7890123456789012345678901234567890",
  9532. body);
  9533. EXPECT_EQ(StatusCode::OK_200, res->status);
  9534. }
  9535. TEST_F(ServerTest, NoZstd) {
  9536. Headers headers;
  9537. headers.emplace("Accept-Encoding", "zstd");
  9538. auto res = cli_.Get("/nocompress", headers);
  9539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9540. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9541. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9542. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9543. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9544. "7890123456789012345678901234567890",
  9545. res->body);
  9546. EXPECT_EQ(StatusCode::OK_200, res->status);
  9547. }
  9548. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9549. Headers headers;
  9550. headers.emplace("Accept-Encoding", "zstd");
  9551. std::string body;
  9552. auto res = cli_.Get("/nocompress", headers,
  9553. [&](const char *data, size_t data_length) {
  9554. EXPECT_EQ(100U, data_length);
  9555. body.append(data, data_length);
  9556. return true;
  9557. });
  9558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9559. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9560. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9561. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9562. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9563. "7890123456789012345678901234567890",
  9564. body);
  9565. EXPECT_EQ(StatusCode::OK_200, res->status);
  9566. }
  9567. // TODO: How to enable zstd ??
  9568. TEST_F(ServerTest, MultipartFormDataZstd) {
  9569. UploadFormDataItems items = {
  9570. {"key1", "test", "", ""},
  9571. {"key2", "--abcdefg123", "", ""},
  9572. };
  9573. Headers headers;
  9574. headers.emplace("Accept-Encoding", "zstd");
  9575. cli_.set_compress(true);
  9576. auto res = cli_.Post("/compress-multipart", headers, items);
  9577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9578. EXPECT_EQ(StatusCode::OK_200, res->status);
  9579. }
  9580. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9581. Headers headers;
  9582. headers.emplace("Accept-Encoding", "zstd");
  9583. cli_.set_compress(true);
  9584. auto res = cli_.Put(
  9585. "/put", headers, 3,
  9586. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9587. sink.os << "PUT";
  9588. return true;
  9589. },
  9590. "text/plain");
  9591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9592. EXPECT_EQ(StatusCode::OK_200, res->status);
  9593. EXPECT_EQ("PUT", res->body);
  9594. }
  9595. // Pre-compression logging tests
  9596. TEST_F(ServerTest, PreCompressionLogging) {
  9597. // Test data for compression (matches the actual /compress endpoint content)
  9598. const std::string test_content =
  9599. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9600. "3456789012345678901234567890";
  9601. // Variables to capture logging data
  9602. std::string pre_compression_body;
  9603. std::string pre_compression_content_type;
  9604. std::string pre_compression_content_encoding;
  9605. std::string post_compression_body;
  9606. std::string post_compression_content_type;
  9607. std::string post_compression_content_encoding;
  9608. // Set up pre-compression logger
  9609. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9610. const Response &res) {
  9611. pre_compression_body = res.body;
  9612. pre_compression_content_type = res.get_header_value("Content-Type");
  9613. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9614. });
  9615. // Set up post-compression logger
  9616. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9617. post_compression_body = res.body;
  9618. post_compression_content_type = res.get_header_value("Content-Type");
  9619. post_compression_content_encoding =
  9620. res.get_header_value("Content-Encoding");
  9621. });
  9622. // Test with gzip compression
  9623. Headers headers;
  9624. headers.emplace("Accept-Encoding", "gzip");
  9625. auto res = cli_.Get("/compress", headers);
  9626. // Verify response was compressed
  9627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9628. EXPECT_EQ(StatusCode::OK_200, res->status);
  9629. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9630. // Verify pre-compression logger captured uncompressed content
  9631. EXPECT_EQ(test_content, pre_compression_body);
  9632. EXPECT_EQ("text/plain", pre_compression_content_type);
  9633. EXPECT_TRUE(pre_compression_content_encoding
  9634. .empty()); // No encoding header before compression
  9635. // Verify post-compression logger captured compressed content
  9636. EXPECT_NE(test_content,
  9637. post_compression_body); // Should be different after compression
  9638. EXPECT_EQ("text/plain", post_compression_content_type);
  9639. EXPECT_EQ("gzip", post_compression_content_encoding);
  9640. // Verify compressed content is smaller
  9641. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9642. }
  9643. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9644. const std::string test_content =
  9645. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9646. "3456789012345678901234567890";
  9647. std::string pre_compression_body;
  9648. std::string post_compression_body;
  9649. svr_.set_pre_compression_logger(
  9650. [&](const Request & /*req*/, const Response &res) {
  9651. pre_compression_body = res.body;
  9652. });
  9653. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9654. post_compression_body = res.body;
  9655. });
  9656. Headers headers;
  9657. headers.emplace("Accept-Encoding", "br");
  9658. auto res = cli_.Get("/compress", headers);
  9659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9660. EXPECT_EQ(StatusCode::OK_200, res->status);
  9661. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9662. // Verify pre-compression content is uncompressed
  9663. EXPECT_EQ(test_content, pre_compression_body);
  9664. // Verify post-compression content is compressed
  9665. EXPECT_NE(test_content, post_compression_body);
  9666. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9667. }
  9668. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9669. const std::string test_content =
  9670. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9671. "3456789012345678901234567890";
  9672. std::string pre_compression_body;
  9673. std::string post_compression_body;
  9674. svr_.set_pre_compression_logger(
  9675. [&](const Request & /*req*/, const Response &res) {
  9676. pre_compression_body = res.body;
  9677. });
  9678. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9679. post_compression_body = res.body;
  9680. });
  9681. // Request without compression (use /nocompress endpoint)
  9682. Headers headers;
  9683. auto res = cli_.Get("/nocompress", headers);
  9684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9685. EXPECT_EQ(StatusCode::OK_200, res->status);
  9686. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9687. // Pre-compression logger should not be called when no compression is applied
  9688. EXPECT_TRUE(
  9689. pre_compression_body.empty()); // Pre-compression logger not called
  9690. EXPECT_EQ(
  9691. test_content,
  9692. post_compression_body); // Post-compression logger captures final content
  9693. }
  9694. TEST_F(ServerTest, LoggerSeesContentLength) {
  9695. size_t logged_content_length = 0;
  9696. std::string logged_content_length_header;
  9697. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9698. logged_content_length = res.content_length_;
  9699. logged_content_length_header = res.get_header_value("Content-Length");
  9700. });
  9701. auto res = cli_.Get("/nocompress");
  9702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9703. EXPECT_EQ(StatusCode::OK_200, res->status);
  9704. EXPECT_EQ(res->body.size(), logged_content_length);
  9705. EXPECT_EQ(std::to_string(logged_content_length),
  9706. logged_content_length_header);
  9707. }
  9708. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9709. const std::string test_content =
  9710. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9711. "3456789012345678901234567890";
  9712. std::string pre_compression_body;
  9713. bool pre_logger_called = false;
  9714. // Set only pre-compression logger
  9715. svr_.set_pre_compression_logger(
  9716. [&](const Request & /*req*/, const Response &res) {
  9717. pre_compression_body = res.body;
  9718. pre_logger_called = true;
  9719. });
  9720. Headers headers;
  9721. headers.emplace("Accept-Encoding", "gzip");
  9722. auto res = cli_.Get("/compress", headers);
  9723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9724. EXPECT_EQ(StatusCode::OK_200, res->status);
  9725. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9726. // Verify pre-compression logger was called
  9727. EXPECT_TRUE(pre_logger_called);
  9728. EXPECT_EQ(test_content, pre_compression_body);
  9729. }
  9730. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9731. {
  9732. // Test with Expect: 100-continue header - success case
  9733. // Server returns 100 Continue, client sends body, server returns 200 OK
  9734. Request req;
  9735. req.method = "POST";
  9736. req.path = "/post-large";
  9737. req.set_header("Expect", "100-continue");
  9738. req.body = LARGE_DATA;
  9739. Response res;
  9740. auto error = Error::Success;
  9741. cli_.set_keep_alive(true);
  9742. auto ret = cli_.send(req, res, error);
  9743. EXPECT_TRUE(ret);
  9744. EXPECT_EQ(StatusCode::OK_200, res.status);
  9745. EXPECT_EQ(LARGE_DATA, res.body);
  9746. }
  9747. {
  9748. // Test with Expect: 100-continue header - error case
  9749. // Client should not send the body when server returns an error
  9750. Request req;
  9751. req.method = "POST";
  9752. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9753. req.set_header("Expect", "100-continue");
  9754. req.body = LARGE_DATA;
  9755. Response res;
  9756. auto error = Error::Success;
  9757. auto start = std::chrono::high_resolution_clock::now();
  9758. cli_.set_keep_alive(true);
  9759. auto ret = cli_.send(req, res, error);
  9760. auto end = std::chrono::high_resolution_clock::now();
  9761. auto elapsed =
  9762. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9763. .count();
  9764. // With Expect: 100-continue, request completes successfully but with error
  9765. EXPECT_TRUE(ret);
  9766. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9767. EXPECT_EQ("close", res.get_header_value("Connection"));
  9768. EXPECT_FALSE(cli_.is_socket_open());
  9769. EXPECT_LE(elapsed, 2000);
  9770. }
  9771. {
  9772. // Send an extra GET request to ensure error recovery without hanging
  9773. Request req;
  9774. req.method = "GET";
  9775. req.path = "/hi";
  9776. auto start = std::chrono::high_resolution_clock::now();
  9777. auto res = cli_.send(req);
  9778. auto end = std::chrono::high_resolution_clock::now();
  9779. auto elapsed =
  9780. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9781. .count();
  9782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9783. EXPECT_EQ(StatusCode::OK_200, res->status);
  9784. EXPECT_EQ("Hello World!", res->body);
  9785. EXPECT_LE(elapsed, 500);
  9786. }
  9787. }
  9788. TEST(ZstdDecompressor, ChunkedDecompression) {
  9789. std::string data;
  9790. for (size_t i = 0; i < 32 * 1024; ++i) {
  9791. data.push_back(static_cast<char>('a' + i % 26));
  9792. }
  9793. std::string compressed_data;
  9794. {
  9795. httplib::detail::zstd_compressor compressor;
  9796. bool result = compressor.compress(
  9797. data.data(), data.size(),
  9798. /*last=*/true,
  9799. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9800. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9801. compressed_data_size);
  9802. return true;
  9803. });
  9804. ASSERT_TRUE(result);
  9805. }
  9806. std::string decompressed_data;
  9807. {
  9808. httplib::detail::zstd_decompressor decompressor;
  9809. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9810. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9811. size_t chunk_size = 130;
  9812. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9813. chunk_begin += chunk_size) {
  9814. size_t current_chunk_size =
  9815. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9816. bool result = decompressor.decompress(
  9817. compressed_data.data() + chunk_begin, current_chunk_size,
  9818. [&](const char *decompressed_data_chunk,
  9819. size_t decompressed_data_chunk_size) {
  9820. decompressed_data.insert(decompressed_data.size(),
  9821. decompressed_data_chunk,
  9822. decompressed_data_chunk_size);
  9823. return true;
  9824. });
  9825. ASSERT_TRUE(result);
  9826. }
  9827. }
  9828. ASSERT_EQ(data, decompressed_data);
  9829. }
  9830. TEST(ZstdDecompressor, Decompress) {
  9831. std::string original_text = "Compressed with ZSTD";
  9832. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9833. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9834. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9835. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9836. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9837. std::string decompressed_data;
  9838. {
  9839. httplib::detail::zstd_decompressor decompressor;
  9840. bool result = decompressor.decompress(
  9841. compressed_data.data(), compressed_data.size(),
  9842. [&](const char *decompressed_data_chunk,
  9843. size_t decompressed_data_chunk_size) {
  9844. decompressed_data.insert(decompressed_data.size(),
  9845. decompressed_data_chunk,
  9846. decompressed_data_chunk_size);
  9847. return true;
  9848. });
  9849. ASSERT_TRUE(result);
  9850. }
  9851. ASSERT_EQ(original_text, decompressed_data);
  9852. }
  9853. #endif
  9854. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9855. // separate chunks so that the server sees each part in its own read(). Used to
  9856. // place a read boundary at a specific offset of a request body.
  9857. static bool send_request_in_parts(time_t read_timeout_sec,
  9858. const std::vector<std::string> &parts,
  9859. std::string *resp = nullptr,
  9860. int port = PORT) {
  9861. auto error = Error::Success;
  9862. auto client_sock = detail::create_client_socket(
  9863. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9864. /*connection_timeout_sec=*/5, 0,
  9865. /*read_timeout_sec=*/5, 0,
  9866. /*write_timeout_sec=*/5, 0, std::string(), error);
  9867. if (client_sock == INVALID_SOCKET) { return false; }
  9868. auto ret = detail::process_client_socket(
  9869. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9870. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9871. for (size_t i = 0; i < parts.size(); i++) {
  9872. const auto &part = parts[i];
  9873. if (part.size() !=
  9874. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9875. return false;
  9876. }
  9877. if (i + 1 < parts.size()) {
  9878. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9879. }
  9880. }
  9881. char buf[512];
  9882. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9883. while (line_reader.getline()) {
  9884. if (resp) { *resp += line_reader.ptr(); }
  9885. }
  9886. return true;
  9887. });
  9888. detail::close_socket(client_sock);
  9889. return ret;
  9890. }
  9891. // Sends a raw request to a server listening at HOST:PORT.
  9892. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9893. std::string *resp = nullptr, int port = PORT) {
  9894. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9895. }
  9896. #ifdef CPPHTTPLIB_SSL_ENABLED
  9897. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9898. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9899. ASSERT_TRUE(svr.is_valid());
  9900. svr.set_read_timeout(1, 0);
  9901. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9902. auto se = detail::scope_exit([&] {
  9903. svr.stop();
  9904. t.join();
  9905. ASSERT_FALSE(svr.is_running());
  9906. });
  9907. svr.wait_until_ready();
  9908. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9909. // keeps each wait well within the read timeout. The server gives up a
  9910. // second in, so the bytes sent after that fail.
  9911. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9912. parts.resize(26, std::string(1, '\0'));
  9913. EXPECT_FALSE(send_request_in_parts(5, parts));
  9914. }
  9915. #endif
  9916. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9917. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9918. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9919. const std::vector<std::string> &parts,
  9920. std::string *resp = nullptr,
  9921. int port = PORT) {
  9922. auto error = Error::Success;
  9923. auto sock = detail::create_client_socket(
  9924. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9925. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9926. /*write_timeout_sec=*/5, 0, std::string(), error);
  9927. if (sock == INVALID_SOCKET) { return false; }
  9928. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9929. auto ctx = SSL_CTX_new(TLS_client_method());
  9930. auto ssl = SSL_new(ctx);
  9931. auto ssl_se = detail::scope_exit([&] {
  9932. SSL_free(ssl);
  9933. SSL_CTX_free(ctx);
  9934. });
  9935. SSL_set_fd(ssl, static_cast<int>(sock));
  9936. if (SSL_connect(ssl) != 1) { return false; }
  9937. for (size_t i = 0; i < parts.size(); i++) {
  9938. const auto &part = parts[i];
  9939. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9940. static_cast<int>(part.size())) {
  9941. return false;
  9942. }
  9943. if (i + 1 < parts.size()) {
  9944. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9945. }
  9946. }
  9947. char buf[512];
  9948. int n;
  9949. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9950. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9951. }
  9952. return true;
  9953. }
  9954. #endif
  9955. // The request line, then a header value a byte at a time.
  9956. static std::vector<std::string> slow_request_head_parts() {
  9957. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9958. parts.resize(26, "a");
  9959. parts.emplace_back("\r\n\r\n");
  9960. return parts;
  9961. }
  9962. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9963. // within the one-second read timeout. The server gives up a second in, before
  9964. // the head is complete.
  9965. static void
  9966. expect_slow_request_head_dropped(Server &svr,
  9967. const std::function<std::string()> &send) {
  9968. std::atomic<bool> handled(false);
  9969. svr.Get("/", [&](const Request &, Response &res) {
  9970. handled = true;
  9971. res.set_content("ok", "text/plain");
  9972. });
  9973. svr.set_read_timeout(1, 0);
  9974. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9975. auto se = detail::scope_exit([&] {
  9976. svr.stop();
  9977. t.join();
  9978. ASSERT_FALSE(svr.is_running());
  9979. });
  9980. svr.wait_until_ready();
  9981. auto resp = send();
  9982. EXPECT_FALSE(handled);
  9983. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9984. }
  9985. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9986. Server svr;
  9987. expect_slow_request_head_dropped(svr, [] {
  9988. std::string resp;
  9989. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9990. return resp;
  9991. });
  9992. }
  9993. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9994. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9996. ASSERT_TRUE(svr.is_valid());
  9997. expect_slow_request_head_dropped(svr, [] {
  9998. std::string resp;
  9999. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10000. return resp;
  10001. });
  10002. }
  10003. #endif
  10004. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10005. Server svr;
  10006. std::string header_value;
  10007. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10008. header_value = req.get_header_value("foo");
  10009. res.set_content("ok", "text/plain");
  10010. });
  10011. thread t = thread([&] { svr.listen(HOST, PORT); });
  10012. auto se = detail::scope_exit([&] {
  10013. svr.stop();
  10014. t.join();
  10015. ASSERT_FALSE(svr.is_running());
  10016. });
  10017. svr.wait_until_ready();
  10018. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10019. // like characters are not treated the same - use vertical tab and escape.
  10020. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10021. "foo: \t \v bar \x1B\t \r\n"
  10022. "Connection: close\r\n"
  10023. "\r\n";
  10024. std::string res;
  10025. ASSERT_TRUE(send_request(5, req, &res));
  10026. EXPECT_EQ(header_value, "");
  10027. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10028. }
  10029. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10030. Server svr;
  10031. std::string received;
  10032. svr.Get("/order", [&](const Request &req, Response &res) {
  10033. received = entries_to_string(req.headers);
  10034. res.set_content("ok", "text/plain");
  10035. });
  10036. auto port = svr.bind_to_any_port(HOST);
  10037. thread t = thread([&] { svr.listen_after_bind(); });
  10038. auto se = detail::scope_exit([&] {
  10039. svr.stop();
  10040. t.join();
  10041. ASSERT_FALSE(svr.is_running());
  10042. });
  10043. svr.wait_until_ready();
  10044. const std::string req = "GET /order HTTP/1.1\r\n"
  10045. "Host: localhost\r\n"
  10046. "X-First: 1\r\n"
  10047. "X-Dup: a\r\n"
  10048. "X-Second: 2\r\n"
  10049. "X-Dup: b\r\n"
  10050. "Connection: close\r\n"
  10051. "\r\n";
  10052. std::string res;
  10053. ASSERT_TRUE(send_request(5, req, &res, port));
  10054. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10055. EXPECT_EQ(
  10056. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10057. received);
  10058. }
  10059. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10060. Server svr;
  10061. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10062. res.set_header("Set-Cookie", "first=1");
  10063. res.set_header("X-Between", "y");
  10064. res.set_header("Set-Cookie", "second=2");
  10065. res.set_content("ok", "text/plain");
  10066. });
  10067. auto port = svr.bind_to_any_port(HOST);
  10068. thread t = thread([&] { svr.listen_after_bind(); });
  10069. auto se = detail::scope_exit([&] {
  10070. svr.stop();
  10071. t.join();
  10072. ASSERT_FALSE(svr.is_running());
  10073. });
  10074. svr.wait_until_ready();
  10075. Client cli(HOST, port);
  10076. auto res = cli.Get("/cookies");
  10077. ASSERT_TRUE(res);
  10078. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10079. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10080. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10081. }
  10082. // A stream may send a byte at a time with a small extension on each chunk,
  10083. // however long it runs
  10084. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10085. Server svr;
  10086. svr.Post("/count", [](const Request &req, Response &res) {
  10087. res.set_content(std::to_string(req.body.size()), "text/plain");
  10088. });
  10089. auto port = svr.bind_to_any_port(HOST);
  10090. ASSERT_LT(0, port);
  10091. thread t = thread([&] { svr.listen_after_bind(); });
  10092. auto se = detail::scope_exit([&] {
  10093. svr.stop();
  10094. t.join();
  10095. ASSERT_FALSE(svr.is_running());
  10096. });
  10097. svr.wait_until_ready();
  10098. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10099. "\r\nTransfer-Encoding: chunked\r\n"
  10100. "Connection: close\r\n\r\n";
  10101. for (auto i = 0; i < 4096; i++) {
  10102. req += "1;a=b\r\nx\r\n";
  10103. }
  10104. req += "0\r\n\r\n";
  10105. std::string res;
  10106. ASSERT_TRUE(send_request(5, req, &res, port));
  10107. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10108. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10109. }
  10110. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10111. Server svr;
  10112. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10113. auto i = new int(0);
  10114. res.set_header("Trailer", "X-Safe, X-Reflected");
  10115. res.set_chunked_content_provider(
  10116. "text/plain",
  10117. [i](size_t /*offset*/, DataSink &sink) {
  10118. if (*i == 0) {
  10119. sink.os << "body";
  10120. } else {
  10121. Headers trailer;
  10122. // A valid trailer that must survive.
  10123. trailer.emplace("X-Safe", "safe");
  10124. // Attacker-controlled value carrying CR/LF (response splitting).
  10125. trailer.emplace("X-Reflected",
  10126. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10127. // Attacker-controlled name carrying CR/LF.
  10128. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10129. sink.done_with_trailer(trailer);
  10130. }
  10131. (*i)++;
  10132. return true;
  10133. },
  10134. [i](bool /*success*/) { delete i; });
  10135. });
  10136. thread t = thread([&] { svr.listen(HOST, PORT); });
  10137. auto se = detail::scope_exit([&] {
  10138. svr.stop();
  10139. t.join();
  10140. ASSERT_FALSE(svr.is_running());
  10141. });
  10142. svr.wait_until_ready();
  10143. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10144. "Host: " + HOST +
  10145. "\r\n"
  10146. "Connection: close\r\n"
  10147. "\r\n";
  10148. std::string res;
  10149. ASSERT_TRUE(send_request(5, req, &res));
  10150. // The injected fields must not appear anywhere in the raw response.
  10151. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10152. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10153. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10154. // Invalid trailers are dropped entirely, matching set_header().
  10155. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10156. // The valid trailer still passes through.
  10157. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10158. }
  10159. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10160. // A custom header writer gets only the fields the default one writes
  10161. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10162. std::string s;
  10163. for (const auto &h : hdrs) {
  10164. s += h.first + ": " + h.second + "\r\n";
  10165. }
  10166. s += "\r\n";
  10167. return strm.write(s.data(), s.size());
  10168. };
  10169. for (auto custom_writer : {false, true}) {
  10170. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10171. Server svr;
  10172. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10173. svr.set_post_routing_handler([](const Request &, Response &res) {
  10174. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10175. });
  10176. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10177. // res.headers is a public field an application can populate directly,
  10178. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10179. // A valid header that must survive.
  10180. res.headers.emplace("X-Safe", "safe");
  10181. // Attacker-controlled value carrying CR/LF (response splitting).
  10182. res.headers.emplace("X-Reflected",
  10183. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10184. // Attacker-controlled name carrying CR/LF.
  10185. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10186. res.set_content("body", "text/plain");
  10187. });
  10188. thread t = thread([&] { svr.listen(HOST, PORT); });
  10189. auto se = detail::scope_exit([&] {
  10190. svr.stop();
  10191. t.join();
  10192. ASSERT_FALSE(svr.is_running());
  10193. });
  10194. svr.wait_until_ready();
  10195. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10196. "Host: " + HOST +
  10197. "\r\n"
  10198. "Connection: close\r\n"
  10199. "\r\n";
  10200. std::string res;
  10201. ASSERT_TRUE(send_request(5, req, &res));
  10202. // The injected fields must not appear anywhere in the raw response.
  10203. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10204. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10205. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10206. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10207. // Invalid headers are dropped entirely, matching set_header().
  10208. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10209. // The valid header still passes through.
  10210. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10211. }
  10212. }
  10213. // Forward declaration: in split builds split.py strips `inline` and moves the
  10214. // definition into httplib.cc, so detail::write_request_line is not visible from
  10215. // the public httplib.h. Re-declaring it here lets the tests link against the
  10216. // symbol in both header-only and split builds.
  10217. namespace httplib {
  10218. namespace detail {
  10219. ssize_t write_request_line(Stream &strm, const std::string &method,
  10220. const std::string &path);
  10221. } // namespace detail
  10222. } // namespace httplib
  10223. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10224. // A well-formed target is written verbatim.
  10225. {
  10226. detail::BufferStream strm;
  10227. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10228. EXPECT_GT(n, 0);
  10229. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10230. }
  10231. // A target carrying CR/LF, SP or other control octets must be rejected
  10232. // before anything reaches the wire, otherwise it splits the request line and
  10233. // injects a header or a whole request.
  10234. const std::string evil_targets[] = {
  10235. "/a\r\nInjected: pwned",
  10236. "/a\rInjected",
  10237. "/a\nInjected",
  10238. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10239. "/a b",
  10240. "/a\tb",
  10241. "/a\x7f",
  10242. };
  10243. for (const auto &evil : evil_targets) {
  10244. detail::BufferStream strm;
  10245. auto n = detail::write_request_line(strm, "GET", evil);
  10246. EXPECT_LT(n, 0);
  10247. EXPECT_TRUE(strm.get_buffer().empty());
  10248. }
  10249. }
  10250. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10251. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10252. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10253. // target reaches write_request. The client must fail cleanly with
  10254. // Error::Write instead of putting a request-line-less, header-injecting
  10255. // request on the wire.
  10256. Server svr;
  10257. svr.Get("/a", [](const Request &, Response &res) {
  10258. res.set_content("ok", "text/plain");
  10259. });
  10260. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10261. auto se = detail::scope_exit([&] {
  10262. svr.stop();
  10263. thread.join();
  10264. ASSERT_FALSE(svr.is_running());
  10265. });
  10266. svr.wait_until_ready();
  10267. {
  10268. Client cli(HOST, PORT);
  10269. cli.set_path_encode(false);
  10270. // The request is rejected before anything is written, so the connection
  10271. // stays silent and the subsequent response read would otherwise block for
  10272. // the full default read timeout. Shorten it -- the assertion is on the
  10273. // error, not the timeout.
  10274. cli.set_read_timeout(1, 0);
  10275. auto res = cli.Get("/a\r\nInjected: pwned");
  10276. EXPECT_FALSE(res);
  10277. EXPECT_EQ(Error::Write, res.error());
  10278. }
  10279. }
  10280. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10281. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10282. // including extension methods.
  10283. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10284. for (const auto &method : good_methods) {
  10285. detail::BufferStream strm;
  10286. auto n = detail::write_request_line(strm, method, "/");
  10287. EXPECT_GT(n, 0);
  10288. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10289. }
  10290. // A method carrying CR/LF would split the request line and smuggle a whole
  10291. // request ahead of the real one. A space or an empty method corrupts the
  10292. // request line. All must be rejected before anything reaches the wire.
  10293. const std::string evil_methods[] = {
  10294. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10295. "GET\r\nInjected: pwned",
  10296. "GET\r",
  10297. "GET\n",
  10298. "GE T",
  10299. "",
  10300. };
  10301. for (const auto &evil : evil_methods) {
  10302. detail::BufferStream strm;
  10303. auto n = detail::write_request_line(strm, evil, "/");
  10304. EXPECT_LT(n, 0);
  10305. EXPECT_TRUE(strm.get_buffer().empty());
  10306. }
  10307. }
  10308. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10309. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10310. // through Client::send must fail with Error::Write and no request, neither
  10311. // the smuggled one nor the real one, may reach the server.
  10312. Server svr;
  10313. std::atomic<int> request_count(0);
  10314. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10315. request_count++;
  10316. res.status = StatusCode::OK_200;
  10317. return Server::HandlerResponse::Handled;
  10318. });
  10319. auto port = svr.bind_to_any_port(HOST);
  10320. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10321. auto se = detail::scope_exit([&] {
  10322. svr.stop();
  10323. thread.join();
  10324. ASSERT_FALSE(svr.is_running());
  10325. });
  10326. svr.wait_until_ready();
  10327. {
  10328. Client cli(HOST, port);
  10329. const std::string evil_methods[] = {
  10330. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10331. "GE T",
  10332. "",
  10333. };
  10334. for (const auto &evil : evil_methods) {
  10335. Request req;
  10336. req.method = evil;
  10337. req.path = "/";
  10338. auto res = cli.send(req);
  10339. EXPECT_FALSE(res);
  10340. EXPECT_EQ(Error::Write, res.error());
  10341. }
  10342. auto handle =
  10343. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10344. EXPECT_FALSE(handle.is_valid());
  10345. EXPECT_EQ(Error::Write, handle.error);
  10346. // A valid request on the same client still goes through.
  10347. auto res = cli.Get("/");
  10348. ASSERT_TRUE(res);
  10349. EXPECT_EQ(StatusCode::OK_200, res->status);
  10350. }
  10351. EXPECT_EQ(1, request_count.load());
  10352. }
  10353. // Sends a raw request and verifies that there isn't a crash or exception.
  10354. static void test_raw_request(const std::string &req,
  10355. std::string *out = nullptr) {
  10356. Server svr;
  10357. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10358. res.set_content("ok", "text/plain");
  10359. });
  10360. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10361. res.set_content("ok", "text/plain");
  10362. });
  10363. svr.Get("/header_field_value_check",
  10364. [&](const Request & /*req*/, Response &res) {
  10365. res.set_content("ok", "text/plain");
  10366. });
  10367. svr.CustomRoute("PROPFIND", "/dav",
  10368. [&](const Request & /*req*/, Response &res) {
  10369. res.status = StatusCode::MultiStatus_207;
  10370. });
  10371. // Server read timeout must be longer than the client read timeout for the
  10372. // bug to reproduce, probably to force the server to process a request
  10373. // without a trailing blank line.
  10374. const time_t client_read_timeout_sec = 1;
  10375. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10376. bool listen_thread_ok = false;
  10377. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10378. auto se = detail::scope_exit([&] {
  10379. svr.stop();
  10380. t.join();
  10381. ASSERT_FALSE(svr.is_running());
  10382. EXPECT_TRUE(listen_thread_ok);
  10383. });
  10384. svr.wait_until_ready();
  10385. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10386. }
  10387. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10388. // A certain header line causes an exception if the header property is parsed
  10389. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10390. test_raw_request(
  10391. "GET /hi HTTP/1.1\r\n"
  10392. " : "
  10393. " "
  10394. " ");
  10395. }
  10396. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10397. // A certain header line causes an exception if the header property *name* is
  10398. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10399. // greedy matcher and requires backtracking when there are a lot of ":"
  10400. // characters.
  10401. // This occurs with libc++ but not libstdc++.
  10402. test_raw_request(
  10403. "GET /hi HTTP/1.1\r\n"
  10404. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10405. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10406. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10407. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10408. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10409. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10410. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10411. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10412. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10413. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10414. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10415. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10416. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10417. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10418. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10419. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10420. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10421. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10422. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10423. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10424. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10425. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10426. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10427. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10428. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10429. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10430. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10431. "&&&%%%");
  10432. }
  10433. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10434. // Make sure this doesn't crash the server.
  10435. // In a previous version of the header line regex, the "\r" rendered the line
  10436. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10437. // a new position where the leading white space ended and the field value
  10438. // began.
  10439. // The crash occurs with libc++ but not libstdc++.
  10440. test_raw_request("GET /hi HTTP/1.1\r\n"
  10441. "a:" +
  10442. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10443. "\r\n"
  10444. "\r\n");
  10445. }
  10446. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10447. const char *rejected[] = {
  10448. // RFC 9112 §3: one SP between the parts, and nothing else
  10449. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10450. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10451. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10452. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10453. // A request-target has no fragment
  10454. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10455. // An HTTP/1.1 request needs a Host
  10456. "GET /hi HTTP/1.1\r\n\r\n",
  10457. };
  10458. for (auto request : rejected) {
  10459. std::string out;
  10460. test_raw_request(request, &out);
  10461. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10462. }
  10463. std::string out;
  10464. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10465. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10466. }
  10467. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10468. // RFC 9112 §6.1
  10469. const char *requests[] = {
  10470. "PUT /put_hi HTTP/1.1\r\n"
  10471. "Host: localhost\r\n"
  10472. "Content-Length: 0\r\n"
  10473. "Transfer-Encoding: chunked\r\n"
  10474. "\r\n"
  10475. "0\r\n\r\n",
  10476. "PUT /put_hi HTTP/1.0\r\n"
  10477. "Connection: keep-alive\r\n"
  10478. "Transfer-Encoding: chunked\r\n"
  10479. "\r\n"
  10480. "0\r\n\r\n",
  10481. };
  10482. for (auto request : requests) {
  10483. std::string out;
  10484. test_raw_request(request, &out);
  10485. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10486. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10487. }
  10488. }
  10489. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10490. std::string out;
  10491. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10492. "Content-Type: text/plain\r\n"
  10493. "Transfer-Encoding: chunked\r\n"
  10494. "\r\n"
  10495. "nothex\r\n",
  10496. &out);
  10497. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10498. }
  10499. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10500. std::string out;
  10501. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10502. "Content-Type: text/plain\r\n"
  10503. "Transfer-Encoding: chunked\r\n"
  10504. "\r\n"
  10505. "3\r\n"
  10506. "xyz\r\n"
  10507. "NaN\r\n",
  10508. &out);
  10509. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10510. }
  10511. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  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. // Length is too large for 64 bits.
  10518. "1ffffffffffffffff\r\n"
  10519. "xyz\r\n",
  10520. &out);
  10521. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10522. }
  10523. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10524. test_raw_request("GET /hi HTTP/1.1\r\n"
  10525. "Content-Type: text/plain\r\n\r");
  10526. }
  10527. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10528. std::string out;
  10529. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10530. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10531. }
  10532. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10533. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10534. std::string out;
  10535. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10536. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10537. }
  10538. }
  10539. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10540. std::string out;
  10541. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10542. "Host: localhost\r\n"
  10543. "Connection: close\r\n\r\n",
  10544. &out);
  10545. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10546. }
  10547. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10548. Server svr;
  10549. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10550. EXPECT_TRUE(!req.remote_addr.empty());
  10551. });
  10552. thread t = thread([&] { svr.listen(HOST, PORT); });
  10553. auto se = detail::scope_exit([&] {
  10554. svr.stop();
  10555. t.join();
  10556. ASSERT_FALSE(svr.is_running());
  10557. });
  10558. svr.wait_until_ready();
  10559. // Send an invalid request line to trigger Bad Request
  10560. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10561. std::string out;
  10562. ASSERT_TRUE(send_request(5, bad_req, &out));
  10563. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10564. }
  10565. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10566. // answered right away rather than blocking on a read that waits for EOF.
  10567. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10568. std::string out;
  10569. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10570. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10571. }
  10572. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10573. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10574. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10575. for (const auto *method : methods) {
  10576. Server svr;
  10577. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10578. EXPECT_FALSE(svr.is_valid()) << method;
  10579. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10580. }
  10581. }
  10582. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10583. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10584. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10585. for (const auto *method : methods) {
  10586. Server svr;
  10587. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10588. EXPECT_FALSE(svr.is_valid()) << method;
  10589. }
  10590. }
  10591. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10592. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10593. "COPY", "MOVE", "LOCK",
  10594. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10595. Server svr;
  10596. for (const auto *method : methods) {
  10597. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10598. }
  10599. EXPECT_TRUE(svr.is_valid());
  10600. }
  10601. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10602. Server svr;
  10603. svr.CustomRoute("POST", "/x",
  10604. [](const Request &, Response &, const ContentReader &) {});
  10605. EXPECT_FALSE(svr.is_valid());
  10606. }
  10607. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10608. Server svr;
  10609. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10610. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10611. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10612. EXPECT_FALSE(svr.is_valid());
  10613. }
  10614. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10615. Server svr;
  10616. auto captured = Error::Success;
  10617. svr.set_error_logger(
  10618. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10619. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10620. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10621. }
  10622. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10623. std::string out;
  10624. std::string request(
  10625. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10626. test_raw_request(request, &out);
  10627. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10628. }
  10629. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10630. std::string out;
  10631. std::string request(
  10632. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10633. test_raw_request(request, &out);
  10634. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10635. }
  10636. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10637. std::string out;
  10638. std::string request(
  10639. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10640. test_raw_request(request, &out);
  10641. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10642. }
  10643. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10644. std::string out;
  10645. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10646. "Host: localhost\r\n"
  10647. "Test: \r\n\r\n",
  10648. &out);
  10649. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10650. }
  10651. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10652. Server svr;
  10653. std::string x_custom;
  10654. std::string cookie;
  10655. std::string xff;
  10656. std::string x_unicode;
  10657. std::string x_iis;
  10658. svr.Get("/check", [&](const Request &req, Response &res) {
  10659. x_custom = req.get_header_value("X-Custom");
  10660. cookie = req.get_header_value("Cookie");
  10661. xff = req.get_header_value("X-Forwarded-For");
  10662. x_unicode = req.get_header_value("X-Unicode");
  10663. x_iis = req.get_header_value("X-IIS");
  10664. res.set_content("ok", "text/plain");
  10665. });
  10666. thread t = thread([&] { svr.listen(HOST, PORT); });
  10667. auto se = detail::scope_exit([&] {
  10668. svr.stop();
  10669. t.join();
  10670. ASSERT_FALSE(svr.is_running());
  10671. });
  10672. svr.wait_until_ready();
  10673. const std::string req = "GET /check HTTP/1.1\r\n"
  10674. "Host: localhost\r\n"
  10675. "X-Custom: a%0D%0AInjected: b\r\n"
  10676. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10677. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10678. "X-Unicode: %E3%81%82\r\n"
  10679. "X-IIS: %u00E9\r\n"
  10680. "Connection: close\r\n"
  10681. "\r\n";
  10682. std::string res;
  10683. ASSERT_TRUE(send_request(5, req, &res));
  10684. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10685. // Every value must be returned verbatim (wire form), with no decoding.
  10686. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10687. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10688. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10689. EXPECT_EQ("%E3%81%82", x_unicode);
  10690. EXPECT_EQ("%u00E9", x_iis);
  10691. }
  10692. // Applications that previously relied on automatic percent-decoding can
  10693. // reproduce the old behavior by explicitly calling decode_path_component()
  10694. // or, for RFC 3986 conformance, decode_uri_component().
  10695. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10696. Server svr;
  10697. std::string decoded;
  10698. svr.Get("/check", [&](const Request &req, Response &res) {
  10699. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10700. res.set_content("ok", "text/plain");
  10701. });
  10702. thread t = thread([&] { svr.listen(HOST, PORT); });
  10703. auto se = detail::scope_exit([&] {
  10704. svr.stop();
  10705. t.join();
  10706. ASSERT_FALSE(svr.is_running());
  10707. });
  10708. svr.wait_until_ready();
  10709. const std::string req = "GET /check HTTP/1.1\r\n"
  10710. "Host: localhost\r\n"
  10711. "X-Custom: hello%20world\r\n"
  10712. "Connection: close\r\n"
  10713. "\r\n";
  10714. std::string res;
  10715. ASSERT_TRUE(send_request(5, req, &res));
  10716. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10717. EXPECT_EQ("hello world", decoded);
  10718. }
  10719. // Regression test for #2033. Browsers send Referer values that include
  10720. // percent-encoded characters such as %0A inside the URL. Decoding the
  10721. // header value would either trip the post-decode CR/LF/NUL guard (the
  10722. // original bug, returning 400) or, after that guard was relaxed, silently
  10723. // store a literal LF — both unacceptable. The wire form must round-trip.
  10724. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10725. Server svr;
  10726. std::string referer;
  10727. svr.Get("/check", [&](const Request &req, Response &res) {
  10728. referer = req.get_header_value("Referer");
  10729. res.set_content("ok", "text/plain");
  10730. });
  10731. thread t = thread([&] { svr.listen(HOST, PORT); });
  10732. auto se = detail::scope_exit([&] {
  10733. svr.stop();
  10734. t.join();
  10735. ASSERT_FALSE(svr.is_running());
  10736. });
  10737. svr.wait_until_ready();
  10738. const std::string req = "GET /check HTTP/1.1\r\n"
  10739. "Host: localhost\r\n"
  10740. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10741. "Connection: close\r\n"
  10742. "\r\n";
  10743. std::string res;
  10744. ASSERT_TRUE(send_request(5, req, &res));
  10745. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10746. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10747. }
  10748. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10749. Server svr;
  10750. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10751. res.set_header("Cache-Control", "no-cache");
  10752. res.set_chunked_content_provider(
  10753. "text/event-stream", [](size_t offset, DataSink &sink) {
  10754. std::string s = "data:";
  10755. s += std::to_string(offset);
  10756. s += "\n\n";
  10757. auto ret = sink.write(s.data(), s.size());
  10758. EXPECT_TRUE(ret);
  10759. std::this_thread::sleep_for(std::chrono::seconds(1));
  10760. return true;
  10761. });
  10762. });
  10763. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10764. svr.wait_until_ready();
  10765. Client client(HOST, PORT);
  10766. const Headers headers = {{"Accept", "text/event-stream"}};
  10767. auto get_thread = std::thread([&client, &headers]() {
  10768. auto res = client.Get(
  10769. "/events", headers,
  10770. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10771. });
  10772. auto se = detail::scope_exit([&] {
  10773. svr.stop();
  10774. get_thread.join();
  10775. listen_thread.join();
  10776. ASSERT_FALSE(svr.is_running());
  10777. });
  10778. // Give GET time to get a few messages.
  10779. std::this_thread::sleep_for(std::chrono::seconds(2));
  10780. }
  10781. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10782. httplib::Server svr;
  10783. svr.Post("/hi",
  10784. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10785. res.status = StatusCode::OK_200;
  10786. });
  10787. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10788. svr.wait_until_ready();
  10789. Client cli(HOST, PORT);
  10790. auto res = cli.Post("/hi", "data", "text/plain");
  10791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10792. EXPECT_EQ(StatusCode::OK_200, res->status);
  10793. svr.stop();
  10794. thread.join();
  10795. ASSERT_FALSE(svr.is_running());
  10796. res = cli.Post("/hi", "data", "text/plain");
  10797. ASSERT_FALSE(res);
  10798. }
  10799. TEST(ServerStopTest, ListenFailure) {
  10800. Server svr;
  10801. auto t = thread([&]() {
  10802. auto ret = svr.listen("????", PORT);
  10803. EXPECT_FALSE(ret);
  10804. });
  10805. svr.wait_until_ready();
  10806. svr.stop();
  10807. t.join();
  10808. }
  10809. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10810. TEST(ServerStopTest, Decommision) {
  10811. Server svr;
  10812. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10813. for (int i = 0; i < 4; i++) {
  10814. auto is_even = !(i % 2);
  10815. std::thread t{[&] {
  10816. try {
  10817. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10818. if (is_even) {
  10819. throw std::runtime_error("Some thing that happens to go wrong.");
  10820. }
  10821. svr.listen(HOST, PORT);
  10822. } catch (...) { svr.decommission(); }
  10823. }};
  10824. svr.wait_until_ready();
  10825. // Server is up
  10826. {
  10827. Client cli(HOST, PORT);
  10828. auto res = cli.Get("/hi");
  10829. if (is_even) {
  10830. EXPECT_FALSE(res);
  10831. } else {
  10832. EXPECT_TRUE(res);
  10833. EXPECT_EQ("hi...", res->body);
  10834. }
  10835. }
  10836. svr.stop();
  10837. t.join();
  10838. // Server is down...
  10839. {
  10840. Client cli(HOST, PORT);
  10841. auto res = cli.Get("/hi");
  10842. EXPECT_FALSE(res);
  10843. }
  10844. }
  10845. }
  10846. #endif
  10847. // Helper function for string body upload progress tests
  10848. template <typename SetupHandler, typename ClientCall>
  10849. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10850. ClientCall &&client_call,
  10851. const string &body) {
  10852. Server svr;
  10853. setup_handler(svr);
  10854. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10855. auto se = detail::scope_exit([&] {
  10856. svr.stop();
  10857. t.join();
  10858. });
  10859. svr.wait_until_ready();
  10860. Client cli(HOST, PORT);
  10861. vector<uint64_t> progress_values;
  10862. bool progress_called = false;
  10863. auto res =
  10864. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10865. progress_values.push_back(current);
  10866. progress_called = true;
  10867. return true;
  10868. });
  10869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10870. EXPECT_EQ(200, res->status);
  10871. EXPECT_TRUE(progress_called);
  10872. }
  10873. TEST(UploadProgressTest, PostStringBodyBasic) {
  10874. TestStringBodyUploadProgress(
  10875. [](Server &svr) {
  10876. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10877. res.set_content("received", "text/plain");
  10878. });
  10879. },
  10880. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10881. return cli.Post("/test", body, "text/plain", progress_callback);
  10882. },
  10883. "test data for upload progress");
  10884. }
  10885. TEST(UploadProgressTest, PutStringBodyBasic) {
  10886. TestStringBodyUploadProgress(
  10887. [](Server &svr) {
  10888. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10889. res.set_content("put received", "text/plain");
  10890. });
  10891. },
  10892. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10893. return cli.Put("/test", body, "text/plain", progress_callback);
  10894. },
  10895. "put test data for upload progress");
  10896. }
  10897. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10898. TestStringBodyUploadProgress(
  10899. [](Server &svr) {
  10900. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10901. res.set_content("patch received", "text/plain");
  10902. });
  10903. },
  10904. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10905. return cli.Patch("/test", body, "text/plain", progress_callback);
  10906. },
  10907. "patch test data for upload progress");
  10908. }
  10909. // Helper function for content provider upload progress tests
  10910. template <typename SetupHandler, typename ClientCall>
  10911. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10912. ClientCall &&client_call) {
  10913. Server svr;
  10914. setup_handler(svr);
  10915. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10916. auto se = detail::scope_exit([&] {
  10917. svr.stop();
  10918. t.join();
  10919. });
  10920. svr.wait_until_ready();
  10921. Client cli(HOST, PORT);
  10922. vector<uint64_t> progress_values;
  10923. auto res =
  10924. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10925. progress_values.push_back(current);
  10926. return true;
  10927. });
  10928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10929. EXPECT_EQ(200, res->status);
  10930. EXPECT_FALSE(progress_values.empty());
  10931. }
  10932. TEST(UploadProgressTest, PostContentProviderProgress) {
  10933. TestContentProviderUploadProgress(
  10934. [](Server &svr) {
  10935. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10936. res.set_content("provider received", "text/plain");
  10937. });
  10938. },
  10939. [](Client &cli, UploadProgress progress_callback) {
  10940. return cli.Post(
  10941. "/test", 9,
  10942. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10943. sink.os << "test data";
  10944. return true;
  10945. },
  10946. "text/plain", progress_callback);
  10947. });
  10948. }
  10949. // Helper function for multipart upload progress tests
  10950. template <typename SetupHandler, typename ClientCall>
  10951. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10952. ClientCall &&client_call,
  10953. const string &endpoint) {
  10954. Server svr;
  10955. setup_handler(svr);
  10956. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10957. auto se = detail::scope_exit([&] {
  10958. svr.stop();
  10959. t.join();
  10960. });
  10961. svr.wait_until_ready();
  10962. Client cli(HOST, PORT);
  10963. vector<uint64_t> progress_values;
  10964. UploadFormDataItems items = {
  10965. {"field1", "value1", "", ""},
  10966. {"field2", "longer value for progress tracking test", "", ""},
  10967. {"file1", "file content data for upload progress", "test.txt",
  10968. "text/plain"}};
  10969. auto res = client_call(cli, endpoint, items,
  10970. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10971. progress_values.push_back(current);
  10972. return true;
  10973. });
  10974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10975. EXPECT_EQ(200, res->status);
  10976. EXPECT_FALSE(progress_values.empty());
  10977. }
  10978. TEST(UploadProgressTest, PostMultipartProgress) {
  10979. TestMultipartUploadProgress(
  10980. [](Server &svr) {
  10981. svr.Post("/multipart", [](const Request &req, Response &res) {
  10982. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10983. res.set_content("multipart received", "text/plain");
  10984. });
  10985. },
  10986. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10987. UploadProgress progress_callback) {
  10988. return cli.Post(endpoint, items, progress_callback);
  10989. },
  10990. "/multipart");
  10991. }
  10992. // Helper function for basic download progress tests
  10993. template <typename SetupHandler, typename ClientCall>
  10994. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10995. ClientCall &&client_call, const string &endpoint,
  10996. size_t expected_content_size) {
  10997. Server svr;
  10998. setup_handler(svr);
  10999. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11000. auto se = detail::scope_exit([&] {
  11001. svr.stop();
  11002. t.join();
  11003. });
  11004. svr.wait_until_ready();
  11005. Client cli(HOST, PORT);
  11006. vector<uint64_t> progress_values;
  11007. auto res = client_call(cli, endpoint,
  11008. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11009. progress_values.push_back(current);
  11010. return true;
  11011. });
  11012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11013. EXPECT_EQ(200, res->status);
  11014. EXPECT_FALSE(progress_values.empty());
  11015. EXPECT_EQ(expected_content_size, res->body.size());
  11016. }
  11017. TEST(DownloadProgressTest, GetBasic) {
  11018. TestBasicDownloadProgress(
  11019. [](Server &svr) {
  11020. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11021. string content(1000, 'D');
  11022. res.set_content(content, "text/plain");
  11023. });
  11024. },
  11025. [](Client &cli, const string &endpoint,
  11026. DownloadProgress progress_callback) {
  11027. return cli.Get(endpoint, progress_callback);
  11028. },
  11029. "/download", 1000u);
  11030. }
  11031. // Helper function for content receiver download progress tests
  11032. template <typename SetupHandler, typename ClientCall>
  11033. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11034. ClientCall &&client_call,
  11035. const string &endpoint,
  11036. size_t expected_content_size) {
  11037. Server svr;
  11038. setup_handler(svr);
  11039. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11040. auto se = detail::scope_exit([&] {
  11041. svr.stop();
  11042. t.join();
  11043. });
  11044. svr.wait_until_ready();
  11045. Client cli(HOST, PORT);
  11046. vector<uint64_t> progress_values;
  11047. string received_body;
  11048. auto res = client_call(
  11049. cli, endpoint,
  11050. [&](const char *data, size_t data_length) -> bool {
  11051. received_body.append(data, data_length);
  11052. return true;
  11053. },
  11054. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11055. progress_values.push_back(current);
  11056. return true;
  11057. });
  11058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11059. EXPECT_EQ(200, res->status);
  11060. EXPECT_FALSE(progress_values.empty());
  11061. EXPECT_EQ(expected_content_size, received_body.size());
  11062. EXPECT_TRUE(res->body.empty());
  11063. }
  11064. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11065. TestContentReceiverDownloadProgress(
  11066. [](Server &svr) {
  11067. svr.Get("/download-receiver",
  11068. [](const Request & /*req*/, Response &res) {
  11069. string content(2000, 'R');
  11070. res.set_content(content, "text/plain");
  11071. });
  11072. },
  11073. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11074. DownloadProgress progress_callback) {
  11075. return cli.Get(endpoint, content_receiver, progress_callback);
  11076. },
  11077. "/download-receiver", 2000u);
  11078. }
  11079. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11080. // A provider reaching a pass with nothing to hand over - an empty buffer
  11081. // popped off a queue, say - must not be taken to mean the body is finished.
  11082. // It used to end the loop with the terminating chunk unwritten while the
  11083. // server still considered the response complete, so the peer waited for an
  11084. // end that never arrived.
  11085. Server svr;
  11086. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11087. auto step = std::make_shared<int>(0);
  11088. res.set_chunked_content_provider("text/plain",
  11089. [step](size_t /*offset*/, DataSink &sink) {
  11090. switch ((*step)++) {
  11091. case 0: sink.write("", 0); break;
  11092. case 1: sink.write("hello", 5); break;
  11093. default: sink.done(); break;
  11094. }
  11095. return true;
  11096. });
  11097. });
  11098. auto port = svr.bind_to_any_port(HOST);
  11099. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11100. auto listen_se = detail::scope_exit([&] {
  11101. svr.stop();
  11102. listen_thread.join();
  11103. ASSERT_FALSE(svr.is_running());
  11104. });
  11105. svr.wait_until_ready();
  11106. Client cli(HOST, port);
  11107. // Without the fix the body is never terminated, so bound the wait rather
  11108. // than letting the test hang on the default read timeout.
  11109. cli.set_read_timeout(5, 0);
  11110. auto res = cli.Get("/stream");
  11111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11112. EXPECT_EQ(StatusCode::OK_200, res->status);
  11113. EXPECT_EQ("hello", res->body);
  11114. }
  11115. TEST(StreamingTest, NoContentLengthStreaming) {
  11116. Server svr;
  11117. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11118. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11119. if (offset < 6) {
  11120. sink.os << (offset < 3 ? "a" : "b");
  11121. } else {
  11122. sink.done();
  11123. }
  11124. return true;
  11125. });
  11126. });
  11127. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11128. auto listen_se = detail::scope_exit([&] {
  11129. svr.stop();
  11130. listen_thread.join();
  11131. ASSERT_FALSE(svr.is_running());
  11132. });
  11133. svr.wait_until_ready();
  11134. Client client(HOST, PORT);
  11135. auto get_thread = std::thread([&client]() {
  11136. std::string s;
  11137. auto res =
  11138. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11139. s += std::string(data, len);
  11140. return true;
  11141. });
  11142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11143. EXPECT_EQ(StatusCode::OK_200, res->status);
  11144. EXPECT_EQ("aaabbb", s);
  11145. });
  11146. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11147. // Give GET time to get a few messages.
  11148. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11149. }
  11150. TEST(MountTest, Unmount) {
  11151. Server svr;
  11152. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11153. auto se = detail::scope_exit([&] {
  11154. svr.stop();
  11155. listen_thread.join();
  11156. ASSERT_FALSE(svr.is_running());
  11157. });
  11158. svr.wait_until_ready();
  11159. Client cli("localhost", PORT);
  11160. svr.set_mount_point("/mount2", "./www2");
  11161. auto res = cli.Get("/");
  11162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11163. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11164. res = cli.Get("/mount2/dir/test.html");
  11165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11166. EXPECT_EQ(StatusCode::OK_200, res->status);
  11167. svr.set_mount_point("/", "./www");
  11168. res = cli.Get("/dir/");
  11169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11170. EXPECT_EQ(StatusCode::OK_200, res->status);
  11171. svr.remove_mount_point("/");
  11172. res = cli.Get("/dir/");
  11173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11174. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11175. svr.remove_mount_point("/mount2");
  11176. res = cli.Get("/mount2/dir/test.html");
  11177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11178. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11179. }
  11180. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11181. Server svr;
  11182. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11183. svr.Get("/api/hello", [](const Request &, Response &res) {
  11184. res.set_content("api", "text/plain");
  11185. });
  11186. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11187. auto se = detail::scope_exit([&] {
  11188. svr.stop();
  11189. listen_thread.join();
  11190. ASSERT_FALSE(svr.is_running());
  11191. });
  11192. svr.wait_until_ready();
  11193. Client cli(HOST, PORT);
  11194. auto res = cli.Get("/dir/test.html");
  11195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11196. EXPECT_EQ(StatusCode::OK_200, res->status);
  11197. res = cli.Get("/api/hello");
  11198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11199. EXPECT_EQ(StatusCode::OK_200, res->status);
  11200. EXPECT_EQ("api", res->body);
  11201. }
  11202. TEST(MountTest, PathSegmentBoundary) {
  11203. Server svr;
  11204. svr.set_mount_point("/mount2", "./www2");
  11205. svr.set_mount_point("/", "./www");
  11206. auto port = svr.bind_to_any_port(HOST);
  11207. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11208. auto se = detail::scope_exit([&] {
  11209. svr.stop();
  11210. listen_thread.join();
  11211. ASSERT_FALSE(svr.is_running());
  11212. });
  11213. svr.wait_until_ready();
  11214. Client cli(HOST, port);
  11215. auto res = cli.Get("/mount2/dir/test.html");
  11216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11217. EXPECT_EQ(StatusCode::OK_200, res->status);
  11218. // "/mount2" must not match part-way through a path segment.
  11219. res = cli.Get("/mount2dir/test.html");
  11220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11221. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11222. // A mount point ending in '/' keeps matching every path below it.
  11223. res = cli.Get("/dir/test.html");
  11224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11225. EXPECT_EQ(StatusCode::OK_200, res->status);
  11226. }
  11227. TEST(MountTest, Redicect) {
  11228. Server svr;
  11229. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11230. auto se = detail::scope_exit([&] {
  11231. svr.stop();
  11232. listen_thread.join();
  11233. ASSERT_FALSE(svr.is_running());
  11234. });
  11235. svr.set_mount_point("/", "./www");
  11236. svr.wait_until_ready();
  11237. Client cli("localhost", PORT);
  11238. auto res = cli.Get("/dir/");
  11239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11240. EXPECT_EQ(StatusCode::OK_200, res->status);
  11241. res = cli.Get("/dir");
  11242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11243. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11244. res = cli.Get("/file");
  11245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11246. EXPECT_EQ(StatusCode::OK_200, res->status);
  11247. res = cli.Get("/file/");
  11248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11249. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11250. cli.set_follow_location(true);
  11251. res = cli.Get("/dir");
  11252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11253. EXPECT_EQ(StatusCode::OK_200, res->status);
  11254. }
  11255. TEST(MountTest, MultibytesPathName) {
  11256. Server svr;
  11257. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11258. auto se = detail::scope_exit([&] {
  11259. svr.stop();
  11260. listen_thread.join();
  11261. ASSERT_FALSE(svr.is_running());
  11262. });
  11263. svr.set_mount_point("/", "./www");
  11264. svr.wait_until_ready();
  11265. Client cli("localhost", PORT);
  11266. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11268. EXPECT_EQ(StatusCode::OK_200, res->status);
  11269. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11270. }
  11271. // A mount point serves no path with an empty segment or one ending in '.' or
  11272. // a space, so a guard in the pre-routing handler sees the path of every file
  11273. // that is served
  11274. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11275. Server svr;
  11276. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11277. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11278. if (req.path == "/dir/test.html") {
  11279. res.status = StatusCode::Unauthorized_401;
  11280. return Server::HandlerResponse::Handled;
  11281. }
  11282. return Server::HandlerResponse::Unhandled;
  11283. });
  11284. auto port = svr.bind_to_any_port(HOST);
  11285. ASSERT_LT(0, port);
  11286. thread t = thread([&] { svr.listen_after_bind(); });
  11287. auto se = detail::scope_exit([&] {
  11288. svr.stop();
  11289. t.join();
  11290. ASSERT_FALSE(svr.is_running());
  11291. });
  11292. svr.wait_until_ready();
  11293. Client cli(HOST, port);
  11294. for (auto path :
  11295. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11296. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11297. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11298. "/dir/test.html%3A%3A$DATA"}) {
  11299. SCOPED_TRACE(path);
  11300. auto res = cli.Get(path);
  11301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11302. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11303. }
  11304. }
  11305. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11306. Server svr;
  11307. svr.set_mount_point("/", "./www");
  11308. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11309. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11310. auto port = svr.bind_to_any_port(HOST);
  11311. ASSERT_GT(port, 0);
  11312. thread t = thread([&] { svr.listen_after_bind(); });
  11313. auto se = detail::scope_exit([&] {
  11314. svr.stop();
  11315. t.join();
  11316. ASSERT_FALSE(svr.is_running());
  11317. });
  11318. svr.wait_until_ready();
  11319. Client cli(HOST, port);
  11320. auto res = cli.Get("/dir/test.abcde");
  11321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11322. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11323. res = cli.Get("/dir/test.html");
  11324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11325. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11326. }
  11327. #ifdef _WIN32
  11328. // Issue #2435: mmap::open() must succeed even when another handle holds
  11329. // the file open for writing (e.g. an active log file).
  11330. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11331. const char *path = "mmap_concurrent_writer_test.txt";
  11332. const char *content = "hello";
  11333. {
  11334. std::ofstream f(path, std::ios::binary);
  11335. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11336. }
  11337. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11338. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11339. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11340. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11341. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11342. detail::mmap m(path);
  11343. ASSERT_TRUE(m.is_open());
  11344. EXPECT_EQ(strlen(content), m.size());
  11345. char buf[8];
  11346. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11347. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11348. }
  11349. #endif
  11350. #ifndef _WIN32
  11351. // A directory or a device has no size to serve.
  11352. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11353. const char *path = "./mmap_not_regular_test_dir";
  11354. ASSERT_EQ(0, ::mkdir(path, 0755));
  11355. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11356. for (auto p : {path, "/dev/null"}) {
  11357. detail::mmap m(p);
  11358. EXPECT_FALSE(m.is_open()) << p;
  11359. EXPECT_EQ(0U, m.size()) << p;
  11360. }
  11361. Server svr;
  11362. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11363. res.set_file_content("/dev/null");
  11364. });
  11365. auto port = svr.bind_to_any_port(HOST);
  11366. thread t = thread([&] { svr.listen_after_bind(); });
  11367. auto se = detail::scope_exit([&] {
  11368. svr.stop();
  11369. t.join();
  11370. });
  11371. svr.wait_until_ready();
  11372. auto res = Client(HOST, port).Get("/null");
  11373. ASSERT_TRUE(res);
  11374. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11375. }
  11376. #endif
  11377. #ifdef __linux__
  11378. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11379. TEST(MmapTest, FileIsNotMapped) {
  11380. const char *path = "mmap_not_mapped_test.txt";
  11381. {
  11382. std::ofstream f(path, std::ios::binary);
  11383. f << "hello";
  11384. }
  11385. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11386. detail::mmap m(path);
  11387. ASSERT_TRUE(m.is_open());
  11388. std::ifstream maps("/proc/self/maps");
  11389. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11390. std::istreambuf_iterator<char>());
  11391. EXPECT_EQ(std::string::npos, mappings.find(path));
  11392. }
  11393. #endif
  11394. TEST(KeepAliveTest, ReadTimeout) {
  11395. Server svr;
  11396. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11397. std::this_thread::sleep_for(std::chrono::seconds(2));
  11398. res.set_content("a", "text/plain");
  11399. });
  11400. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11401. res.set_content("b", "text/plain");
  11402. });
  11403. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11404. auto se = detail::scope_exit([&] {
  11405. svr.stop();
  11406. listen_thread.join();
  11407. ASSERT_FALSE(svr.is_running());
  11408. });
  11409. svr.wait_until_ready();
  11410. Client cli("localhost", PORT);
  11411. cli.set_keep_alive(true);
  11412. cli.set_read_timeout(std::chrono::seconds(1));
  11413. auto resa = cli.Get("/a");
  11414. ASSERT_FALSE(resa);
  11415. EXPECT_EQ(Error::Read, resa.error());
  11416. auto resb = cli.Get("/b");
  11417. ASSERT_TRUE(resb);
  11418. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11419. EXPECT_EQ("b", resb->body);
  11420. }
  11421. TEST(KeepAliveTest, MaxCount) {
  11422. size_t keep_alive_max_count = 3;
  11423. Server svr;
  11424. svr.set_keep_alive_max_count(keep_alive_max_count);
  11425. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11426. res.set_content("Hello World!", "text/plain");
  11427. });
  11428. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11429. auto se = detail::scope_exit([&] {
  11430. svr.stop();
  11431. listen_thread.join();
  11432. ASSERT_FALSE(svr.is_running());
  11433. });
  11434. svr.wait_until_ready();
  11435. Client cli(HOST, PORT);
  11436. cli.set_keep_alive(true);
  11437. for (size_t i = 0; i < 5; i++) {
  11438. auto result = cli.Get("/hi");
  11439. ASSERT_TRUE(result);
  11440. EXPECT_EQ(StatusCode::OK_200, result->status);
  11441. if (i == keep_alive_max_count - 1) {
  11442. EXPECT_EQ("close", result->get_header_value("Connection"));
  11443. } else {
  11444. EXPECT_FALSE(result->has_header("Connection"));
  11445. }
  11446. }
  11447. }
  11448. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11449. // can pull the next one into the server's buffer. The server must serve it
  11450. // without waiting for the socket to become readable again. The keep-alive
  11451. // timeout outlasts the client's read timeout, so a request left waiting for it
  11452. // shows up as a missing response.
  11453. static void serve_pipelining_routes(Server &svr,
  11454. const std::function<void(int)> &client) {
  11455. svr.set_keep_alive_timeout(5);
  11456. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11457. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11458. });
  11459. svr.Post("/echo", [](const Request &req, Response &res) {
  11460. res.set_content("echo " + req.body, "text/plain");
  11461. });
  11462. auto port = svr.bind_to_any_port(HOST);
  11463. thread t = thread([&] { svr.listen_after_bind(); });
  11464. auto se = detail::scope_exit([&] {
  11465. svr.stop();
  11466. t.join();
  11467. });
  11468. svr.wait_until_ready();
  11469. client(port);
  11470. }
  11471. static std::string
  11472. send_pipelined_requests(const std::vector<std::string> &parts) {
  11473. Server svr;
  11474. std::string res;
  11475. serve_pipelining_routes(svr, [&](int port) {
  11476. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11477. });
  11478. return res;
  11479. }
  11480. static void expect_in_order(const std::string &res,
  11481. const std::vector<std::string> &bodies) {
  11482. size_t pos = 0;
  11483. for (const auto &body : bodies) {
  11484. pos = res.find(body, pos);
  11485. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11486. pos += body.size();
  11487. }
  11488. }
  11489. TEST(KeepAliveTest, PipelinedRequests) {
  11490. auto res = send_pipelined_requests(
  11491. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11492. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11493. "Content-Length: 4\r\n\r\nbody"
  11494. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11495. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11496. }
  11497. // The second request starts in the server's buffer and ends on the socket.
  11498. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11499. auto res =
  11500. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11501. "GET /hi/2 HTTP/1.1\r\nHo",
  11502. "st: localhost\r\nConnection: close\r\n\r\n"});
  11503. expect_in_order(res, {"hi 1", "hi 2"});
  11504. }
  11505. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11506. // CRLF after a body does not turn into a 400 for the next request.
  11507. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11508. auto res = send_pipelined_requests(
  11509. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11510. "Content-Length: 4\r\n\r\nbody\r\n"
  11511. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11512. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11513. expect_in_order(res, {"echo body", "hi 2"});
  11514. }
  11515. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11516. // must not be served as the next request.
  11517. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11518. auto res = send_pipelined_requests(
  11519. {"INVALID REQUEST LINE\r\n\r\n"
  11520. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11521. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11522. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11523. }
  11524. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11525. // Over TLS, the next request is held by the TLS library as already decrypted
  11526. // data rather than on the socket.
  11527. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11528. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11529. std::string res;
  11530. serve_pipelining_routes(svr, [&](int port) {
  11531. // One part, so all three requests arrive in one TLS record
  11532. EXPECT_TRUE(send_ssl_request_in_parts(
  11533. 2,
  11534. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11535. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11536. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11537. &res, port));
  11538. });
  11539. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11540. }
  11541. #endif
  11542. TEST(KeepAliveTest, Issue1041) {
  11543. Server svr;
  11544. svr.set_keep_alive_timeout(3);
  11545. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11546. res.set_content("Hello World!", "text/plain");
  11547. });
  11548. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11549. auto se = detail::scope_exit([&] {
  11550. svr.stop();
  11551. listen_thread.join();
  11552. ASSERT_FALSE(svr.is_running());
  11553. });
  11554. svr.wait_until_ready();
  11555. Client cli(HOST, PORT);
  11556. cli.set_keep_alive(true);
  11557. auto result = cli.Get("/hi");
  11558. ASSERT_TRUE(result);
  11559. EXPECT_EQ(StatusCode::OK_200, result->status);
  11560. std::this_thread::sleep_for(std::chrono::seconds(5));
  11561. result = cli.Get("/hi");
  11562. ASSERT_TRUE(result);
  11563. EXPECT_EQ(StatusCode::OK_200, result->status);
  11564. }
  11565. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11566. Server svr;
  11567. svr.set_keep_alive_max_count(0);
  11568. std::set<int> remote_ports;
  11569. svr.Get("/hi", [&](const Request &req, Response &res) {
  11570. remote_ports.insert(req.remote_port);
  11571. res.set_content("hi", "text/plain");
  11572. });
  11573. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11574. auto se = detail::scope_exit([&] {
  11575. svr.stop();
  11576. listen_thread.join();
  11577. ASSERT_FALSE(svr.is_running());
  11578. });
  11579. svr.wait_until_ready();
  11580. Client cli(HOST, PORT);
  11581. cli.set_keep_alive(true);
  11582. for (int i = 0; i < 3; i++) {
  11583. auto res = cli.Get("/hi");
  11584. ASSERT_TRUE(res);
  11585. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11586. }
  11587. // All three over one connection
  11588. EXPECT_EQ(1u, remote_ports.size());
  11589. }
  11590. // Forward declaration (see the base64_encode note).
  11591. namespace httplib {
  11592. namespace detail {
  11593. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11594. } // namespace detail
  11595. } // namespace httplib
  11596. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11597. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11598. #ifndef _WIN32
  11599. signal(SIGPIPE, SIG_IGN);
  11600. #endif
  11601. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11602. ASSERT_NE(INVALID_SOCKET, srv);
  11603. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11604. default_socket_options(srv);
  11605. sockaddr_in addr{};
  11606. addr.sin_family = AF_INET;
  11607. addr.sin_port = 0;
  11608. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11609. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11610. ASSERT_EQ(0, ::listen(srv, 2));
  11611. socklen_t addr_len = sizeof(addr);
  11612. ASSERT_EQ(0,
  11613. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11614. auto port = ntohs(addr.sin_port);
  11615. struct Peer {
  11616. socket_t sock = INVALID_SOCKET;
  11617. #ifdef CPPHTTPLIB_SSL_ENABLED
  11618. tls::session_t session = nullptr;
  11619. #endif
  11620. };
  11621. #ifdef CPPHTTPLIB_SSL_ENABLED
  11622. tls::ctx_t ctx = nullptr;
  11623. if (use_tls) {
  11624. ctx = tls::create_server_context();
  11625. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11626. nullptr);
  11627. }
  11628. auto ctx_se = detail::scope_exit([&] {
  11629. if (ctx) { tls::free_context(ctx); }
  11630. });
  11631. #endif
  11632. auto close_peer = [](Peer &peer) {
  11633. #ifdef CPPHTTPLIB_SSL_ENABLED
  11634. if (peer.session) { tls::free_session(peer.session); }
  11635. #endif
  11636. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11637. };
  11638. auto accept_peer = [&]() {
  11639. Peer peer;
  11640. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11641. peer.sock = ::accept(srv, nullptr, nullptr);
  11642. if (peer.sock == INVALID_SOCKET) { return peer; }
  11643. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11644. #ifdef CPPHTTPLIB_SSL_ENABLED
  11645. if (use_tls) {
  11646. peer.session = tls::create_session(ctx, peer.sock);
  11647. tls::TlsError err;
  11648. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err)) {
  11649. close_peer(peer);
  11650. return Peer();
  11651. }
  11652. }
  11653. #endif
  11654. return peer;
  11655. };
  11656. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11657. #ifdef CPPHTTPLIB_SSL_ENABLED
  11658. tls::TlsError err;
  11659. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11660. #endif
  11661. return detail::read_socket(peer.sock, buf, len, 0);
  11662. };
  11663. auto read_head = [&](const Peer &peer) {
  11664. std::string head;
  11665. char buf[1024];
  11666. while (head.find("\r\n\r\n") == std::string::npos) {
  11667. auto n = read_some(peer, buf, sizeof(buf));
  11668. if (n <= 0) { break; }
  11669. head.append(buf, static_cast<size_t>(n));
  11670. }
  11671. };
  11672. auto send_text = [](const Peer &peer, const std::string &text) {
  11673. #ifdef CPPHTTPLIB_SSL_ENABLED
  11674. tls::TlsError err;
  11675. if (peer.session) {
  11676. tls::write(peer.session, text.data(), text.size(), err);
  11677. return;
  11678. }
  11679. #endif
  11680. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11681. };
  11682. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11683. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11684. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11685. // Sent once the first response is read, so that it lands on an idle socket
  11686. std::promise<void> first_response_read;
  11687. auto first_response_read_future = first_response_read.get_future();
  11688. auto server_thread = std::thread([&] {
  11689. auto peer1 = accept_peer();
  11690. if (peer1.sock == INVALID_SOCKET) { return; }
  11691. read_head(peer1);
  11692. if (same_write) {
  11693. send_text(peer1, first + stray);
  11694. } else {
  11695. send_text(peer1, first);
  11696. first_response_read_future.wait_for(std::chrono::seconds(5));
  11697. send_text(peer1, stray);
  11698. }
  11699. // peer1 stays open, so only the unread data can tell the client
  11700. auto peer2 = accept_peer();
  11701. if (peer2.sock != INVALID_SOCKET) {
  11702. read_head(peer2);
  11703. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11704. "Connection: close\r\n\r\nsecond");
  11705. close_peer(peer2);
  11706. }
  11707. close_peer(peer1);
  11708. });
  11709. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11710. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11711. std::to_string(port));
  11712. #ifdef CPPHTTPLIB_SSL_ENABLED
  11713. cli.enable_server_certificate_verification(false);
  11714. #endif
  11715. cli.set_keep_alive(true);
  11716. cli.set_read_timeout(5, 0);
  11717. auto res = cli.Get("/1");
  11718. first_response_read.set_value();
  11719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11720. EXPECT_EQ("first", res->body);
  11721. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11722. res = cli.Get("/2");
  11723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11724. EXPECT_EQ(StatusCode::OK_200, res->status);
  11725. EXPECT_EQ("second", res->body);
  11726. }
  11727. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11728. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11729. }
  11730. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11731. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11732. }
  11733. #ifdef CPPHTTPLIB_SSL_ENABLED
  11734. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11735. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11736. }
  11737. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11738. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11739. }
  11740. #endif
  11741. TEST(KeepAliveTest, Issue1959) {
  11742. Server svr;
  11743. svr.set_keep_alive_timeout(5);
  11744. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11745. res.set_content("a", "text/plain");
  11746. });
  11747. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11748. auto se = detail::scope_exit([&] {
  11749. if (!svr.is_running()) return;
  11750. svr.stop();
  11751. listen_thread.join();
  11752. ASSERT_FALSE(svr.is_running());
  11753. });
  11754. svr.wait_until_ready();
  11755. Client cli("localhost", PORT);
  11756. cli.set_keep_alive(true);
  11757. using namespace std::chrono;
  11758. auto start = steady_clock::now();
  11759. cli.Get("/a");
  11760. svr.stop();
  11761. listen_thread.join();
  11762. auto end = steady_clock::now();
  11763. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11764. EXPECT_LT(elapsed, 5000);
  11765. }
  11766. #ifdef CPPHTTPLIB_SSL_ENABLED
  11767. TEST(KeepAliveTest, SSLClientReconnection) {
  11768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11769. ASSERT_TRUE(svr.is_valid());
  11770. svr.set_keep_alive_timeout(1);
  11771. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11772. res.set_content("Hello World!", "text/plain");
  11773. });
  11774. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11775. auto se = detail::scope_exit([&] {
  11776. svr.stop();
  11777. listen_thread.join();
  11778. ASSERT_FALSE(svr.is_running());
  11779. });
  11780. svr.wait_until_ready();
  11781. SSLClient cli(HOST, PORT);
  11782. cli.enable_server_certificate_verification(false);
  11783. cli.set_keep_alive(true);
  11784. auto result = cli.Get("/hi");
  11785. ASSERT_TRUE(result);
  11786. EXPECT_EQ(StatusCode::OK_200, result->status);
  11787. result = cli.Get("/hi");
  11788. ASSERT_TRUE(result);
  11789. EXPECT_EQ(StatusCode::OK_200, result->status);
  11790. std::this_thread::sleep_for(std::chrono::seconds(2));
  11791. // Recoonect
  11792. result = cli.Get("/hi");
  11793. ASSERT_TRUE(result);
  11794. EXPECT_EQ(StatusCode::OK_200, result->status);
  11795. result = cli.Get("/hi");
  11796. ASSERT_TRUE(result);
  11797. EXPECT_EQ(StatusCode::OK_200, result->status);
  11798. }
  11799. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11800. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11801. ASSERT_TRUE(svr.is_valid());
  11802. svr.set_keep_alive_timeout(1);
  11803. std::string content = "reconnect";
  11804. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11805. res.set_content("Hello World!", "text/plain");
  11806. });
  11807. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11808. auto se = detail::scope_exit([&] {
  11809. svr.stop();
  11810. listen_thread.join();
  11811. ASSERT_FALSE(svr.is_running());
  11812. });
  11813. svr.wait_until_ready();
  11814. SSLClient cli(HOST, PORT);
  11815. cli.enable_server_certificate_verification(false);
  11816. cli.set_keep_alive(true);
  11817. auto result = cli.Post(
  11818. "/hi", content.size(),
  11819. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11820. sink.write(content.c_str(), content.size());
  11821. return true;
  11822. },
  11823. "text/plain");
  11824. ASSERT_TRUE(result);
  11825. EXPECT_EQ(200, result->status);
  11826. std::this_thread::sleep_for(std::chrono::seconds(2));
  11827. // Recoonect
  11828. result = cli.Post(
  11829. "/hi", content.size(),
  11830. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11831. sink.write(content.c_str(), content.size());
  11832. return true;
  11833. },
  11834. "text/plain");
  11835. ASSERT_TRUE(result);
  11836. EXPECT_EQ(200, result->status);
  11837. result = cli.Post(
  11838. "/hi", content.size(),
  11839. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11840. sink.write(content.c_str(), content.size());
  11841. return true;
  11842. },
  11843. "text/plain");
  11844. ASSERT_TRUE(result);
  11845. EXPECT_EQ(200, result->status);
  11846. }
  11847. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11848. using namespace httplib::tls;
  11849. {
  11850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11851. ASSERT_TRUE(svr.is_valid());
  11852. svr.Get("/sni", [&](const Request &req, Response &res) {
  11853. std::string expected = req.sni();
  11854. EXPECT_EQ(expected, req.get_param_value("expected"));
  11855. res.set_content("ok", "text/plain");
  11856. });
  11857. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11858. auto se = detail::scope_exit([&] {
  11859. svr.stop();
  11860. listen_thread.join();
  11861. ASSERT_FALSE(svr.is_running());
  11862. });
  11863. svr.wait_until_ready();
  11864. {
  11865. SSLClient cli("localhost", PORT);
  11866. cli.enable_server_certificate_verification(false);
  11867. auto res = cli.Get("/sni?expected=localhost");
  11868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11869. }
  11870. {
  11871. SSLClient cli("::1", PORT);
  11872. cli.enable_server_certificate_verification(false);
  11873. auto res = cli.Get("/sni?expected=");
  11874. // NOTE: This may fail if the server is listening on IPv4 only
  11875. // (e.g., when localhost resolves to 127.0.0.1 only)
  11876. if (res) {
  11877. EXPECT_EQ(StatusCode::OK_200, res->status);
  11878. } else {
  11879. EXPECT_EQ(Error::Connection, res.error());
  11880. }
  11881. }
  11882. }
  11883. }
  11884. // The SNI of a failed handshake does not reach the next connection that the
  11885. // same worker thread serves
  11886. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11887. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11888. ASSERT_TRUE(svr.is_valid());
  11889. svr.new_task_queue = [] { return new ThreadPool(1); };
  11890. svr.Get("/sni", [](const Request &req, Response &res) {
  11891. res.set_content(req.sni(), "text/plain");
  11892. });
  11893. auto port = svr.bind_to_any_port("127.0.0.1");
  11894. ASSERT_LT(0, port);
  11895. thread t = thread([&] { svr.listen_after_bind(); });
  11896. auto se = detail::scope_exit([&] {
  11897. svr.stop();
  11898. t.join();
  11899. ASSERT_FALSE(svr.is_running());
  11900. });
  11901. svr.wait_until_ready();
  11902. {
  11903. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11904. SSLClient cli("localhost", port);
  11905. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11906. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11907. auto res = cli.Get("/sni");
  11908. ASSERT_FALSE(res);
  11909. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11910. }
  11911. // An IP host sends no SNI (RFC 6066)
  11912. SSLClient cli("127.0.0.1", port);
  11913. cli.enable_server_certificate_verification(false);
  11914. auto res = cli.Get("/sni");
  11915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11916. EXPECT_EQ("", res->body);
  11917. }
  11918. #endif
  11919. TEST(ClientProblemDetectionTest, ContentProvider) {
  11920. Server svr;
  11921. size_t content_length = 1024 * 1024;
  11922. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11923. res.set_content_provider(
  11924. content_length, "text/plain",
  11925. [&](size_t offset, size_t length, DataSink &sink) {
  11926. auto out_len = std::min(length, static_cast<size_t>(1024));
  11927. std::string out(out_len, '@');
  11928. sink.write(out.data(), out_len);
  11929. return offset < 4096;
  11930. },
  11931. [](bool success) { ASSERT_FALSE(success); });
  11932. });
  11933. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11934. res.set_content_provider(
  11935. 0, "text/plain",
  11936. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11937. EXPECT_TRUE(false);
  11938. return true;
  11939. },
  11940. [](bool success) { ASSERT_FALSE(success); });
  11941. });
  11942. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11943. auto se = detail::scope_exit([&] {
  11944. svr.stop();
  11945. listen_thread.join();
  11946. ASSERT_FALSE(svr.is_running());
  11947. });
  11948. svr.wait_until_ready();
  11949. Client cli("localhost", PORT);
  11950. {
  11951. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11952. size_t /*data_length*/) { return false; });
  11953. ASSERT_FALSE(res);
  11954. }
  11955. {
  11956. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11957. size_t /*data_length*/) { return false; });
  11958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11959. }
  11960. }
  11961. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11962. // A provider that reports success without writing anything and without
  11963. // calling done() used to be handed the same offset and length again on every
  11964. // pass, so it spun for as long as the peer stayed connected.
  11965. Server svr;
  11966. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11967. res.set_content("ok", "text/plain");
  11968. });
  11969. auto port = svr.bind_to_any_port(HOST);
  11970. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11971. auto se = detail::scope_exit([&] {
  11972. svr.stop();
  11973. listen_thread.join();
  11974. ASSERT_FALSE(svr.is_running());
  11975. });
  11976. svr.wait_until_ready();
  11977. std::atomic<int> call_count{0};
  11978. Client cli(HOST, port);
  11979. auto res = cli.Post(
  11980. "/", 1024,
  11981. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11982. // Give up after enough passes to show the spin, so that losing the
  11983. // check below fails this test instead of hanging it.
  11984. return ++call_count < 100;
  11985. },
  11986. "text/plain");
  11987. ASSERT_FALSE(res);
  11988. EXPECT_EQ(Error::Write, res.error());
  11989. EXPECT_EQ(1, call_count.load());
  11990. }
  11991. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11992. // A writer only has to assign `write`. The other three used to be left as
  11993. // empty std::functions, so a provider calling one threw
  11994. // std::bad_function_call out of the thread running it and took the whole
  11995. // process down.
  11996. DataSink sink;
  11997. std::string written;
  11998. sink.write = [&](const char *data, size_t data_len) {
  11999. written.append(data, data_len);
  12000. return true;
  12001. };
  12002. EXPECT_TRUE(sink.is_writable());
  12003. sink.done();
  12004. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12005. EXPECT_TRUE(written.empty());
  12006. }
  12007. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12008. // A sink that cannot carry trailers still has to finish.
  12009. DataSink sink;
  12010. auto done_count = 0;
  12011. sink.done = [&]() { done_count++; };
  12012. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12013. EXPECT_EQ(1, done_count);
  12014. }
  12015. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12016. Server svr;
  12017. const std::string body(4096, 'x');
  12018. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12019. res.set_content_provider(body.size(), "text/plain",
  12020. [&](size_t offset, size_t length, DataSink &sink) {
  12021. sink.write(body.data() + offset, length);
  12022. sink.done();
  12023. return true;
  12024. });
  12025. });
  12026. auto port = svr.bind_to_any_port(HOST);
  12027. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12028. auto se = detail::scope_exit([&] {
  12029. svr.stop();
  12030. listen_thread.join();
  12031. ASSERT_FALSE(svr.is_running());
  12032. });
  12033. svr.wait_until_ready();
  12034. Client cli(HOST, port);
  12035. auto res = cli.Get("/");
  12036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12037. EXPECT_EQ(StatusCode::OK_200, res->status);
  12038. EXPECT_EQ(body, res->body);
  12039. }
  12040. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12041. Server svr;
  12042. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12043. res.set_content_provider(
  12044. 1024, "text/plain",
  12045. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12046. sink.write("hello", 5);
  12047. sink.done(); // short of the 1024 bytes the response promised
  12048. return true;
  12049. });
  12050. });
  12051. auto port = svr.bind_to_any_port(HOST);
  12052. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12053. auto se = detail::scope_exit([&] {
  12054. svr.stop();
  12055. listen_thread.join();
  12056. ASSERT_FALSE(svr.is_running());
  12057. });
  12058. svr.wait_until_ready();
  12059. Client cli(HOST, port);
  12060. cli.set_read_timeout(5, 0);
  12061. // The response is short of its Content-Length, so the client cannot read a
  12062. // complete body. What matters is that this returns at all: a no-op done()
  12063. // would leave the writer looping over a provider that never makes progress.
  12064. auto res = cli.Get("/");
  12065. EXPECT_FALSE(res);
  12066. }
  12067. // Read as the next response by a peer that sees it after a framed body.
  12068. static const std::string smuggled_response =
  12069. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12070. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12071. Server svr;
  12072. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12073. res.set_content_provider(
  12074. 5, "text/plain",
  12075. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12076. auto data = "AAAAA" + smuggled_response;
  12077. sink.write(data.data(), data.size());
  12078. return true;
  12079. });
  12080. });
  12081. thread t = thread([&] { svr.listen(HOST, PORT); });
  12082. auto se = detail::scope_exit([&] {
  12083. svr.stop();
  12084. t.join();
  12085. ASSERT_FALSE(svr.is_running());
  12086. });
  12087. svr.wait_until_ready();
  12088. std::string resp;
  12089. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12090. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12091. resp.clear();
  12092. ASSERT_TRUE(send_request(
  12093. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12094. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12095. }
  12096. TEST(NoContentTest, BodyIsNotSent) {
  12097. Server svr;
  12098. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12099. res.status = StatusCode::NoContent_204;
  12100. res.set_content(smuggled_response, "text/plain");
  12101. });
  12102. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12103. res.status = StatusCode::NotModified_304;
  12104. res.set_chunked_content_provider(
  12105. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12106. sink.write(smuggled_response.data(), smuggled_response.size());
  12107. sink.done();
  12108. return true;
  12109. });
  12110. });
  12111. thread t = thread([&] { svr.listen(HOST, PORT); });
  12112. auto se = detail::scope_exit([&] {
  12113. svr.stop();
  12114. t.join();
  12115. ASSERT_FALSE(svr.is_running());
  12116. });
  12117. svr.wait_until_ready();
  12118. for (auto path : {"/204", "/304"}) {
  12119. std::string resp;
  12120. ASSERT_TRUE(send_request(
  12121. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12122. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12123. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12124. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12125. }
  12126. }
  12127. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12128. Server svr;
  12129. std::atomic<bool> smuggled(false);
  12130. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12131. res.set_content("ok", "text/plain");
  12132. });
  12133. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12134. smuggled = true;
  12135. });
  12136. auto port = svr.bind_to_any_port(HOST);
  12137. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12138. auto se = detail::scope_exit([&] {
  12139. svr.stop();
  12140. listen_thread.join();
  12141. ASSERT_FALSE(svr.is_running());
  12142. });
  12143. svr.wait_until_ready();
  12144. // What follows the body would be read as the next request.
  12145. Client cli(HOST, port);
  12146. auto res = cli.Post(
  12147. "/", 5,
  12148. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12149. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12150. sink.write(data.data(), data.size());
  12151. return true;
  12152. },
  12153. "text/plain");
  12154. ASSERT_FALSE(res);
  12155. EXPECT_EQ(Error::Write, res.error());
  12156. EXPECT_FALSE(smuggled);
  12157. }
  12158. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12159. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12160. // The compressed path builds the whole body before connecting, so this
  12161. // fails client-side and never reaches a server.
  12162. Client cli(HOST, PORT);
  12163. cli.set_compress(true);
  12164. auto res = cli.Post(
  12165. "/", 1024,
  12166. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12167. sink.write("hello", 5);
  12168. sink.done(); // short of the 1024 bytes the request announced
  12169. return true;
  12170. },
  12171. "text/plain");
  12172. ASSERT_FALSE(res);
  12173. EXPECT_EQ(Error::Write, res.error());
  12174. }
  12175. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12176. Server svr;
  12177. std::string received;
  12178. size_t content_length_count = 0;
  12179. bool has_transfer_encoding = true;
  12180. svr.Post("/echo", [&](const Request &req, Response &res) {
  12181. received = req.body;
  12182. content_length_count = req.get_header_value_count("Content-Length");
  12183. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12184. res.set_content("ok", "text/plain");
  12185. });
  12186. svr.Get("/next", [](const Request &, Response &res) {
  12187. res.set_content("next", "text/plain");
  12188. });
  12189. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12190. auto se = detail::scope_exit([&] {
  12191. svr.stop();
  12192. listen_thread.join();
  12193. ASSERT_FALSE(svr.is_running());
  12194. });
  12195. svr.wait_until_ready();
  12196. Client cli(HOST, PORT);
  12197. cli.set_keep_alive(true);
  12198. cli.set_compress(true);
  12199. const std::string body = "hello world";
  12200. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12201. auto res = cli.Post("/echo", headers, body, "text/plain");
  12202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12203. EXPECT_EQ(StatusCode::OK_200, res->status);
  12204. EXPECT_EQ(body, received);
  12205. EXPECT_EQ(1u, content_length_count);
  12206. EXPECT_FALSE(has_transfer_encoding);
  12207. // The rest of a truncated body would be read as this request
  12208. auto res2 = cli.Get("/next");
  12209. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12210. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12211. EXPECT_EQ("next", res2->body);
  12212. }
  12213. #endif
  12214. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12215. Server svr;
  12216. std::string received;
  12217. size_t content_length_count = 1;
  12218. bool has_transfer_encoding = false;
  12219. svr.Post("/echo", [&](const Request &req, Response &res) {
  12220. received = req.body;
  12221. content_length_count = req.get_header_value_count("Content-Length");
  12222. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12223. res.set_content("ok", "text/plain");
  12224. });
  12225. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12226. auto se = detail::scope_exit([&] {
  12227. svr.stop();
  12228. listen_thread.join();
  12229. ASSERT_FALSE(svr.is_running());
  12230. });
  12231. svr.wait_until_ready();
  12232. Client cli(HOST, PORT);
  12233. cli.set_keep_alive(true);
  12234. const std::string body = "hello world";
  12235. Headers headers = {{"Content-Length", "5"}};
  12236. auto res = cli.Post(
  12237. "/echo", headers,
  12238. [&](size_t /*offset*/, DataSink &sink) {
  12239. sink.write(body.data(), body.size());
  12240. sink.done();
  12241. return true;
  12242. },
  12243. "text/plain");
  12244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12245. EXPECT_EQ(StatusCode::OK_200, res->status);
  12246. EXPECT_EQ(body, received);
  12247. EXPECT_EQ(0u, content_length_count);
  12248. EXPECT_TRUE(has_transfer_encoding);
  12249. }
  12250. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12251. Server svr;
  12252. svr.set_error_handler([](Request const &, Response &res) -> void {
  12253. res.set_chunked_content_provider(
  12254. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12255. sink.os << "hello";
  12256. sink.os << "world";
  12257. sink.done();
  12258. return true;
  12259. });
  12260. });
  12261. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12262. auto se = detail::scope_exit([&] {
  12263. svr.stop();
  12264. listen_thread.join();
  12265. ASSERT_FALSE(svr.is_running());
  12266. });
  12267. svr.wait_until_ready();
  12268. Client cli("localhost", PORT);
  12269. auto res = cli.Get("/");
  12270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12271. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12272. EXPECT_EQ("helloworld", res->body);
  12273. }
  12274. // A body set after a content provider must replace it, not be sent through it.
  12275. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12276. Server svr;
  12277. svr.set_mount_point("/", "./www");
  12278. svr.set_file_request_handler([](const Request &req, Response &res) {
  12279. if (req.path == "/dir/test.html") {
  12280. res.status = StatusCode::Forbidden_403;
  12281. res.set_content(std::string(5000, 'D'), "text/plain");
  12282. } else if (req.path == "/file") {
  12283. res.status = StatusCode::Forbidden_403;
  12284. res.body = "Denied";
  12285. }
  12286. });
  12287. auto port = svr.bind_to_any_port(HOST);
  12288. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12289. auto se = detail::scope_exit([&] {
  12290. svr.stop();
  12291. t.join();
  12292. ASSERT_FALSE(svr.is_running());
  12293. });
  12294. svr.wait_until_ready();
  12295. Client cli(HOST, port);
  12296. {
  12297. auto res = cli.Get("/dir/test.html");
  12298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12299. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12300. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12301. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12302. }
  12303. {
  12304. auto res = cli.Get("/file");
  12305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12306. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12307. EXPECT_EQ("Denied", res->body);
  12308. }
  12309. {
  12310. auto res = cli.Get("/dir/index.html");
  12311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12312. EXPECT_EQ(StatusCode::OK_200, res->status);
  12313. EXPECT_EQ(0U, res->body.find("<html>"));
  12314. }
  12315. }
  12316. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12317. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12318. Server svr;
  12319. std::vector<bool> released;
  12320. std::mutex released_mutex;
  12321. auto releaser = [&](bool success) {
  12322. std::lock_guard<std::mutex> guard(released_mutex);
  12323. released.push_back(success);
  12324. };
  12325. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12326. return sink.write(&"hello"[offset], length);
  12327. };
  12328. svr.Get("/sized", [&](const Request &, Response &res) {
  12329. res.status = StatusCode::NotFound_404;
  12330. res.set_content_provider(5, "text/plain", provider, releaser);
  12331. });
  12332. svr.Get("/chunked", [&](const Request &, Response &res) {
  12333. res.status = StatusCode::ServiceUnavailable_503;
  12334. res.set_chunked_content_provider(
  12335. "text/plain",
  12336. [](size_t, DataSink &sink) {
  12337. sink.os << "chunk";
  12338. sink.done();
  12339. return true;
  12340. },
  12341. releaser);
  12342. });
  12343. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12344. res.set_content_provider(5, "text/plain", provider, releaser);
  12345. throw std::runtime_error("after the provider");
  12346. });
  12347. svr.set_error_handler([](const Request &req, Response &res) {
  12348. // Leave the exception handler's content to it.
  12349. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12350. res.set_content(std::string(1000, 'E'), "text/html");
  12351. return Server::HandlerResponse::Handled;
  12352. });
  12353. svr.set_exception_handler(
  12354. [](const Request &, Response &res, std::exception_ptr) {
  12355. res.status = StatusCode::InternalServerError_500;
  12356. res.set_content(std::string(1000, 'X'), "text/html");
  12357. });
  12358. auto port = svr.bind_to_any_port(HOST);
  12359. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12360. auto se = detail::scope_exit([&] {
  12361. svr.stop();
  12362. t.join();
  12363. ASSERT_FALSE(svr.is_running());
  12364. });
  12365. svr.wait_until_ready();
  12366. Client cli(HOST, port);
  12367. {
  12368. auto res = cli.Get("/sized");
  12369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12371. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12372. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12373. }
  12374. {
  12375. auto res = cli.Get("/chunked");
  12376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12377. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12378. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12379. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12380. }
  12381. {
  12382. auto res = cli.Get("/throw");
  12383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12384. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12385. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12386. }
  12387. std::lock_guard<std::mutex> guard(released_mutex);
  12388. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12389. }
  12390. #endif
  12391. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12392. Server svr;
  12393. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12394. return sink.write(&"abc"[offset], length);
  12395. };
  12396. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12397. res.set_file_content("./www/dir/test.html");
  12398. res.set_content("body", "text/plain");
  12399. });
  12400. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12401. res.set_content(std::string(100, 'B'), "text/plain");
  12402. res.set_file_content("./www/dir/test.html");
  12403. });
  12404. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12405. res.set_content(std::string(100, 'B'), "text/plain");
  12406. res.set_content_provider(3, "text/x-provider", abc);
  12407. });
  12408. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12409. res.set_content_provider(3, "text/x-provider", abc);
  12410. res.set_content(std::string(100, 'B'), "text/plain");
  12411. });
  12412. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12413. res.set_content_provider(3, "text/x-provider", abc);
  12414. res.set_file_content("./www/dir/test.html", "text/x-file");
  12415. });
  12416. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12417. res.set_file_content("./www/dir/test.html");
  12418. res.set_header("Content-Type", "text/x-handler");
  12419. });
  12420. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12421. res.set_content_provider(3, "text/plain", abc);
  12422. res.body = "direct";
  12423. });
  12424. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12425. res.set_file_content("./www/dir/test.html");
  12426. res.body = "direct";
  12427. });
  12428. auto port = svr.bind_to_any_port(HOST);
  12429. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12430. auto se = detail::scope_exit([&] {
  12431. svr.stop();
  12432. t.join();
  12433. ASSERT_FALSE(svr.is_running());
  12434. });
  12435. svr.wait_until_ready();
  12436. Client cli(HOST, port);
  12437. auto expect_body = [&](const char *path, const std::string &body,
  12438. const std::string &type) {
  12439. // Uncompressed, so Content-Length can be compared with the body.
  12440. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12441. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12442. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12443. EXPECT_EQ(body, res->body) << path;
  12444. EXPECT_EQ(std::to_string(body.size()),
  12445. res->get_header_value("Content-Length"))
  12446. << path;
  12447. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12448. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12449. };
  12450. expect_body("/file-then-body", "body", "text/plain");
  12451. expect_body("/body-then-file", "test.html", "text/html");
  12452. expect_body("/body-then-provider", "abc", "text/x-provider");
  12453. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12454. expect_body("/provider-then-file", "test.html", "text/x-file");
  12455. expect_body("/file-then-header", "test.html", "text/x-handler");
  12456. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12457. expect_body("/file-then-direct-body", "direct", "text/plain");
  12458. // Ranges are checked against the body, not the dropped provider.
  12459. {
  12460. auto res = cli.Get("/provider-then-direct-body",
  12461. Headers{{make_range_header({{1, 2}})}});
  12462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12463. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12464. EXPECT_EQ("ir", res->body);
  12465. }
  12466. {
  12467. auto res = cli.Get("/file-then-direct-body",
  12468. Headers{{make_range_header({{7, 8}})}});
  12469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12470. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12471. }
  12472. }
  12473. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12474. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12475. const char *path = "./truncated_while_served.txt";
  12476. const size_t size = 32 * 1024 * 1024;
  12477. {
  12478. std::ofstream f(path, std::ios::binary);
  12479. f << std::string(size, 'x');
  12480. }
  12481. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12482. // Over TLS, where the bytes are encrypted in this process rather than
  12483. // copied by send().
  12484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12485. svr.Get("/file", [&](const Request &, Response &res) {
  12486. res.set_file_content(path, "text/plain");
  12487. });
  12488. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12489. auto se = detail::scope_exit([&] {
  12490. svr.stop();
  12491. thread.join();
  12492. ASSERT_FALSE(svr.is_running());
  12493. });
  12494. svr.wait_until_ready();
  12495. // The file shrinks once the first bytes are in, as a rewrite in place
  12496. // would, and reading the mapping past its new end used to raise SIGBUS.
  12497. SSLClient cli(HOST, PORT);
  12498. cli.enable_server_certificate_verification(false);
  12499. size_t received = 0;
  12500. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12501. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12502. received += len;
  12503. return true;
  12504. });
  12505. EXPECT_FALSE(res);
  12506. EXPECT_LT(received, size);
  12507. }
  12508. #endif
  12509. // Forward declaration (see the base64_encode note).
  12510. namespace httplib {
  12511. namespace detail {
  12512. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12513. const std::string &content_type,
  12514. EncodingType encoding);
  12515. } // namespace detail
  12516. } // namespace httplib
  12517. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12518. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12519. ASSERT_TRUE(mm->is_open());
  12520. Response res;
  12521. detail::set_file_content_provider(res, mm, "text/html",
  12522. detail::EncodingType::None);
  12523. std::string out;
  12524. DataSink sink;
  12525. sink.write = [&](const char *d, size_t l) {
  12526. out.append(d, l);
  12527. return true;
  12528. };
  12529. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12530. EXPECT_EQ("test.html", out);
  12531. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12532. EXPECT_EQ("test.html", out);
  12533. }
  12534. TEST(LongPollingTest, ClientCloseDetection) {
  12535. Server svr;
  12536. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12537. res.set_chunked_content_provider(
  12538. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12539. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12540. sink.os << "hello";
  12541. auto count = 10;
  12542. while (count > 0 && sink.is_writable()) {
  12543. this_thread::sleep_for(chrono::milliseconds(10));
  12544. count--;
  12545. }
  12546. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12547. return true;
  12548. });
  12549. });
  12550. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12551. auto se = detail::scope_exit([&] {
  12552. svr.stop();
  12553. listen_thread.join();
  12554. ASSERT_FALSE(svr.is_running());
  12555. });
  12556. svr.wait_until_ready();
  12557. Client cli("localhost", PORT);
  12558. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12559. EXPECT_EQ("hello", string(data, data_length));
  12560. return false; // close the socket immediately.
  12561. });
  12562. ASSERT_FALSE(res);
  12563. }
  12564. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12565. Server svr;
  12566. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12567. res.set_chunked_content_provider(
  12568. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12569. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12570. sink.os << "hello";
  12571. EXPECT_TRUE(sink.os.good());
  12572. // Wait for the client to close the connection
  12573. auto count = 10;
  12574. while (count > 0 && sink.is_writable()) {
  12575. this_thread::sleep_for(chrono::milliseconds(10));
  12576. count--;
  12577. }
  12578. // After client disconnect, write repeatedly until the socket
  12579. // write actually fails (small writes may be absorbed by the
  12580. // kernel buffer)
  12581. std::string chunk(1024, 'x');
  12582. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12583. sink.os << chunk;
  12584. }
  12585. EXPECT_TRUE(sink.os.fail());
  12586. return true;
  12587. });
  12588. });
  12589. auto port = svr.bind_to_any_port("localhost");
  12590. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12591. auto se = detail::scope_exit([&] {
  12592. svr.stop();
  12593. listen_thread.join();
  12594. ASSERT_FALSE(svr.is_running());
  12595. });
  12596. svr.wait_until_ready();
  12597. Client cli("localhost", port);
  12598. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12599. EXPECT_EQ("hello", string(data, data_length));
  12600. return false; // close the socket immediately.
  12601. });
  12602. ASSERT_FALSE(res);
  12603. }
  12604. TEST(GetWithParametersTest, GetWithParameters) {
  12605. Server svr;
  12606. svr.Get("/", [&](const Request &req, Response &) {
  12607. EXPECT_EQ("world", req.get_param_value("hello"));
  12608. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12609. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12610. });
  12611. svr.Get("/params", [&](const Request &req, Response &) {
  12612. EXPECT_EQ("world", req.get_param_value("hello"));
  12613. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12614. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12615. });
  12616. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12617. EXPECT_EQ("resource-id", req.matches[1]);
  12618. EXPECT_EQ("foo", req.get_param_value("param1"));
  12619. EXPECT_EQ("bar", req.get_param_value("param2"));
  12620. });
  12621. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12622. EXPECT_EQ("user-id", req.path_params.at("id"));
  12623. EXPECT_EQ("foo", req.get_param_value("param1"));
  12624. EXPECT_EQ("bar", req.get_param_value("param2"));
  12625. });
  12626. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12627. auto se = detail::scope_exit([&] {
  12628. svr.stop();
  12629. listen_thread.join();
  12630. ASSERT_FALSE(svr.is_running());
  12631. });
  12632. svr.wait_until_ready();
  12633. {
  12634. Client cli(HOST, PORT);
  12635. Params params;
  12636. params.emplace("hello", "world");
  12637. params.emplace("hello2", "world2");
  12638. params.emplace("hello3", "world3");
  12639. auto res = cli.Get("/", params, Headers{});
  12640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12641. EXPECT_EQ(StatusCode::OK_200, res->status);
  12642. }
  12643. {
  12644. Client cli(HOST, PORT);
  12645. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12647. EXPECT_EQ(StatusCode::OK_200, res->status);
  12648. }
  12649. {
  12650. Client cli(HOST, PORT);
  12651. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  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("/users/user-id?param1=foo&param2=bar");
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. EXPECT_EQ(StatusCode::OK_200, res->status);
  12660. }
  12661. }
  12662. TEST(GetWithParametersTest, GetWithParameters2) {
  12663. Server svr;
  12664. svr.Get("/", [&](const Request &req, Response &res) {
  12665. auto text = req.get_param_value("hello");
  12666. res.set_content(text, "text/plain");
  12667. });
  12668. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12669. auto se = detail::scope_exit([&] {
  12670. svr.stop();
  12671. listen_thread.join();
  12672. ASSERT_FALSE(svr.is_running());
  12673. });
  12674. svr.wait_until_ready();
  12675. Client cli("localhost", PORT);
  12676. Params params;
  12677. params.emplace("hello", "world");
  12678. std::string body;
  12679. auto res = cli.Get("/", params, Headers{},
  12680. [&](const char *data, size_t data_length) {
  12681. body.append(data, data_length);
  12682. return true;
  12683. });
  12684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12685. EXPECT_EQ(StatusCode::OK_200, res->status);
  12686. EXPECT_EQ("world", body);
  12687. }
  12688. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12689. Server svr;
  12690. svr.Get("/search", [&](const Request &req, Response &res) {
  12691. auto q = req.get_param_value("q");
  12692. res.set_content(q, "text/plain");
  12693. });
  12694. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12695. auto se = detail::scope_exit([&] {
  12696. svr.stop();
  12697. listen_thread.join();
  12698. ASSERT_FALSE(svr.is_running());
  12699. });
  12700. svr.wait_until_ready();
  12701. Client cli("localhost", PORT);
  12702. // Verify that Get(path, params) works without requiring Headers argument
  12703. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12705. EXPECT_EQ(StatusCode::OK_200, res->status);
  12706. EXPECT_EQ("cpp-httplib", res->body);
  12707. }
  12708. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12709. auto host = "httpbingo.org";
  12710. auto path = std::string{"/range/32"};
  12711. #ifdef CPPHTTPLIB_SSL_ENABLED
  12712. SSLClient cli(host);
  12713. #else
  12714. Client cli(host);
  12715. #endif
  12716. cli.set_default_headers({make_range_header({{1, 10}})});
  12717. cli.set_connection_timeout(5);
  12718. {
  12719. auto res = cli.Get(path);
  12720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12721. EXPECT_EQ("bcdefghijk", res->body);
  12722. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12723. }
  12724. {
  12725. auto res = cli.Get(path);
  12726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12727. EXPECT_EQ("bcdefghijk", res->body);
  12728. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12729. }
  12730. }
  12731. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12732. Server svr;
  12733. svr.set_default_headers({{"Hello", "World"}});
  12734. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12735. res.set_content("ok", "text/plain");
  12736. });
  12737. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12738. auto se = detail::scope_exit([&] {
  12739. svr.stop();
  12740. listen_thread.join();
  12741. ASSERT_FALSE(svr.is_running());
  12742. });
  12743. svr.wait_until_ready();
  12744. Client cli("localhost", PORT);
  12745. auto res = cli.Get("/");
  12746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12747. EXPECT_EQ(StatusCode::OK_200, res->status);
  12748. EXPECT_EQ("ok", res->body);
  12749. EXPECT_EQ("World", res->get_header_value("Hello"));
  12750. }
  12751. #ifdef CPPHTTPLIB_SSL_ENABLED
  12752. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12753. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12754. ASSERT_TRUE(svr.is_valid());
  12755. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12756. std::this_thread::sleep_for(std::chrono::seconds(2));
  12757. res.set_content("a", "text/plain");
  12758. });
  12759. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12760. res.set_content("b", "text/plain");
  12761. });
  12762. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12763. auto se = detail::scope_exit([&] {
  12764. svr.stop();
  12765. listen_thread.join();
  12766. ASSERT_FALSE(svr.is_running());
  12767. });
  12768. svr.wait_until_ready();
  12769. SSLClient cli("localhost", PORT);
  12770. cli.enable_server_certificate_verification(false);
  12771. cli.set_keep_alive(true);
  12772. cli.set_read_timeout(std::chrono::seconds(1));
  12773. auto resa = cli.Get("/a");
  12774. ASSERT_TRUE(!resa);
  12775. EXPECT_EQ(Error::Read, resa.error());
  12776. auto resb = cli.Get("/b");
  12777. ASSERT_TRUE(resb);
  12778. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12779. EXPECT_EQ("b", resb->body);
  12780. }
  12781. // Closing an idle keep-alive connection sends close_notify and returns. The
  12782. // server must not wait for the client's close_notify: an idle client never
  12783. // sends one, so the worker would be held until the read timeout expires, and
  12784. // stop() would wait for it.
  12785. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12786. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12787. ASSERT_TRUE(svr.is_valid());
  12788. svr.set_keep_alive_timeout(1);
  12789. svr.set_read_timeout(10, 0);
  12790. svr.Get("/", [](const Request &, Response &res) {
  12791. res.set_content("ok", "text/plain");
  12792. });
  12793. auto port = svr.bind_to_any_port(HOST);
  12794. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12795. auto se = detail::scope_exit([&] {
  12796. if (listen_thread.joinable()) {
  12797. svr.stop();
  12798. listen_thread.join();
  12799. }
  12800. });
  12801. svr.wait_until_ready();
  12802. SSLClient cli(HOST, port);
  12803. cli.enable_server_certificate_verification(false);
  12804. cli.set_keep_alive(true);
  12805. auto res = cli.Get("/");
  12806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12807. EXPECT_EQ(StatusCode::OK_200, res->status);
  12808. // Stay idle past the keep-alive timeout so the server closes the connection.
  12809. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12810. auto start = std::chrono::steady_clock::now();
  12811. svr.stop();
  12812. listen_thread.join();
  12813. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12814. std::chrono::steady_clock::now() - start)
  12815. .count();
  12816. EXPECT_LT(elapsed, 3000);
  12817. }
  12818. #endif
  12819. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12820. protected:
  12821. ServerTestWithAI_PASSIVE()
  12822. : cli_(HOST, PORT)
  12823. #ifdef CPPHTTPLIB_SSL_ENABLED
  12824. ,
  12825. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12826. #endif
  12827. {
  12828. #ifdef CPPHTTPLIB_SSL_ENABLED
  12829. cli_.enable_server_certificate_verification(false);
  12830. #endif
  12831. }
  12832. virtual void SetUp() {
  12833. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12834. res.set_content("Hello World!", "text/plain");
  12835. });
  12836. t_ = thread(
  12837. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12838. svr_.wait_until_ready();
  12839. }
  12840. virtual void TearDown() {
  12841. svr_.stop();
  12842. t_.join();
  12843. }
  12844. #ifdef CPPHTTPLIB_SSL_ENABLED
  12845. SSLClient cli_;
  12846. SSLServer svr_;
  12847. #else
  12848. Client cli_;
  12849. Server svr_;
  12850. #endif
  12851. thread t_;
  12852. };
  12853. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12854. auto res = cli_.Get("/hi");
  12855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12856. EXPECT_EQ(StatusCode::OK_200, res->status);
  12857. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12858. EXPECT_EQ("Hello World!", res->body);
  12859. }
  12860. class ServerUpDownTest : public ::testing::Test {
  12861. protected:
  12862. ServerUpDownTest() : cli_(HOST, PORT) {}
  12863. virtual void SetUp() {
  12864. t_ = thread([&]() {
  12865. svr_.bind_to_any_port(HOST);
  12866. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12867. ASSERT_TRUE(svr_.listen_after_bind());
  12868. });
  12869. svr_.wait_until_ready();
  12870. }
  12871. virtual void TearDown() {
  12872. svr_.stop();
  12873. t_.join();
  12874. }
  12875. Client cli_;
  12876. Server svr_;
  12877. thread t_;
  12878. };
  12879. TEST_F(ServerUpDownTest, QuickStartStop) {
  12880. // Should not crash, especially when run with
  12881. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12882. }
  12883. class PayloadMaxLengthTest : public ::testing::Test {
  12884. protected:
  12885. PayloadMaxLengthTest()
  12886. : cli_(HOST, PORT)
  12887. #ifdef CPPHTTPLIB_SSL_ENABLED
  12888. ,
  12889. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12890. #endif
  12891. {
  12892. #ifdef CPPHTTPLIB_SSL_ENABLED
  12893. cli_.enable_server_certificate_verification(false);
  12894. #endif
  12895. }
  12896. virtual void SetUp() {
  12897. svr_.set_payload_max_length(8);
  12898. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12899. res.set_content("test", "text/plain");
  12900. });
  12901. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12902. svr_.wait_until_ready();
  12903. }
  12904. virtual void TearDown() {
  12905. svr_.stop();
  12906. t_.join();
  12907. }
  12908. #ifdef CPPHTTPLIB_SSL_ENABLED
  12909. SSLClient cli_;
  12910. SSLServer svr_;
  12911. #else
  12912. Client cli_;
  12913. Server svr_;
  12914. #endif
  12915. thread t_;
  12916. };
  12917. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12918. auto res = cli_.Post("/test", "123456789", "text/plain");
  12919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12920. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12921. res = cli_.Post("/test", "12345678", "text/plain");
  12922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12923. EXPECT_EQ(StatusCode::OK_200, res->status);
  12924. }
  12925. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12926. // Test chunked encoding with payload exceeding the 8-byte limit
  12927. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12928. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12930. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12931. }
  12932. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12933. // Test chunked encoding with payload within the 8-byte limit
  12934. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12935. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12937. EXPECT_EQ(StatusCode::OK_200, res->status);
  12938. }
  12939. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12940. // Test using send_request to send chunked data exceeding payload limit
  12941. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12942. "Host: " +
  12943. std::string(HOST) + ":" + std::to_string(PORT) +
  12944. "\r\n"
  12945. "Transfer-Encoding: chunked\r\n"
  12946. "Connection: close\r\n"
  12947. "\r\n"
  12948. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12949. "0123456789\r\n"
  12950. "0\r\n" // End chunk
  12951. "\r\n";
  12952. std::string response;
  12953. bool result = send_request(1, chunked_request, &response);
  12954. if (!result) {
  12955. // If send_request fails, it might be because the server closed the
  12956. // connection due to payload limit enforcement, which is acceptable
  12957. SUCCEED()
  12958. << "Server rejected oversized chunked request (connection closed)";
  12959. } else {
  12960. // If we got a response, check if it's an error response or connection was
  12961. // closed early Short response length indicates connection was closed due to
  12962. // payload limit
  12963. if (response.length() <= 10) {
  12964. SUCCEED() << "Server closed connection for oversized chunked request";
  12965. } else {
  12966. // Check for error status codes
  12967. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12968. response.find("Payload Too Large") != std::string::npos ||
  12969. response.find("400") != std::string::npos);
  12970. }
  12971. }
  12972. }
  12973. class LargePayloadMaxLengthTest : public ::testing::Test {
  12974. protected:
  12975. LargePayloadMaxLengthTest()
  12976. : cli_(HOST, PORT)
  12977. #ifdef CPPHTTPLIB_SSL_ENABLED
  12978. ,
  12979. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12980. #endif
  12981. {
  12982. #ifdef CPPHTTPLIB_SSL_ENABLED
  12983. cli_.enable_server_certificate_verification(false);
  12984. #endif
  12985. }
  12986. virtual void SetUp() {
  12987. // Set 10MB payload limit
  12988. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12989. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12990. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12991. res.set_content("Large payload test", "text/plain");
  12992. });
  12993. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12994. svr_.wait_until_ready();
  12995. }
  12996. virtual void TearDown() {
  12997. svr_.stop();
  12998. t_.join();
  12999. }
  13000. #ifdef CPPHTTPLIB_SSL_ENABLED
  13001. SSLClient cli_;
  13002. SSLServer svr_;
  13003. #else
  13004. Client cli_;
  13005. Server svr_;
  13006. #endif
  13007. thread t_;
  13008. };
  13009. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13010. // Test chunked encoding with payload within 10MB limit
  13011. std::string medium_payload(5 * 1024 * 1024,
  13012. 'A'); // 5MB payload, within 10MB limit
  13013. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13015. EXPECT_EQ(StatusCode::OK_200, res->status);
  13016. }
  13017. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13018. // Test chunked encoding with payload exceeding 10MB limit
  13019. std::string large_payload(12 * 1024 * 1024,
  13020. 'B'); // 12MB payload, exceeds 10MB limit
  13021. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13022. // Server may either return 413 or close the connection
  13023. if (res) {
  13024. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13025. } else {
  13026. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13027. }
  13028. }
  13029. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13030. Server svr;
  13031. svr.Get("/", [](const Request &, Response &res) {
  13032. // Claims the most the client accepts, far more than it sends, then drops
  13033. // the connection.
  13034. res.set_content_provider(std::string().max_size(), "text/plain",
  13035. [](size_t, size_t, DataSink &sink) {
  13036. sink.write("abc", 3);
  13037. return false;
  13038. });
  13039. });
  13040. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13041. auto se = detail::scope_exit([&] {
  13042. svr.stop();
  13043. thread.join();
  13044. ASSERT_FALSE(svr.is_running());
  13045. });
  13046. svr.wait_until_ready();
  13047. Client cli(HOST, PORT);
  13048. cli.set_payload_max_length(0);
  13049. EXPECT_FALSE(cli.Get("/"));
  13050. }
  13051. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13052. // Stream API does, not as a plain read failure
  13053. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13054. Server svr;
  13055. svr.Get("/big", [](const Request &, Response &res) {
  13056. res.set_content(std::string(100000, 'b'), "text/plain");
  13057. });
  13058. auto port = svr.bind_to_any_port(HOST);
  13059. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13060. auto se = detail::scope_exit([&] {
  13061. svr.stop();
  13062. thread.join();
  13063. });
  13064. svr.wait_until_ready();
  13065. Client cli(HOST, port);
  13066. cli.set_payload_max_length(1000);
  13067. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13068. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13069. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13070. [](const char *, size_t) { return true; });
  13071. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13072. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13073. // Small on the wire, over the limit once decompressed
  13074. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13075. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13076. #endif
  13077. }
  13078. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13079. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13080. // path.
  13081. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13082. Server svr;
  13083. const size_t LIMIT = 64 * 1024; // 64KB
  13084. svr.set_payload_max_length(LIMIT);
  13085. size_t total = 0;
  13086. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13087. const ContentReader &content_reader) {
  13088. content_reader([&](const char * /*data*/, size_t len) {
  13089. total += len;
  13090. return true;
  13091. });
  13092. res.status = 200;
  13093. res.set_content("stream_ok", "text/plain");
  13094. });
  13095. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13096. auto se = detail::scope_exit([&] {
  13097. svr.stop();
  13098. thread.join();
  13099. ASSERT_FALSE(svr.is_running());
  13100. });
  13101. svr.wait_until_ready();
  13102. // Prepare 256KB raw data and gzip-compress it
  13103. std::string raw(256 * 1024, 'A');
  13104. std::string gz;
  13105. {
  13106. z_stream zs{};
  13107. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13108. Z_DEFAULT_STRATEGY);
  13109. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13110. zs.avail_in = static_cast<uInt>(raw.size());
  13111. char outbuf[4096];
  13112. int ret;
  13113. do {
  13114. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13115. zs.avail_out = sizeof(outbuf);
  13116. ret = deflate(&zs, Z_FINISH);
  13117. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13118. } while (ret != Z_STREAM_END);
  13119. deflateEnd(&zs);
  13120. }
  13121. Client cli(HOST, PORT);
  13122. cli.set_connection_timeout(std::chrono::seconds(5));
  13123. Headers headers = {{"Content-Encoding", "gzip"}};
  13124. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13125. "application/octet-stream");
  13126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13127. // Server must reject oversized decompressed payloads with 413.
  13128. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13129. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13130. EXPECT_LE(total, LIMIT);
  13131. }
  13132. #endif
  13133. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13134. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13135. // the payload must be passed through untouched instead of being rejected.
  13136. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13137. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13138. Server svr;
  13139. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13140. res.set_content(body, "image/jpeg");
  13141. res.set_header("Content-Encoding", "UTF-8");
  13142. });
  13143. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13144. res.set_content(body, "image/jpeg");
  13145. res.set_header("Content-Encoding", "identity");
  13146. });
  13147. svr.Post("/echo", [](const Request &req, Response &res) {
  13148. res.set_content(req.body, "image/jpeg");
  13149. });
  13150. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13151. auto se = detail::scope_exit([&] {
  13152. svr.stop();
  13153. t.join();
  13154. ASSERT_FALSE(svr.is_running());
  13155. });
  13156. svr.wait_until_ready();
  13157. Client cli(HOST, PORT);
  13158. {
  13159. auto res = cli.Get("/image");
  13160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13161. EXPECT_EQ(StatusCode::OK_200, res->status);
  13162. EXPECT_EQ(body, res->body);
  13163. }
  13164. {
  13165. auto res = cli.Get("/identity");
  13166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13167. EXPECT_EQ(StatusCode::OK_200, res->status);
  13168. EXPECT_EQ(body, res->body);
  13169. }
  13170. {
  13171. // The same applies to a request body reaching the server.
  13172. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13173. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13175. EXPECT_EQ(StatusCode::OK_200, res->status);
  13176. EXPECT_EQ(body, res->body);
  13177. }
  13178. }
  13179. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13180. // gzip-encoded response even when the build has no zlib support.
  13181. static const char GZIPPED_HELLO_WORLD[] = {
  13182. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13183. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13184. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13185. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13186. // A content coding is a whole token, not something the field value merely
  13187. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13188. // as "fibre" look like Brotli, and turned a multi-coding value like
  13189. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13190. // it was never meant to see.
  13191. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13192. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13193. Server svr;
  13194. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13195. res.set_content(body, "image/jpeg");
  13196. res.set_header("Content-Encoding", "fibre");
  13197. });
  13198. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13199. res.set_content(body, "image/jpeg");
  13200. res.set_header("Content-Encoding", "gzip, br");
  13201. });
  13202. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13203. res.set_content(body, "image/jpeg");
  13204. res.set_header("Content-Encoding", "x-zstd-ish");
  13205. });
  13206. auto port = svr.bind_to_any_port(HOST);
  13207. thread t = thread([&]() { svr.listen_after_bind(); });
  13208. auto se = detail::scope_exit([&] {
  13209. svr.stop();
  13210. t.join();
  13211. ASSERT_FALSE(svr.is_running());
  13212. });
  13213. svr.wait_until_ready();
  13214. Client cli(HOST, port);
  13215. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13216. auto res = cli.Get(path);
  13217. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13218. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13219. // Not a coding we recognize, so the payload comes back untouched
  13220. EXPECT_EQ(body, res->body) << path;
  13221. }
  13222. }
  13223. // A content coding cpp-httplib recognizes but was not built with must be
  13224. // reported as such. Handing the still-compressed payload back to the caller
  13225. // would silently corrupt it.
  13226. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13227. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13228. Server svr;
  13229. // "image/jpeg" keeps the server from applying a content coding of its own,
  13230. // so the hand-crafted Content-Encoding below survives.
  13231. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13232. res.set_content(gzipped, "image/jpeg");
  13233. res.set_header("Content-Encoding", "gzip");
  13234. });
  13235. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13236. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13237. res.set_content(gzipped, "image/jpeg");
  13238. res.set_header("Content-Encoding", "GZIP");
  13239. });
  13240. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13241. auto se = detail::scope_exit([&] {
  13242. svr.stop();
  13243. t.join();
  13244. ASSERT_FALSE(svr.is_running());
  13245. });
  13246. svr.wait_until_ready();
  13247. Client cli(HOST, PORT);
  13248. {
  13249. auto res = cli.Get("/gzipped");
  13250. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13252. EXPECT_EQ("Hello World!", res->body);
  13253. #else
  13254. ASSERT_FALSE(res);
  13255. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13256. #endif
  13257. }
  13258. {
  13259. // open_stream() must behave the same way.
  13260. auto handle = cli.open_stream("GET", "/gzipped");
  13261. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13262. ASSERT_TRUE(handle.is_valid());
  13263. std::string received;
  13264. char buf[256];
  13265. ssize_t n;
  13266. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13267. received.append(buf, static_cast<size_t>(n));
  13268. }
  13269. EXPECT_EQ("Hello World!", received);
  13270. #else
  13271. EXPECT_FALSE(handle.is_valid());
  13272. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13273. #endif
  13274. }
  13275. {
  13276. // A differently-cased coding must not be mistaken for an unknown one, or
  13277. // the body would be handed back still compressed.
  13278. auto res = cli.Get("/gzipped-uppercase");
  13279. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13281. EXPECT_EQ("Hello World!", res->body);
  13282. #else
  13283. ASSERT_FALSE(res);
  13284. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13285. #endif
  13286. }
  13287. }
  13288. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13289. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13290. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13291. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13292. // body a second time and appending a second Content-Encoding field line, so
  13293. // clients that decode one coding per listed value handed back raw gzip bytes.
  13294. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13295. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13296. Server svr;
  13297. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13298. // keeps the server from applying a coding of its own.
  13299. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13300. res.set_content(gzipped, "text/plain");
  13301. res.set_header("Content-Encoding", "gzip");
  13302. });
  13303. auto port = svr.bind_to_any_port(HOST);
  13304. thread t = thread([&]() { svr.listen_after_bind(); });
  13305. auto se = detail::scope_exit([&] {
  13306. svr.stop();
  13307. t.join();
  13308. ASSERT_FALSE(svr.is_running());
  13309. });
  13310. svr.wait_until_ready();
  13311. Client cli(HOST, port);
  13312. Headers headers = {{"Accept-Encoding", "gzip"}};
  13313. auto res = cli.Get("/pre-gzipped", headers);
  13314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13315. EXPECT_EQ(StatusCode::OK_200, res->status);
  13316. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13317. EXPECT_EQ("Hello World!", res->body);
  13318. }
  13319. // set_compress(false) sends every handler response as it is, buffered or
  13320. // streamed
  13321. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13322. const std::string text(1000, 'a');
  13323. Server svr;
  13324. svr.set_compress(false);
  13325. svr.Get("/buffered", [&](const Request &, Response &res) {
  13326. res.set_content(text, "text/plain");
  13327. });
  13328. svr.Get("/streamed", [&](const Request &, Response &res) {
  13329. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13330. sink.write(text.data(), text.size());
  13331. sink.done();
  13332. return true;
  13333. });
  13334. });
  13335. auto port = svr.bind_to_any_port(HOST);
  13336. ASSERT_LT(0, port);
  13337. thread t = thread([&] { svr.listen_after_bind(); });
  13338. auto se = detail::scope_exit([&] {
  13339. svr.stop();
  13340. t.join();
  13341. ASSERT_FALSE(svr.is_running());
  13342. });
  13343. svr.wait_until_ready();
  13344. Client cli(HOST, port);
  13345. cli.set_decompress(false);
  13346. for (auto path : {"/buffered", "/streamed"}) {
  13347. SCOPED_TRACE(path);
  13348. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13350. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13351. EXPECT_EQ(text, res->body);
  13352. }
  13353. }
  13354. // A chunked provider settles its coding where the headers are written and
  13355. // reuses it at write time. Both ends of that have to hold: a handler's own
  13356. // Content-Encoding suppresses the coding, and a response without one is still
  13357. // compressed as it always was.
  13358. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13359. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13360. const std::string plain = "Hello World! Hello World! Hello World!";
  13361. Server svr;
  13362. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13363. res.set_header("Content-Encoding", "gzip");
  13364. res.set_chunked_content_provider(
  13365. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13366. sink.write(gzipped.data(), gzipped.size());
  13367. sink.done();
  13368. return true;
  13369. });
  13370. });
  13371. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13372. res.set_chunked_content_provider(
  13373. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13374. sink.write(plain.data(), plain.size());
  13375. sink.done();
  13376. return true;
  13377. });
  13378. });
  13379. auto port = svr.bind_to_any_port(HOST);
  13380. thread t = thread([&]() { svr.listen_after_bind(); });
  13381. auto se = detail::scope_exit([&] {
  13382. svr.stop();
  13383. t.join();
  13384. ASSERT_FALSE(svr.is_running());
  13385. });
  13386. svr.wait_until_ready();
  13387. Client cli(HOST, port);
  13388. Headers headers = {{"Accept-Encoding", "gzip"}};
  13389. {
  13390. auto res = cli.Get("/pre-gzipped", headers);
  13391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13392. EXPECT_EQ(StatusCode::OK_200, res->status);
  13393. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13394. EXPECT_EQ("Hello World!", res->body);
  13395. }
  13396. {
  13397. auto res = cli.Get("/negotiated", headers);
  13398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13399. EXPECT_EQ(StatusCode::OK_200, res->status);
  13400. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13401. EXPECT_EQ(plain, res->body);
  13402. }
  13403. }
  13404. #endif
  13405. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13406. // the same message as the comma-joined one, so both have to be read the same
  13407. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13408. // single gzip coding, and a body the sender says was encoded twice was handed
  13409. // back after one pass, still compressed but presented as decoded.
  13410. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13411. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13412. Server svr;
  13413. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13414. res.set_content(body, "image/jpeg");
  13415. res.headers.emplace("Content-Encoding", "gzip");
  13416. res.headers.emplace("Content-Encoding", "gzip");
  13417. });
  13418. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13419. res.set_content(body, "image/jpeg");
  13420. res.set_header("Content-Encoding", "gzip, gzip");
  13421. });
  13422. auto port = svr.bind_to_any_port(HOST);
  13423. thread t = thread([&]() { svr.listen_after_bind(); });
  13424. auto se = detail::scope_exit([&] {
  13425. svr.stop();
  13426. t.join();
  13427. ASSERT_FALSE(svr.is_running());
  13428. });
  13429. svr.wait_until_ready();
  13430. Client cli(HOST, port);
  13431. // Two codings is not something cpp-httplib decodes, so both representations
  13432. // take the pass-through path rather than one of them being gunzipped once.
  13433. for (const char *path : {"/split", "/joined"}) {
  13434. auto res = cli.Get(path);
  13435. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13436. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13437. EXPECT_EQ(body, res->body) << path;
  13438. }
  13439. }
  13440. // Regression test for DoS vulnerability: a malicious server sending a response
  13441. // without Content-Length header must not cause unbounded memory consumption on
  13442. // the client side. The client should stop reading after a reasonable limit,
  13443. // similar to the server-side set_payload_max_length protection.
  13444. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13445. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13446. #ifndef _WIN32
  13447. signal(SIGPIPE, SIG_IGN);
  13448. #endif
  13449. auto server_thread = std::thread([] {
  13450. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13451. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13452. default_socket_options(srv);
  13453. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13454. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13455. sockaddr_in addr{};
  13456. addr.sin_family = AF_INET;
  13457. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13458. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13459. int opt = 1;
  13460. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13461. #ifdef _WIN32
  13462. reinterpret_cast<const char *>(&opt),
  13463. #else
  13464. &opt,
  13465. #endif
  13466. sizeof(opt));
  13467. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13468. ::listen(srv, 1);
  13469. sockaddr_in cli_addr{};
  13470. socklen_t cli_len = sizeof(cli_addr);
  13471. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13472. if (cli != INVALID_SOCKET) {
  13473. char buf[4096];
  13474. ::recv(cli, buf, sizeof(buf), 0);
  13475. // Malicious response: no Content-Length, no chunked encoding
  13476. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13477. "Connection: close\r\n"
  13478. "\r\n";
  13479. ::send(cli,
  13480. #ifdef _WIN32
  13481. static_cast<const char *>(response_header.c_str()),
  13482. static_cast<int>(response_header.size()),
  13483. #else
  13484. response_header.c_str(), response_header.size(),
  13485. #endif
  13486. 0);
  13487. // Send 10MB of data
  13488. std::string chunk(64 * 1024, 'A');
  13489. size_t total_sent = 0;
  13490. while (total_sent < MALICIOUS_DATA_SIZE) {
  13491. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13492. auto sent = ::send(cli,
  13493. #ifdef _WIN32
  13494. static_cast<const char *>(chunk.c_str()),
  13495. static_cast<int>(to_send),
  13496. #else
  13497. chunk.c_str(), to_send,
  13498. #endif
  13499. 0);
  13500. if (sent <= 0) break;
  13501. total_sent += static_cast<size_t>(sent);
  13502. }
  13503. detail::close_socket(cli);
  13504. }
  13505. detail::close_socket(srv);
  13506. });
  13507. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13508. size_t total_read = 0;
  13509. {
  13510. Client cli("127.0.0.1", PORT + 2);
  13511. cli.set_read_timeout(5, 0);
  13512. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13513. auto stream = cli.open_stream("GET", "/malicious");
  13514. ASSERT_TRUE(stream.is_valid());
  13515. char buffer[64 * 1024];
  13516. ssize_t n;
  13517. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13518. total_read += static_cast<size_t>(n);
  13519. }
  13520. } // StreamHandle and Client destroyed here, closing the socket
  13521. server_thread.join();
  13522. // With set_payload_max_length, the client must stop reading before consuming
  13523. // all 10MB. The read loop should be cut off at or near the configured limit.
  13524. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13525. << "Client read " << total_read << " bytes, exceeding the configured "
  13526. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13527. }
  13528. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13529. // the entire response body without truncation.
  13530. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13531. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13532. #ifndef _WIN32
  13533. signal(SIGPIPE, SIG_IGN);
  13534. #endif
  13535. auto server_thread = std::thread([] {
  13536. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13537. default_socket_options(srv);
  13538. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13539. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13540. sockaddr_in addr{};
  13541. addr.sin_family = AF_INET;
  13542. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13543. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13544. int opt = 1;
  13545. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13546. #ifdef _WIN32
  13547. reinterpret_cast<const char *>(&opt),
  13548. #else
  13549. &opt,
  13550. #endif
  13551. sizeof(opt));
  13552. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13553. ::listen(srv, 1);
  13554. sockaddr_in cli_addr{};
  13555. socklen_t cli_len = sizeof(cli_addr);
  13556. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13557. if (cli != INVALID_SOCKET) {
  13558. char buf[4096];
  13559. ::recv(cli, buf, sizeof(buf), 0);
  13560. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13561. "Connection: close\r\n"
  13562. "\r\n";
  13563. ::send(cli,
  13564. #ifdef _WIN32
  13565. static_cast<const char *>(response_header.c_str()),
  13566. static_cast<int>(response_header.size()),
  13567. #else
  13568. response_header.c_str(), response_header.size(),
  13569. #endif
  13570. 0);
  13571. std::string chunk(64 * 1024, 'A');
  13572. size_t total_sent = 0;
  13573. while (total_sent < DATA_SIZE) {
  13574. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13575. auto sent = ::send(cli,
  13576. #ifdef _WIN32
  13577. static_cast<const char *>(chunk.c_str()),
  13578. static_cast<int>(to_send),
  13579. #else
  13580. chunk.c_str(), to_send,
  13581. #endif
  13582. 0);
  13583. if (sent <= 0) break;
  13584. total_sent += static_cast<size_t>(sent);
  13585. }
  13586. #ifdef _WIN32
  13587. ::shutdown(cli, SD_SEND);
  13588. #else
  13589. ::shutdown(cli, SHUT_WR);
  13590. #endif
  13591. // Drain until the client closes its end, ensuring all data is delivered
  13592. char drain[1024];
  13593. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13594. detail::close_socket(cli);
  13595. }
  13596. detail::close_socket(srv);
  13597. });
  13598. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13599. size_t total_read = 0;
  13600. {
  13601. Client cli("127.0.0.1", PORT + 2);
  13602. cli.set_read_timeout(5, 0);
  13603. cli.set_payload_max_length(0); // 0 means no limit
  13604. auto stream = cli.open_stream("GET", "/data");
  13605. ASSERT_TRUE(stream.is_valid());
  13606. char buffer[64 * 1024];
  13607. ssize_t n;
  13608. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13609. total_read += static_cast<size_t>(n);
  13610. }
  13611. }
  13612. server_thread.join();
  13613. EXPECT_EQ(total_read, DATA_SIZE)
  13614. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13615. << " bytes without truncation, but only read " << total_read << " bytes.";
  13616. }
  13617. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13618. // enormous Content-Length must not cause the client to pre-allocate a huge
  13619. // response body buffer. The reservation is capped at payload_max_length_, and
  13620. // the read itself fails when the body exceeds the limit.
  13621. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13622. #ifndef _WIN32
  13623. signal(SIGPIPE, SIG_IGN);
  13624. #endif
  13625. auto server_thread = std::thread([] {
  13626. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13627. default_socket_options(srv);
  13628. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13629. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13630. sockaddr_in addr{};
  13631. addr.sin_family = AF_INET;
  13632. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13633. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13634. int opt = 1;
  13635. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13636. #ifdef _WIN32
  13637. reinterpret_cast<const char *>(&opt),
  13638. #else
  13639. &opt,
  13640. #endif
  13641. sizeof(opt));
  13642. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13643. ::listen(srv, 1);
  13644. sockaddr_in cli_addr{};
  13645. socklen_t cli_len = sizeof(cli_addr);
  13646. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13647. if (cli != INVALID_SOCKET) {
  13648. char buf[4096];
  13649. ::recv(cli, buf, sizeof(buf), 0);
  13650. // Malicious response: claim a 20GB body but send only a tiny payload.
  13651. std::string response = "HTTP/1.1 200 OK\r\n"
  13652. "Content-Length: 20000000000\r\n"
  13653. "\r\n"
  13654. "abc";
  13655. ::send(cli,
  13656. #ifdef _WIN32
  13657. static_cast<const char *>(response.c_str()),
  13658. static_cast<int>(response.size()),
  13659. #else
  13660. response.c_str(), response.size(),
  13661. #endif
  13662. 0);
  13663. detail::close_socket(cli);
  13664. }
  13665. detail::close_socket(srv);
  13666. });
  13667. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13668. {
  13669. Client cli("127.0.0.1", PORT + 2);
  13670. cli.set_read_timeout(5, 0);
  13671. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13672. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13673. // (server claims more bytes than payload_max_length permits), but it must
  13674. // not exhaust memory before getting there.
  13675. auto res = cli.Get("/malicious");
  13676. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13677. }
  13678. server_thread.join();
  13679. }
  13680. // Verify that content_receiver bypasses the default payload_max_length,
  13681. // allowing streaming downloads larger than 100MB without requiring an explicit
  13682. // set_payload_max_length call.
  13683. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13684. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13685. #ifndef _WIN32
  13686. signal(SIGPIPE, SIG_IGN);
  13687. #endif
  13688. auto server_thread = std::thread([] {
  13689. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13690. default_socket_options(srv);
  13691. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13692. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13693. sockaddr_in addr{};
  13694. addr.sin_family = AF_INET;
  13695. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13696. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13697. int opt = 1;
  13698. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13699. #ifdef _WIN32
  13700. reinterpret_cast<const char *>(&opt),
  13701. #else
  13702. &opt,
  13703. #endif
  13704. sizeof(opt));
  13705. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13706. ::listen(srv, 1);
  13707. sockaddr_in cli_addr{};
  13708. socklen_t cli_len = sizeof(cli_addr);
  13709. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13710. if (cli != INVALID_SOCKET) {
  13711. char buf[4096];
  13712. ::recv(cli, buf, sizeof(buf), 0);
  13713. // Response with Content-Length larger than default 100MB limit
  13714. auto content_length = std::to_string(DATA_SIZE);
  13715. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13716. "Content-Length: " +
  13717. content_length +
  13718. "\r\n"
  13719. "Connection: close\r\n"
  13720. "\r\n";
  13721. ::send(cli,
  13722. #ifdef _WIN32
  13723. static_cast<const char *>(response_header.c_str()),
  13724. static_cast<int>(response_header.size()),
  13725. #else
  13726. response_header.c_str(), response_header.size(),
  13727. #endif
  13728. 0);
  13729. std::string chunk(64 * 1024, 'A');
  13730. size_t total_sent = 0;
  13731. while (total_sent < DATA_SIZE) {
  13732. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13733. auto sent = ::send(cli,
  13734. #ifdef _WIN32
  13735. static_cast<const char *>(chunk.c_str()),
  13736. static_cast<int>(to_send),
  13737. #else
  13738. chunk.c_str(), to_send,
  13739. #endif
  13740. 0);
  13741. if (sent <= 0) break;
  13742. total_sent += static_cast<size_t>(sent);
  13743. }
  13744. detail::close_socket(cli);
  13745. }
  13746. detail::close_socket(srv);
  13747. });
  13748. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13749. size_t total_received = 0;
  13750. {
  13751. Client cli("127.0.0.1", PORT + 2);
  13752. cli.set_read_timeout(10, 0);
  13753. // Do NOT call set_payload_max_length — use the default 100MB limit
  13754. auto res =
  13755. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13756. total_received += data_length;
  13757. return true;
  13758. });
  13759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13760. EXPECT_EQ(StatusCode::OK_200, res->status);
  13761. }
  13762. server_thread.join();
  13763. EXPECT_EQ(total_received, DATA_SIZE)
  13764. << "With content_receiver, the client should read all " << DATA_SIZE
  13765. << " bytes despite the default 100MB payload_max_length, but only read "
  13766. << total_received << " bytes.";
  13767. }
  13768. // Verify that an explicit set_payload_max_length smaller than the response is
  13769. // enforced even when a content_receiver is used.
  13770. TEST(ClientVulnerabilityTest,
  13771. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13772. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13773. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13774. #ifndef _WIN32
  13775. signal(SIGPIPE, SIG_IGN);
  13776. #endif
  13777. auto server_thread = std::thread([] {
  13778. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13779. default_socket_options(srv);
  13780. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13781. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13782. sockaddr_in addr{};
  13783. addr.sin_family = AF_INET;
  13784. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13785. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13786. int opt = 1;
  13787. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13788. #ifdef _WIN32
  13789. reinterpret_cast<const char *>(&opt),
  13790. #else
  13791. &opt,
  13792. #endif
  13793. sizeof(opt));
  13794. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13795. ::listen(srv, 1);
  13796. sockaddr_in cli_addr{};
  13797. socklen_t cli_len = sizeof(cli_addr);
  13798. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13799. if (cli != INVALID_SOCKET) {
  13800. char buf[4096];
  13801. ::recv(cli, buf, sizeof(buf), 0);
  13802. auto content_length = std::to_string(DATA_SIZE);
  13803. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13804. "Content-Length: " +
  13805. content_length +
  13806. "\r\n"
  13807. "Connection: close\r\n"
  13808. "\r\n";
  13809. ::send(cli,
  13810. #ifdef _WIN32
  13811. static_cast<const char *>(response_header.c_str()),
  13812. static_cast<int>(response_header.size()),
  13813. #else
  13814. response_header.c_str(), response_header.size(),
  13815. #endif
  13816. 0);
  13817. std::string chunk(64 * 1024, 'A');
  13818. size_t total_sent = 0;
  13819. while (total_sent < DATA_SIZE) {
  13820. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13821. auto sent = ::send(cli,
  13822. #ifdef _WIN32
  13823. static_cast<const char *>(chunk.c_str()),
  13824. static_cast<int>(to_send),
  13825. #else
  13826. chunk.c_str(), to_send,
  13827. #endif
  13828. 0);
  13829. if (sent <= 0) break;
  13830. total_sent += static_cast<size_t>(sent);
  13831. }
  13832. detail::close_socket(cli);
  13833. }
  13834. detail::close_socket(srv);
  13835. });
  13836. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13837. size_t total_received = 0;
  13838. {
  13839. Client cli("127.0.0.1", PORT + 2);
  13840. cli.set_read_timeout(10, 0);
  13841. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13842. auto res =
  13843. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13844. total_received += data_length;
  13845. return true;
  13846. });
  13847. // Should fail because 200MB exceeds the explicit 150MB limit
  13848. EXPECT_FALSE(res);
  13849. }
  13850. server_thread.join();
  13851. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13852. << "Client with content_receiver should respect the explicit "
  13853. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13854. << total_received << " bytes.";
  13855. }
  13856. // Verify that an explicit set_payload_max_length larger than the response
  13857. // allows the content_receiver to read all data successfully.
  13858. TEST(ClientVulnerabilityTest,
  13859. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13860. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13861. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13862. #ifndef _WIN32
  13863. signal(SIGPIPE, SIG_IGN);
  13864. #endif
  13865. auto server_thread = std::thread([] {
  13866. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13867. default_socket_options(srv);
  13868. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13869. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13870. sockaddr_in addr{};
  13871. addr.sin_family = AF_INET;
  13872. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13873. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13874. int opt = 1;
  13875. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13876. #ifdef _WIN32
  13877. reinterpret_cast<const char *>(&opt),
  13878. #else
  13879. &opt,
  13880. #endif
  13881. sizeof(opt));
  13882. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13883. ::listen(srv, 1);
  13884. sockaddr_in cli_addr{};
  13885. socklen_t cli_len = sizeof(cli_addr);
  13886. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13887. if (cli != INVALID_SOCKET) {
  13888. char buf[4096];
  13889. ::recv(cli, buf, sizeof(buf), 0);
  13890. auto content_length = std::to_string(DATA_SIZE);
  13891. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13892. "Content-Length: " +
  13893. content_length +
  13894. "\r\n"
  13895. "Connection: close\r\n"
  13896. "\r\n";
  13897. ::send(cli,
  13898. #ifdef _WIN32
  13899. static_cast<const char *>(response_header.c_str()),
  13900. static_cast<int>(response_header.size()),
  13901. #else
  13902. response_header.c_str(), response_header.size(),
  13903. #endif
  13904. 0);
  13905. std::string chunk(64 * 1024, 'A');
  13906. size_t total_sent = 0;
  13907. while (total_sent < DATA_SIZE) {
  13908. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13909. auto sent = ::send(cli,
  13910. #ifdef _WIN32
  13911. static_cast<const char *>(chunk.c_str()),
  13912. static_cast<int>(to_send),
  13913. #else
  13914. chunk.c_str(), to_send,
  13915. #endif
  13916. 0);
  13917. if (sent <= 0) break;
  13918. total_sent += static_cast<size_t>(sent);
  13919. }
  13920. #ifdef _WIN32
  13921. ::shutdown(cli, SD_SEND);
  13922. #else
  13923. ::shutdown(cli, SHUT_WR);
  13924. #endif
  13925. char drain[1024];
  13926. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13927. detail::close_socket(cli);
  13928. }
  13929. detail::close_socket(srv);
  13930. });
  13931. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13932. size_t total_received = 0;
  13933. {
  13934. Client cli("127.0.0.1", PORT + 2);
  13935. cli.set_read_timeout(10, 0);
  13936. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13937. auto res =
  13938. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13939. total_received += data_length;
  13940. return true;
  13941. });
  13942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13943. EXPECT_EQ(StatusCode::OK_200, res->status);
  13944. }
  13945. server_thread.join();
  13946. EXPECT_EQ(total_received, DATA_SIZE)
  13947. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13948. << " bytes (larger than " << DATA_SIZE
  13949. << " bytes response), content_receiver should read all data, but only "
  13950. "read "
  13951. << total_received << " bytes.";
  13952. }
  13953. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13954. // Regression test for "zip bomb" attack on the client side: a malicious server
  13955. // sends a small gzip-compressed response that decompresses to a huge payload.
  13956. // The client must enforce payload_max_length on the decompressed size.
  13957. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13958. constexpr size_t DECOMPRESSED_SIZE =
  13959. 10 * 1024 * 1024; // 10MB after decompression
  13960. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13961. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13962. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13963. std::string compressed;
  13964. {
  13965. httplib::detail::gzip_compressor compressor;
  13966. bool ok =
  13967. compressor.compress(uncompressed.data(), uncompressed.size(),
  13968. /*last=*/true, [&](const char *buf, size_t len) {
  13969. compressed.append(buf, len);
  13970. return true;
  13971. });
  13972. ASSERT_TRUE(ok);
  13973. }
  13974. // Sanity: compressed data should be much smaller than the decompressed size
  13975. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13976. #ifndef _WIN32
  13977. signal(SIGPIPE, SIG_IGN);
  13978. #endif
  13979. // Set up the listening socket in the main thread so the server is guaranteed
  13980. // to be ready before the client connects (eliminates race condition).
  13981. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13982. default_socket_options(srv);
  13983. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13984. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13985. sockaddr_in addr{};
  13986. addr.sin_family = AF_INET;
  13987. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13988. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13989. int opt = 1;
  13990. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13991. #ifdef _WIN32
  13992. reinterpret_cast<const char *>(&opt),
  13993. #else
  13994. &opt,
  13995. #endif
  13996. sizeof(opt));
  13997. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13998. ASSERT_EQ(0, ::listen(srv, 1));
  13999. auto server_thread = std::thread([&compressed, srv] {
  14000. sockaddr_in cli_addr{};
  14001. socklen_t cli_len = sizeof(cli_addr);
  14002. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14003. if (cli != INVALID_SOCKET) {
  14004. // Read the full HTTP request (until \r\n\r\n)
  14005. char buf[4096];
  14006. size_t total = 0;
  14007. while (total < sizeof(buf)) {
  14008. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14009. if (n <= 0) break;
  14010. total += static_cast<size_t>(n);
  14011. // Check for end of headers
  14012. if (total >= 4) {
  14013. std::string req(buf, total);
  14014. if (req.find("\r\n\r\n") != std::string::npos) break;
  14015. }
  14016. }
  14017. // Malicious response: gzip-compressed body, no Content-Length
  14018. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14019. "Content-Encoding: gzip\r\n"
  14020. "Connection: close\r\n"
  14021. "\r\n";
  14022. ::send(cli,
  14023. #ifdef _WIN32
  14024. static_cast<const char *>(response_header.c_str()),
  14025. static_cast<int>(response_header.size()),
  14026. #else
  14027. response_header.c_str(), response_header.size(),
  14028. #endif
  14029. 0);
  14030. // Send the compressed payload (small on the wire, huge when decompressed)
  14031. size_t total_sent = 0;
  14032. while (total_sent < compressed.size()) {
  14033. auto to_send = std::min(compressed.size() - total_sent,
  14034. static_cast<size_t>(64 * 1024));
  14035. auto sent =
  14036. ::send(cli,
  14037. #ifdef _WIN32
  14038. static_cast<const char *>(compressed.c_str() + total_sent),
  14039. static_cast<int>(to_send),
  14040. #else
  14041. compressed.c_str() + total_sent, to_send,
  14042. #endif
  14043. 0);
  14044. if (sent <= 0) break;
  14045. total_sent += static_cast<size_t>(sent);
  14046. }
  14047. detail::close_socket(cli);
  14048. }
  14049. });
  14050. auto se = detail::scope_exit([&] {
  14051. detail::close_socket(srv);
  14052. server_thread.join();
  14053. });
  14054. size_t total_decompressed = 0;
  14055. {
  14056. Client cli("127.0.0.1", PORT + 3);
  14057. cli.set_read_timeout(5, 0);
  14058. cli.set_decompress(true);
  14059. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14060. auto stream = cli.open_stream("GET", "/zipbomb");
  14061. ASSERT_TRUE(stream.is_valid());
  14062. char buffer[64 * 1024];
  14063. ssize_t n;
  14064. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14065. total_decompressed += static_cast<size_t>(n);
  14066. }
  14067. }
  14068. // The decompressed size must be capped by payload_max_length. Without
  14069. // protection, the client would decompress the full 10MB from a tiny
  14070. // compressed payload, enabling a zip bomb DoS attack.
  14071. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14072. << "Client decompressed " << total_decompressed
  14073. << " bytes from a gzip response. The decompressed size should be "
  14074. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14075. }
  14076. #endif
  14077. TEST(HostAndPortPropertiesTest, NoSSL) {
  14078. httplib::Client cli("www.google.com", 1234);
  14079. ASSERT_EQ("www.google.com", cli.host());
  14080. ASSERT_EQ(1234, cli.port());
  14081. }
  14082. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14083. httplib::Client cli("www.google.com:1234");
  14084. ASSERT_EQ("www.google.com", cli.host());
  14085. ASSERT_EQ(1234, cli.port());
  14086. }
  14087. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14088. // Port number that overflows int — should not crash, client becomes invalid
  14089. httplib::Client cli("http://www.google.com:99999999999999999999");
  14090. ASSERT_FALSE(cli.is_valid());
  14091. }
  14092. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14093. // Port 99999 exceeds valid range (1-65535) — should not crash
  14094. httplib::Client cli("http://www.google.com:99999");
  14095. ASSERT_FALSE(cli.is_valid());
  14096. auto res = cli.Get("/");
  14097. EXPECT_FALSE(res);
  14098. EXPECT_EQ(Error::Connection, res.error());
  14099. }
  14100. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14101. httplib::Client cli("http://user:pass@localhost:1234");
  14102. ASSERT_FALSE(cli.is_valid());
  14103. EXPECT_FALSE(cli.Get("/"));
  14104. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14105. }
  14106. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14107. httplib::Client cli("http://www.google.com:80abc");
  14108. ASSERT_FALSE(cli.is_valid());
  14109. }
  14110. #ifdef CPPHTTPLIB_SSL_ENABLED
  14111. TEST(HostAndPortPropertiesTest, SSL) {
  14112. httplib::SSLClient cli("www.google.com");
  14113. ASSERT_EQ("www.google.com", cli.host());
  14114. ASSERT_EQ(443, cli.port());
  14115. }
  14116. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14117. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14118. std::string cert;
  14119. read_file(CA_CERT_FILE, cert);
  14120. httplib::SSLClient httplib_client("www.google.com");
  14121. // Load CA store first time
  14122. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14123. // Load CA store second time (update)
  14124. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14125. // Verify client is still valid and can make connections
  14126. httplib_client.enable_server_certificate_verification(true);
  14127. auto res = httplib_client.Get("/");
  14128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14129. // Google may return 200 or 301 depending on various factors
  14130. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  14131. res->status == StatusCode::MovedPermanently_301);
  14132. }
  14133. TEST(SSLClientTest, ServerNameIndication_Online) {
  14134. auto host = "httpbingo.org";
  14135. auto path = std::string{"/get"};
  14136. SSLClient cli(host, 443);
  14137. auto res = cli.Get(path);
  14138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14139. ASSERT_EQ(StatusCode::OK_200, res->status);
  14140. }
  14141. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14142. // Use a site that will cause SSL verification failure due to self-signed cert
  14143. SSLClient cli("self-signed.badssl.com", 443);
  14144. cli.enable_server_certificate_verification(true);
  14145. auto res = cli.Get("/");
  14146. ASSERT_TRUE(!res);
  14147. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14148. // Verify backend error is captured for SSLServerVerification
  14149. // This occurs when certificate verification fails
  14150. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14151. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14152. EXPECT_NE(0UL, res.ssl_backend_error());
  14153. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14154. res.ssl_error());
  14155. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14156. #if !defined(_WIN32) || \
  14157. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14158. // On non-Windows or when Windows Schannel is disabled, the error comes
  14159. // from OpenSSL's verification
  14160. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14161. res.ssl_backend_error());
  14162. #endif
  14163. #endif
  14164. }
  14165. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14166. // Use a site where hostname doesn't match the certificate
  14167. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14168. SSLClient cli("wrong.host.badssl.com", 443);
  14169. cli.enable_server_certificate_verification(true);
  14170. cli.enable_server_hostname_verification(true);
  14171. auto res = cli.Get("/");
  14172. ASSERT_TRUE(!res);
  14173. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14174. // Verify backend error is captured for hostname verification failure
  14175. EXPECT_NE(0UL, res.ssl_backend_error());
  14176. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14177. res.ssl_error());
  14178. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14179. #if !defined(_WIN32) || \
  14180. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14181. // On non-Windows or when Windows Schannel is disabled, the error comes
  14182. // from OpenSSL's hostname verification
  14183. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14184. res.ssl_backend_error());
  14185. #endif
  14186. #endif
  14187. }
  14188. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14189. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14190. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14191. SSLClient cli("www.google.com", 443);
  14192. cli.enable_server_certificate_verification(true);
  14193. auto res = cli.Get("/");
  14194. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14195. }
  14196. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14197. SSLClient cli("www.google.com", 443);
  14198. cli.enable_server_certificate_verification(true);
  14199. cli.enable_windows_certificate_verification(false);
  14200. auto res = cli.Get("/");
  14201. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14202. }
  14203. // The server sends an intermediate cross-signed by a root Windows trusts,
  14204. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14205. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14206. SSLClient cli("accounts.spotify.com", 443);
  14207. auto res = cli.Get("/");
  14208. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14209. << " ssl_backend_error=" << res.ssl_backend_error();
  14210. }
  14211. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14212. // policy status, which no backend reports for a self-signed certificate.
  14213. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14214. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14215. ASSERT_TRUE(svr.is_valid());
  14216. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14217. auto se = detail::scope_exit([&] {
  14218. svr.stop();
  14219. t.join();
  14220. ASSERT_FALSE(svr.is_running());
  14221. });
  14222. svr.wait_until_ready();
  14223. SSLClient cli("127.0.0.1", PORT);
  14224. cli.set_connection_timeout(30);
  14225. auto res = cli.Get("/");
  14226. ASSERT_FALSE(res);
  14227. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14228. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14229. }
  14230. #endif
  14231. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14232. Client cli("https://google.com");
  14233. auto res = cli.Get("/");
  14234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14235. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14236. }
  14237. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14238. SSLClient cli("google.com");
  14239. cli.set_ca_cert_path(CA_CERT_FILE);
  14240. auto res = cli.Get("/");
  14241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14242. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14243. }
  14244. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14245. SSLClient cli("google.com");
  14246. cli.enable_server_certificate_verification(true);
  14247. cli.set_ca_cert_path("hello");
  14248. auto res = cli.Get("/");
  14249. ASSERT_TRUE(!res);
  14250. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14251. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14252. // should be set
  14253. EXPECT_EQ(0, res.ssl_error());
  14254. // Verify backend error is captured for SSLLoadingCerts
  14255. // This error occurs when loading CA certificates fails
  14256. EXPECT_NE(0UL, res.ssl_backend_error());
  14257. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14258. // OpenSSL specific error codes:
  14259. // > openssl errstr 0x80000002
  14260. // error:80000002:system library::No such file or directory
  14261. // > openssl errstr 0xA000126
  14262. // error:0A000126:SSL routines::unexpected eof while reading
  14263. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14264. res.ssl_backend_error() == 0xA000126);
  14265. #endif
  14266. }
  14267. TEST(SSLClientTest, ServerCertificateVerification4) {
  14268. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14269. ASSERT_TRUE(svr.is_valid());
  14270. svr.Get("/test", [&](const Request &, Response &res) {
  14271. res.set_content("test", "text/plain");
  14272. svr.stop();
  14273. ASSERT_TRUE(true);
  14274. });
  14275. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14276. auto se = detail::scope_exit([&] {
  14277. t.join();
  14278. ASSERT_FALSE(svr.is_running());
  14279. });
  14280. svr.wait_until_ready();
  14281. SSLClient cli("127.0.0.1", PORT);
  14282. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14283. cli.enable_server_certificate_verification(true);
  14284. cli.set_connection_timeout(30);
  14285. auto res = cli.Get("/test");
  14286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14287. ASSERT_EQ(StatusCode::OK_200, res->status);
  14288. }
  14289. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14290. std::string cert;
  14291. read_file(CA_CERT_FILE, cert);
  14292. SSLClient cli("google.com");
  14293. cli.load_ca_cert_store(cert.data(), cert.size());
  14294. const auto res = cli.Get("/");
  14295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14296. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14297. }
  14298. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14299. // clang-format off
  14300. static constexpr char cert[] =
  14301. "GlobalSign Root CA\n"
  14302. "==================\n"
  14303. "-----BEGIN CERTIFICATE-----\n"
  14304. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14305. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14306. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14307. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14308. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14309. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14310. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14311. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14312. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14313. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14314. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14315. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14316. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14317. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14318. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14319. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14320. "-----END CERTIFICATE-----\n";
  14321. // clang-format on
  14322. SSLClient cli("google.com");
  14323. cli.load_ca_cert_store(cert, sizeof(cert));
  14324. const auto res = cli.Get("/");
  14325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14326. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14327. }
  14328. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14329. SSLClient cli("www.youtube.com");
  14330. cli.set_ca_cert_path(CA_CERT_FILE);
  14331. cli.enable_server_certificate_verification(true);
  14332. cli.set_follow_location(true);
  14333. auto res = cli.Get("/");
  14334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14335. ASSERT_EQ(StatusCode::OK_200, res->status);
  14336. }
  14337. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14338. SSLClient cli("wWw.YouTube.Com");
  14339. cli.set_ca_cert_path(CA_CERT_FILE);
  14340. cli.enable_server_certificate_verification(true);
  14341. cli.enable_server_hostname_verification(true);
  14342. cli.set_follow_location(true);
  14343. auto res = cli.Get("/");
  14344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14345. ASSERT_EQ(StatusCode::OK_200, res->status);
  14346. }
  14347. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14348. SSLClient cli("gOoGlE.COm");
  14349. cli.enable_server_certificate_verification(true);
  14350. cli.enable_server_hostname_verification(true);
  14351. cli.set_follow_location(true);
  14352. auto res = cli.Get("/");
  14353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14354. ASSERT_EQ(StatusCode::OK_200, res->status);
  14355. }
  14356. TEST(SSLClientTest, Issue2004_Online) {
  14357. Client client("https://google.com");
  14358. client.set_follow_location(true);
  14359. auto res = client.Get("/");
  14360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14361. ASSERT_EQ(StatusCode::OK_200, res->status);
  14362. auto body = res->body;
  14363. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  14364. }
  14365. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14366. // Create SSLClient with invalid cert/key to make is_valid() return false
  14367. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14368. "nonexistent_key.pem");
  14369. // is_valid() should be false due to cert loading failure
  14370. ASSERT_FALSE(cli.is_valid());
  14371. auto res = cli.Get("/");
  14372. ASSERT_FALSE(res);
  14373. EXPECT_EQ(Error::SSLConnection, res.error());
  14374. }
  14375. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14376. // Test for Issue #2251: SSL error not properly reported when client cert
  14377. // and key paths are swapped or mismatched
  14378. // This simulates the scenario where user accidentally swaps the cert and key
  14379. // files
  14380. // Using client cert file as private key and vice versa (completely wrong)
  14381. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14382. // Should fail validation due to cert/key mismatch
  14383. ASSERT_FALSE(cli.is_valid());
  14384. // Attempt to make a request should fail with proper error
  14385. auto res = cli.Get("/");
  14386. ASSERT_FALSE(res);
  14387. EXPECT_EQ(Error::SSLConnection, res.error());
  14388. // SSL error should be recorded in the Result object (this is the key fix for
  14389. // Issue #2251)
  14390. auto backend_error = res.ssl_backend_error();
  14391. EXPECT_NE(0u, backend_error);
  14392. }
  14393. // Tests cert/key mismatch detection at the TLS context level
  14394. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14395. // Test that using mismatched cert/key causes connection failure.
  14396. // We verify this at the SSLClient level rather than through internal
  14397. // TLS API functions.
  14398. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14399. cli.enable_server_certificate_verification(false);
  14400. cli.set_connection_timeout(2);
  14401. // The mismatch should cause a connection or handshake error
  14402. auto res = cli.Get("/test");
  14403. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14404. // Either way, the request should fail
  14405. EXPECT_FALSE(res);
  14406. }
  14407. #endif
  14408. #if 0
  14409. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14410. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14411. ASSERT_TRUE(cli != nullptr);
  14412. cli->set_address_family(AF_INET6);
  14413. cli->set_interface("en0");
  14414. auto res = cli->Get("/get");
  14415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14416. ASSERT_EQ(StatusCode::OK_200, res->status);
  14417. }
  14418. #endif
  14419. // Client certificate tests - work with all TLS backends
  14420. #ifdef CPPHTTPLIB_SSL_ENABLED
  14421. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14422. void ClientCertPresent(
  14423. const std::string &client_cert_file,
  14424. const std::string &client_private_key_file,
  14425. const std::string &client_encrypted_private_key_pass = std::string(),
  14426. const ClientCertServerSetup &setup = nullptr) {
  14427. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14428. ASSERT_TRUE(svr.is_valid());
  14429. if (setup) { setup(svr); }
  14430. svr.Get("/test", [&](const Request &req, Response &res) {
  14431. res.set_content("test", "text/plain");
  14432. auto cert = req.peer_cert();
  14433. ASSERT_TRUE(static_cast<bool>(cert));
  14434. std::string common_name = cert.subject_cn();
  14435. EXPECT_EQ("Common Name", common_name);
  14436. });
  14437. auto port = svr.bind_to_any_port(HOST);
  14438. ASSERT_LT(0, port);
  14439. thread t = thread([&]() { svr.listen_after_bind(); });
  14440. auto se = detail::scope_exit([&] {
  14441. svr.stop();
  14442. t.join();
  14443. ASSERT_FALSE(svr.is_running());
  14444. });
  14445. svr.wait_until_ready();
  14446. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14447. client_encrypted_private_key_pass);
  14448. cli.enable_server_certificate_verification(false);
  14449. cli.set_connection_timeout(30);
  14450. auto res = cli.Get("/test");
  14451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14452. ASSERT_EQ(StatusCode::OK_200, res->status);
  14453. }
  14454. TEST(SSLClientServerTest, ClientCertPresent) {
  14455. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14456. }
  14457. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14458. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14459. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14460. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14461. }
  14462. // Expects svr, which must require client certificates, to reject a client
  14463. // that has none
  14464. void RejectsClientWithoutCert(SSLServer &svr) {
  14465. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14466. auto port = svr.bind_to_any_port(HOST);
  14467. ASSERT_LT(0, port);
  14468. thread t = thread([&]() { svr.listen_after_bind(); });
  14469. auto se = detail::scope_exit([&] {
  14470. svr.stop();
  14471. t.join();
  14472. ASSERT_FALSE(svr.is_running());
  14473. });
  14474. svr.wait_until_ready();
  14475. SSLClient cli(HOST, port);
  14476. cli.set_connection_timeout(30);
  14477. // Skip the server certificate check, so that the request fails because the
  14478. // client certificate is missing rather than because cert.pem is not trusted
  14479. cli.enable_server_certificate_verification(false);
  14480. auto res = cli.Get("/test");
  14481. ASSERT_FALSE(res);
  14482. // The server rejects the client during the handshake, or on TLS 1.3 right
  14483. // after it, which the client notices on its first write or read
  14484. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14485. res.error() == Error::Write || res.error() == Error::Read)
  14486. << to_string(res.error());
  14487. if (res.error() == Error::SSLConnection) {
  14488. EXPECT_NE(0UL, res.ssl_backend_error());
  14489. }
  14490. // A rejection noticed on the write keeps the TLS error the write hit
  14491. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14492. }
  14493. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14494. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14495. ASSERT_TRUE(svr.is_valid());
  14496. if (setup) { setup(svr); }
  14497. RejectsClientWithoutCert(svr);
  14498. }
  14499. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14500. // A server that requires client certificates must keep requiring them after
  14501. // setup changes it, and keep accepting a client that has one
  14502. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14503. ClientCertMissing(setup);
  14504. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14505. setup);
  14506. }
  14507. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14508. ClientCertStillRequired([](SSLServer &svr) {
  14509. ASSERT_TRUE(tls::set_verify_callback(
  14510. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14511. });
  14512. }
  14513. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14514. ClientCertStillRequired([](SSLServer &svr) {
  14515. ASSERT_TRUE(tls::set_verify_callback(
  14516. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14517. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14518. });
  14519. }
  14520. // The client verifies the server certificate during the handshake, so a
  14521. // server that fails the check never gets the client certificate, even when a
  14522. // verifier of the client's own accepts it
  14523. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14524. struct Case {
  14525. const char *trusted_ca;
  14526. const char *host;
  14527. Error error;
  14528. };
  14529. // cert2.pem names localhost: the first client does not trust it, and the
  14530. // second trusts it but asks for another name
  14531. for (const auto &c :
  14532. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14533. Case{SERVER_CERT2_FILE, "example.com",
  14534. Error::SSLServerHostnameVerification}}) {
  14535. for (auto with_verifier : {false, true}) {
  14536. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14537. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14538. CLIENT_CA_CERT_FILE);
  14539. ASSERT_TRUE(svr.is_valid());
  14540. std::atomic<bool> got_client_cert{false};
  14541. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14542. [&](const tls::VerifyContext &) {
  14543. got_client_cert = true;
  14544. return true;
  14545. }));
  14546. auto port = svr.bind_to_any_port("127.0.0.1");
  14547. ASSERT_LT(0, port);
  14548. thread t = thread([&] { svr.listen_after_bind(); });
  14549. svr.wait_until_ready();
  14550. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14551. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14552. cli.set_ca_cert_path(c.trusted_ca);
  14553. if (with_verifier) {
  14554. cli.set_server_certificate_verifier(
  14555. [](const tls::VerifyContext &) { return true; });
  14556. }
  14557. auto res = cli.Get("/");
  14558. EXPECT_FALSE(res);
  14559. EXPECT_EQ(c.error, res.error());
  14560. svr.stop();
  14561. t.join();
  14562. EXPECT_FALSE(got_client_cert);
  14563. }
  14564. }
  14565. }
  14566. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14567. std::string cert_pem, key_pem, ca_pem;
  14568. read_file(SERVER_CERT_FILE, cert_pem);
  14569. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14570. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14571. ASSERT_TRUE(
  14572. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14573. }
  14574. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14576. ASSERT_TRUE(svr.is_valid());
  14577. UpdateCertsPemWithClientCA(svr);
  14578. RejectsClientWithoutCert(svr);
  14579. }
  14580. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14581. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14582. }
  14583. // A TLS error from one request must not show up in a later request's Result
  14584. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14585. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14586. ASSERT_TRUE(svr.is_valid());
  14587. svr.Get("/test", [](const Request &, Response &res) {
  14588. res.set_content("test", "text/plain");
  14589. });
  14590. auto port = svr.bind_to_any_port(HOST);
  14591. ASSERT_LT(0, port);
  14592. thread t = thread([&]() { svr.listen_after_bind(); });
  14593. auto se = detail::scope_exit([&] {
  14594. svr.stop();
  14595. t.join();
  14596. ASSERT_FALSE(svr.is_running());
  14597. });
  14598. svr.wait_until_ready();
  14599. SSLClient cli(HOST, port);
  14600. cli.set_connection_timeout(30);
  14601. cli.enable_server_hostname_verification(false);
  14602. // cert.pem is not trusted, so the handshake fails
  14603. ASSERT_FALSE(cli.Get("/test"));
  14604. cli.enable_server_certificate_verification(false);
  14605. auto res = cli.Get("/test");
  14606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14607. EXPECT_EQ(0, res.ssl_error());
  14608. EXPECT_EQ(0UL, res.ssl_backend_error());
  14609. }
  14610. // PEM memory-based constructor tests (works with all TLS backends).
  14611. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14612. // terminator after it.
  14613. void PemMemoryClientCertPresent(
  14614. const std::string &client_cert_file,
  14615. const std::string &client_private_key_file,
  14616. const std::string &client_encrypted_private_key_pass = std::string(),
  14617. bool exact_size = false) {
  14618. // Read PEM files into memory
  14619. std::string server_cert_pem, server_key_pem;
  14620. std::string client_ca_pem;
  14621. std::string client_cert_pem, client_key_pem;
  14622. read_file(SERVER_CERT_FILE, server_cert_pem);
  14623. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14624. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14625. read_file(client_cert_file, client_cert_pem);
  14626. read_file(client_private_key_file, client_key_pem);
  14627. std::list<std::vector<char>> exact_copies;
  14628. auto data = [&](const std::string &pem) -> const char * {
  14629. if (!exact_size) { return pem.c_str(); }
  14630. exact_copies.emplace_back(pem.begin(), pem.end());
  14631. return exact_copies.back().data();
  14632. };
  14633. // Create server with PEM memory
  14634. SSLServer::PemMemory server_pem = {
  14635. data(server_cert_pem),
  14636. server_cert_pem.size(),
  14637. data(server_key_pem),
  14638. server_key_pem.size(),
  14639. data(client_ca_pem),
  14640. client_ca_pem.size(),
  14641. nullptr // no password for server key
  14642. };
  14643. SSLServer svr(server_pem);
  14644. ASSERT_TRUE(svr.is_valid());
  14645. svr.Get("/test", [&](const Request &req, Response &res) {
  14646. res.set_content("test", "text/plain");
  14647. auto cert = req.peer_cert();
  14648. ASSERT_TRUE(static_cast<bool>(cert));
  14649. EXPECT_EQ("Common Name", cert.subject_cn());
  14650. });
  14651. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14652. auto se = detail::scope_exit([&] {
  14653. svr.stop();
  14654. t.join();
  14655. ASSERT_FALSE(svr.is_running());
  14656. });
  14657. svr.wait_until_ready();
  14658. // Create client with PEM memory
  14659. const char *password = client_encrypted_private_key_pass.empty()
  14660. ? nullptr
  14661. : client_encrypted_private_key_pass.c_str();
  14662. SSLClient::PemMemory client_pem = {
  14663. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14664. client_key_pem.size(), password};
  14665. SSLClient cli(HOST, PORT, client_pem);
  14666. cli.enable_server_certificate_verification(false);
  14667. cli.set_connection_timeout(30);
  14668. auto res = cli.Get("/test");
  14669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14670. ASSERT_EQ(StatusCode::OK_200, res->status);
  14671. }
  14672. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14673. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14674. }
  14675. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14676. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14677. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14678. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14679. }
  14680. // A server built from PEM memory with a client CA requires client certificates,
  14681. // also when the CA is a NUL-terminated string passed with a length of 0
  14682. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14683. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14684. read_file(SERVER_CERT_FILE, server_cert_pem);
  14685. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14686. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14687. SSLServer::PemMemory server_pem = {
  14688. server_cert_pem.c_str(),
  14689. server_cert_pem.size(),
  14690. server_key_pem.c_str(),
  14691. server_key_pem.size(),
  14692. client_ca_pem.c_str(),
  14693. client_ca_pem.size(),
  14694. nullptr // no password for server key
  14695. };
  14696. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14697. SCOPED_TRACE(client_ca_pem_len);
  14698. server_pem.client_ca_pem_len = client_ca_pem_len;
  14699. SSLServer svr(server_pem);
  14700. ASSERT_TRUE(svr.is_valid());
  14701. RejectsClientWithoutCert(svr);
  14702. }
  14703. // An empty CA fails to load instead of turning the check off
  14704. server_pem.client_ca_pem = "";
  14705. server_pem.client_ca_pem_len = 0;
  14706. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14707. }
  14708. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14709. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14710. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14711. true);
  14712. }
  14713. // A length shorter than the PEM cuts it short, so it no longer loads
  14714. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14715. std::string cert, key;
  14716. read_file(SERVER_CERT_FILE, cert);
  14717. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14718. for (auto cut_cert : {true, false}) {
  14719. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14720. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14721. SSLServer::PemMemory server_pem = {
  14722. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14723. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14724. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14725. key_len, nullptr};
  14726. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14727. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14728. key.c_str(), key_len, nullptr};
  14729. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14730. }
  14731. }
  14732. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14733. class NoListenSSLServer : public SSLServer {
  14734. public:
  14735. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14736. const char *client_ca_cert_file_path,
  14737. const char *client_ca_cert_dir_path = nullptr)
  14738. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14739. client_ca_cert_dir_path),
  14740. stop_(false) {}
  14741. std::atomic_bool stop_;
  14742. private:
  14743. bool process_and_close_socket(socket_t /*sock*/) override {
  14744. // Don't create SSL context
  14745. while (!stop_.load()) {
  14746. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14747. }
  14748. return true;
  14749. }
  14750. };
  14751. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14752. CLIENT_CA_CERT_FILE);
  14753. ASSERT_TRUE(svr.is_valid());
  14754. svr.Get("/test", [&](const Request &, Response &res) {
  14755. res.set_content("test", "text/plain");
  14756. });
  14757. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14758. auto se = detail::scope_exit([&] {
  14759. svr.stop_ = true;
  14760. svr.stop();
  14761. t.join();
  14762. ASSERT_FALSE(svr.is_running());
  14763. });
  14764. svr.wait_until_ready();
  14765. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14766. cli.enable_server_certificate_verification(false);
  14767. cli.set_connection_timeout(1);
  14768. auto res = cli.Get("/test");
  14769. ASSERT_TRUE(!res);
  14770. EXPECT_EQ(Error::SSLConnection, res.error());
  14771. // Timeout results in WantRead error code (maps to backend-specific value)
  14772. EXPECT_NE(0, res.ssl_error());
  14773. }
  14774. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14775. // Test SSLServer with client certificate verification using the standard
  14776. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14777. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14778. CLIENT_CA_CERT_DIR);
  14779. ASSERT_TRUE(svr.is_valid());
  14780. svr.Get("/test", [&](const Request &req, Response &res) {
  14781. res.set_content("test", "text/plain");
  14782. auto cert = req.peer_cert();
  14783. ASSERT_TRUE(static_cast<bool>(cert));
  14784. auto common_name = cert.subject_cn();
  14785. EXPECT_EQ("Common Name", common_name);
  14786. });
  14787. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14788. auto se = detail::scope_exit([&] {
  14789. svr.stop();
  14790. t.join();
  14791. ASSERT_FALSE(svr.is_running());
  14792. });
  14793. svr.wait_until_ready();
  14794. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14795. cli.enable_server_certificate_verification(false);
  14796. cli.set_connection_timeout(30);
  14797. auto res = cli.Get("/test");
  14798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14799. ASSERT_EQ(StatusCode::OK_200, res->status);
  14800. }
  14801. // Test verify_hostname on every backend: a host is named by a SAN only
  14802. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14803. using namespace httplib::tls;
  14804. // We need a running server to test against
  14805. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14806. ASSERT_TRUE(svr.is_valid());
  14807. svr.Get("/test", [](const Request &, Response &res) {
  14808. res.set_content("ok", "text/plain");
  14809. });
  14810. thread t([&]() { svr.listen(HOST, PORT); });
  14811. auto se = detail::scope_exit([&] {
  14812. svr.stop();
  14813. t.join();
  14814. });
  14815. svr.wait_until_ready();
  14816. bool verify_callback_called = false;
  14817. bool verify_result_wrong = false;
  14818. SSLClient cli(HOST, PORT);
  14819. cli.enable_server_certificate_verification(true);
  14820. cli.set_ca_cert_path(CA_CERT_FILE);
  14821. cli.set_connection_timeout(5);
  14822. // Note: Test certificate has CN="Common Name", not "localhost"
  14823. bool verify_result_cn = false;
  14824. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14825. verify_callback_called = true;
  14826. if (!ctx.cert) return false;
  14827. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14828. verify_result_cn = ctx.check_hostname("Common Name");
  14829. // Test 2: wrong hostname should not match
  14830. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14831. return true; // Accept for the purpose of this test
  14832. });
  14833. auto res = cli.Get("/test");
  14834. // The request may succeed or fail depending on cert configuration
  14835. // but the callback should have been called
  14836. ASSERT_TRUE(verify_callback_called)
  14837. << "Verify callback should have been called";
  14838. EXPECT_FALSE(verify_result_cn)
  14839. << "verify_hostname must not match the certificate CN (no SAN)";
  14840. // Wrong hostname should not match
  14841. EXPECT_FALSE(verify_result_wrong)
  14842. << "verify_hostname should not match 'wronghost.example.com'";
  14843. }
  14844. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14845. // backend verifies it.
  14846. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14847. // Certificate CN is "localhost" and it carries no SAN.
  14848. SSLServer svr(SERVER_CERT_DNS_CN_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. auto port = svr.bind_to_any_port(HOST);
  14854. thread t([&]() { svr.listen_after_bind(); });
  14855. auto se = detail::scope_exit([&] {
  14856. svr.stop();
  14857. t.join();
  14858. });
  14859. svr.wait_until_ready();
  14860. SSLClient cli("localhost", port);
  14861. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14862. cli.enable_server_certificate_verification(true);
  14863. cli.set_connection_timeout(5);
  14864. auto res = cli.Get("/test");
  14865. ASSERT_FALSE(res);
  14866. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14867. // The same certificate is accepted once host name verification is off, so the
  14868. // failure above is the host name and not the chain.
  14869. cli.enable_server_hostname_verification(false);
  14870. res = cli.Get("/test");
  14871. ASSERT_TRUE(res) << to_string(res.error());
  14872. EXPECT_EQ(StatusCode::OK_200, res->status);
  14873. }
  14874. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14875. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14876. // X509_check_ip behavior and must hold for every backend.
  14877. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14878. using namespace httplib::tls;
  14879. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14880. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14881. ASSERT_TRUE(svr.is_valid());
  14882. svr.Get("/test", [](const Request &, Response &res) {
  14883. res.set_content("ok", "text/plain");
  14884. });
  14885. thread t([&]() { svr.listen(HOST, PORT); });
  14886. auto se = detail::scope_exit([&] {
  14887. svr.stop();
  14888. t.join();
  14889. });
  14890. svr.wait_until_ready();
  14891. bool verify_callback_called = false;
  14892. bool ip_matched_via_cn = true;
  14893. SSLClient cli(HOST, PORT);
  14894. cli.enable_server_certificate_verification(true);
  14895. cli.set_ca_cert_path(CA_CERT_FILE);
  14896. cli.set_connection_timeout(5);
  14897. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14898. verify_callback_called = true;
  14899. if (!ctx.cert) return false;
  14900. // The IP appears only in the CN, so it must NOT be accepted.
  14901. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14902. return true; // Accept for the purpose of this test
  14903. });
  14904. cli.Get("/test");
  14905. ASSERT_TRUE(verify_callback_called)
  14906. << "Verify callback should have been called";
  14907. EXPECT_FALSE(ip_matched_via_cn)
  14908. << "An IP host must not be authenticated via the certificate CN";
  14909. }
  14910. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14911. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14912. using namespace httplib::tls;
  14913. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14914. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14915. ASSERT_TRUE(svr.is_valid());
  14916. svr.Get("/test", [](const Request &, Response &res) {
  14917. res.set_content("ok", "text/plain");
  14918. });
  14919. thread t([&]() { svr.listen(HOST, PORT); });
  14920. auto se = detail::scope_exit([&] {
  14921. svr.stop();
  14922. t.join();
  14923. });
  14924. svr.wait_until_ready();
  14925. bool verify_callback_called = false;
  14926. bool san_matched = false;
  14927. bool wrong_ipv6_matched = true;
  14928. bool cn_ipv6_matched = true;
  14929. SSLClient cli(HOST, PORT);
  14930. cli.enable_server_certificate_verification(true);
  14931. cli.set_ca_cert_path(CA_CERT_FILE);
  14932. cli.set_connection_timeout(5);
  14933. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14934. verify_callback_called = true;
  14935. if (!ctx.cert) return false;
  14936. // Matches the IPv6 iPAddress SAN.
  14937. san_matched = ctx.check_hostname("2001:db8::1");
  14938. // A different IPv6 address must not match.
  14939. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14940. // "::1" lives only in the CN, so it must not be accepted.
  14941. cn_ipv6_matched = ctx.check_hostname("::1");
  14942. return true; // Accept for the purpose of this test
  14943. });
  14944. cli.Get("/test");
  14945. ASSERT_TRUE(verify_callback_called)
  14946. << "Verify callback should have been called";
  14947. EXPECT_TRUE(san_matched)
  14948. << "verify_hostname should match an IPv6 iPAddress SAN";
  14949. EXPECT_FALSE(wrong_ipv6_matched)
  14950. << "verify_hostname should not match a non-matching IPv6 address";
  14951. EXPECT_FALSE(cn_ipv6_matched)
  14952. << "An IPv6 host must not be authenticated via the certificate CN";
  14953. }
  14954. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14955. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14956. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14957. using namespace httplib::tls;
  14958. // SANs: DNS:a.zz, IP:42.46.122.122
  14959. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14960. ASSERT_TRUE(svr.is_valid());
  14961. svr.Get("/test", [](const Request &, Response &res) {
  14962. res.set_content("ok", "text/plain");
  14963. });
  14964. auto port = svr.bind_to_any_port(HOST);
  14965. thread t([&]() { svr.listen_after_bind(); });
  14966. auto se = detail::scope_exit([&] {
  14967. svr.stop();
  14968. t.join();
  14969. });
  14970. svr.wait_until_ready();
  14971. bool verify_callback_called = false;
  14972. bool dns_san_matched = false;
  14973. bool ip_san_matched = false;
  14974. bool ip_matched_via_dns_san = true;
  14975. bool dns_matched_via_ip_san = true;
  14976. bool cn_matched_next_to_dns_san = true;
  14977. SSLClient cli(HOST, port);
  14978. cli.enable_server_certificate_verification(true);
  14979. cli.set_ca_cert_path(CA_CERT_FILE);
  14980. cli.set_connection_timeout(5);
  14981. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14982. verify_callback_called = true;
  14983. if (!ctx.cert) return false;
  14984. dns_san_matched = ctx.check_hostname("a.zz");
  14985. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14986. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14987. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14988. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14989. return true; // Accept for the purpose of this test
  14990. });
  14991. cli.Get("/test");
  14992. ASSERT_TRUE(verify_callback_called)
  14993. << "Verify callback should have been called";
  14994. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14995. EXPECT_TRUE(ip_san_matched)
  14996. << "verify_hostname should match an iPAddress SAN";
  14997. EXPECT_FALSE(ip_matched_via_dns_san)
  14998. << "An IP host must not be authenticated via a dNSName SAN";
  14999. EXPECT_FALSE(dns_matched_via_ip_san)
  15000. << "A DNS host must not be authenticated via an iPAddress SAN";
  15001. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15002. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15003. }
  15004. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15005. // "www.*.example.test" names one host and not every host under example.test.
  15006. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15007. using namespace httplib::tls;
  15008. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15009. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15010. ASSERT_TRUE(svr.is_valid());
  15011. svr.Get("/test", [](const Request &, Response &res) {
  15012. res.set_content("ok", "text/plain");
  15013. });
  15014. auto port = svr.bind_to_any_port(HOST);
  15015. thread t([&]() { svr.listen_after_bind(); });
  15016. auto se = detail::scope_exit([&] {
  15017. svr.stop();
  15018. t.join();
  15019. });
  15020. svr.wait_until_ready();
  15021. bool verify_callback_called = false;
  15022. bool leftmost_wildcard_matched = false;
  15023. bool wildcard_spanned_labels = true;
  15024. bool inner_wildcard_matched = true;
  15025. SSLClient cli(HOST, port);
  15026. cli.enable_server_certificate_verification(true);
  15027. cli.set_ca_cert_path(CA_CERT_FILE);
  15028. cli.set_connection_timeout(5);
  15029. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15030. verify_callback_called = true;
  15031. if (!ctx.cert) return false;
  15032. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15033. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15034. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15035. return true; // Accept for the purpose of this test
  15036. });
  15037. cli.Get("/test");
  15038. ASSERT_TRUE(verify_callback_called)
  15039. << "Verify callback should have been called";
  15040. EXPECT_TRUE(leftmost_wildcard_matched)
  15041. << "A leftmost wildcard should match a single label";
  15042. EXPECT_FALSE(wildcard_spanned_labels)
  15043. << "A wildcard label must not match more than one label";
  15044. EXPECT_FALSE(inner_wildcard_matched)
  15045. << "A wildcard outside the leftmost label must not be honoured";
  15046. }
  15047. // sans() must report each SAN entry under its own type.
  15048. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15049. using namespace httplib::tls;
  15050. // SANs: DNS:a.zz, IP:42.46.122.122
  15051. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15052. ASSERT_TRUE(svr.is_valid());
  15053. svr.Get("/test", [](const Request &, Response &res) {
  15054. res.set_content("ok", "text/plain");
  15055. });
  15056. auto port = svr.bind_to_any_port(HOST);
  15057. thread t([&]() { svr.listen_after_bind(); });
  15058. auto se = detail::scope_exit([&] {
  15059. svr.stop();
  15060. t.join();
  15061. });
  15062. svr.wait_until_ready();
  15063. bool verify_callback_called = false;
  15064. std::vector<SanEntry> sans;
  15065. SSLClient cli(HOST, port);
  15066. cli.enable_server_certificate_verification(true);
  15067. cli.set_ca_cert_path(CA_CERT_FILE);
  15068. cli.set_connection_timeout(5);
  15069. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15070. verify_callback_called = true;
  15071. if (!ctx.cert) return false;
  15072. sans = ctx.sans();
  15073. return true; // Accept for the purpose of this test
  15074. });
  15075. cli.Get("/test");
  15076. ASSERT_TRUE(verify_callback_called)
  15077. << "Verify callback should have been called";
  15078. auto has_san = [&](SanType type, const std::string &value) {
  15079. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15080. return san.type == type && san.value == value;
  15081. });
  15082. };
  15083. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15084. << "sans() should report the dNSName SAN";
  15085. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15086. << "sans() should report the iPAddress SAN";
  15087. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15088. << "sans() must not report the dNSName SAN as an address";
  15089. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15090. << "sans() must not report the iPAddress SAN as a DNS name";
  15091. }
  15092. #endif
  15093. // mbedTLS-specific callback constructor test
  15094. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15095. #ifdef CPPHTTPLIB_SSL_ENABLED
  15096. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15097. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15098. ASSERT_TRUE(svr.is_valid());
  15099. // Set up a handler to verify client certificate is present
  15100. bool client_cert_verified = false;
  15101. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15102. // Verify that client certificate was provided
  15103. client_cert_verified = true;
  15104. res.set_content("success", "text/plain");
  15105. });
  15106. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15107. auto se = detail::scope_exit([&] {
  15108. svr.stop();
  15109. t.join();
  15110. ASSERT_FALSE(svr.is_running());
  15111. });
  15112. svr.wait_until_ready();
  15113. // Client with certificate
  15114. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15115. cli.enable_server_certificate_verification(false);
  15116. cli.set_connection_timeout(30);
  15117. auto res = cli.Get("/test");
  15118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15119. ASSERT_EQ(StatusCode::OK_200, res->status);
  15120. ASSERT_TRUE(client_cert_verified);
  15121. EXPECT_EQ("success", res->body);
  15122. }
  15123. #endif
  15124. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15125. // backends
  15126. #ifdef CPPHTTPLIB_SSL_ENABLED
  15127. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15128. using namespace httplib::tls;
  15129. // Test that when client CA cert file is provided,
  15130. // the server properly requests and validates client certificates
  15131. // Create a server with client authentication
  15132. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15133. ASSERT_TRUE(svr.is_valid());
  15134. bool handler_called = false;
  15135. svr.Get("/test", [&](const Request &req, Response &res) {
  15136. handler_called = true;
  15137. // Verify that a client certificate was provided
  15138. auto cert = req.peer_cert();
  15139. ASSERT_TRUE(static_cast<bool>(cert));
  15140. // Get the issuer name
  15141. std::string issuer_str = cert.issuer_name();
  15142. ASSERT_FALSE(issuer_str.empty());
  15143. // The client certificate should be issued by our test CA
  15144. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15145. res.set_content("authenticated", "text/plain");
  15146. });
  15147. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15148. auto se = detail::scope_exit([&] {
  15149. svr.stop();
  15150. t.join();
  15151. ASSERT_FALSE(svr.is_running());
  15152. });
  15153. svr.wait_until_ready();
  15154. // Connect with a client certificate issued by the CA
  15155. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15156. cli.enable_server_certificate_verification(false);
  15157. cli.set_connection_timeout(30);
  15158. auto res = cli.Get("/test");
  15159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15160. ASSERT_EQ(StatusCode::OK_200, res->status);
  15161. ASSERT_TRUE(handler_called);
  15162. EXPECT_EQ("authenticated", res->body);
  15163. }
  15164. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15165. using namespace httplib::tls;
  15166. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15167. ASSERT_TRUE(svr.is_valid());
  15168. svr.Get("/test", [](const Request &, Response &res) {
  15169. res.set_content("ok", "text/plain");
  15170. });
  15171. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15172. auto se = detail::scope_exit([&] {
  15173. svr.stop();
  15174. t.join();
  15175. });
  15176. svr.wait_until_ready();
  15177. SSLClient cli(HOST, PORT);
  15178. cli.enable_server_certificate_verification(false);
  15179. cli.set_connection_timeout(30);
  15180. bool cert_checked = false;
  15181. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15182. if (ctx.cert) {
  15183. auto sans = ctx.sans();
  15184. // Test certificate may or may not have SANs - just verify the API
  15185. // works If SANs exist, verify the types are valid
  15186. for (const auto &san : sans) {
  15187. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15188. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15189. san.type == SanType::OTHER);
  15190. EXPECT_FALSE(san.value.empty());
  15191. }
  15192. cert_checked = true;
  15193. }
  15194. return true;
  15195. });
  15196. auto res = cli.Get("/test");
  15197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15198. EXPECT_TRUE(cert_checked);
  15199. }
  15200. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15201. using namespace httplib::tls;
  15202. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15203. ASSERT_TRUE(svr.is_valid());
  15204. svr.Get("/test", [](const Request &, Response &res) {
  15205. res.set_content("ok", "text/plain");
  15206. });
  15207. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15208. auto se = detail::scope_exit([&] {
  15209. svr.stop();
  15210. t.join();
  15211. });
  15212. svr.wait_until_ready();
  15213. SSLClient cli(HOST, PORT);
  15214. cli.enable_server_certificate_verification(false);
  15215. cli.set_connection_timeout(30);
  15216. bool validity_checked = false;
  15217. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15218. if (ctx.cert) {
  15219. time_t not_before = 0, not_after = 0;
  15220. bool result = ctx.validity(not_before, not_after);
  15221. EXPECT_TRUE(result);
  15222. // Verify that not_before < now < not_after for a valid cert
  15223. time_t now = time(nullptr);
  15224. EXPECT_LT(not_before, now);
  15225. EXPECT_GT(not_after, now);
  15226. validity_checked = true;
  15227. }
  15228. return true;
  15229. });
  15230. auto res = cli.Get("/test");
  15231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15232. EXPECT_TRUE(validity_checked);
  15233. }
  15234. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15235. using namespace httplib::tls;
  15236. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15237. ASSERT_TRUE(svr.is_valid());
  15238. svr.Get("/test", [](const Request &, Response &res) {
  15239. res.set_content("ok", "text/plain");
  15240. });
  15241. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15242. auto se = detail::scope_exit([&] {
  15243. svr.stop();
  15244. t.join();
  15245. });
  15246. svr.wait_until_ready();
  15247. SSLClient cli(HOST, PORT);
  15248. cli.enable_server_certificate_verification(false);
  15249. cli.set_connection_timeout(30);
  15250. bool serial_checked = false;
  15251. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15252. if (ctx.cert) {
  15253. std::string serial = ctx.serial();
  15254. EXPECT_FALSE(serial.empty());
  15255. // Serial should be a hex string
  15256. for (char c : serial) {
  15257. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15258. (c >= 'a' && c <= 'f'));
  15259. }
  15260. serial_checked = true;
  15261. }
  15262. return true;
  15263. });
  15264. auto res = cli.Get("/test");
  15265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15266. EXPECT_TRUE(serial_checked);
  15267. }
  15268. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15269. // Test 1: Valid CA file - no error should be recorded
  15270. {
  15271. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15272. CLIENT_CA_CERT_FILE);
  15273. ASSERT_TRUE(svr.is_valid());
  15274. // With valid setup, last_ssl_error should be 0
  15275. EXPECT_EQ(0, svr.ssl_last_error());
  15276. }
  15277. // Test 2: Invalid CA file content
  15278. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15279. {
  15280. // Create a temporary file with completely invalid content
  15281. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15282. {
  15283. std::ofstream ofs(temp_invalid_ca);
  15284. ofs << "This is not a certificate file at all\n";
  15285. ofs << "Just plain text content\n";
  15286. }
  15287. // Create server with invalid CA file
  15288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15289. // Clean up temporary file
  15290. std::remove(temp_invalid_ca);
  15291. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15292. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15293. // Note: SSL_CTX_load_verify_locations typically fails first,
  15294. // but our error handling code path is still exercised
  15295. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15296. }
  15297. }
  15298. TEST(VerifyCallbackTest, VerifyContextFields) {
  15299. using namespace httplib::tls;
  15300. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15301. ASSERT_TRUE(svr.is_valid());
  15302. svr.Get("/test", [](const Request &, Response &res) {
  15303. res.set_content("ok", "text/plain");
  15304. });
  15305. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15306. auto se = detail::scope_exit([&] {
  15307. svr.stop();
  15308. t.join();
  15309. });
  15310. svr.wait_until_ready();
  15311. SSLClient cli(HOST, PORT);
  15312. cli.enable_server_certificate_verification(false);
  15313. cli.set_connection_timeout(30);
  15314. int callback_count = 0;
  15315. bool saw_leaf_cert = false;
  15316. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15317. if (ctx.cert) {
  15318. callback_count++;
  15319. // We should see at least one certificate (the leaf)
  15320. std::string cn = ctx.subject_cn();
  15321. if (!cn.empty()) { saw_leaf_cert = true; }
  15322. // Verify context fields are populated
  15323. EXPECT_NE(ctx.session, nullptr);
  15324. EXPECT_GE(ctx.depth, 0);
  15325. }
  15326. return true;
  15327. });
  15328. auto res = cli.Get("/test");
  15329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15330. EXPECT_GT(callback_count, 0);
  15331. EXPECT_TRUE(saw_leaf_cert);
  15332. }
  15333. // A verifier that accepts runs alongside the built-in verification, and is the
  15334. // only check once that is turned off.
  15335. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15336. using namespace httplib::tls;
  15337. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15338. ASSERT_TRUE(svr.is_valid());
  15339. svr.Get("/test", [](const Request &, Response &res) {
  15340. res.set_content("ok", "text/plain");
  15341. });
  15342. auto port = svr.bind_to_any_port(HOST);
  15343. thread t([&]() { svr.listen_after_bind(); });
  15344. auto se = detail::scope_exit([&] {
  15345. svr.stop();
  15346. t.join();
  15347. });
  15348. svr.wait_until_ready();
  15349. SSLClient cli(HOST, port);
  15350. cli.enable_server_hostname_verification(false);
  15351. auto calls = 0;
  15352. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15353. calls++;
  15354. return true;
  15355. });
  15356. // cert.pem is not trusted
  15357. auto res = cli.Get("/test");
  15358. ASSERT_FALSE(res);
  15359. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15360. EXPECT_GT(calls, 0);
  15361. cli.enable_server_certificate_verification(false);
  15362. res = cli.Get("/test");
  15363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15364. EXPECT_EQ("ok", res->body);
  15365. }
  15366. // A verifier belongs to the client that set it, not to the thread that set it.
  15367. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15368. using namespace httplib::tls;
  15369. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15370. ASSERT_TRUE(svr.is_valid());
  15371. svr.Get("/test", [](const Request &, Response &res) {
  15372. res.set_content("ok", "text/plain");
  15373. });
  15374. auto port = svr.bind_to_any_port(HOST);
  15375. thread t([&]() { svr.listen_after_bind(); });
  15376. auto se = detail::scope_exit([&] {
  15377. svr.stop();
  15378. t.join();
  15379. });
  15380. svr.wait_until_ready();
  15381. auto rejecting_calls = 0;
  15382. SSLClient rejecting(HOST, port);
  15383. rejecting.enable_server_certificate_verification(false);
  15384. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15385. rejecting_calls++;
  15386. return false;
  15387. });
  15388. auto accepting_calls = 0;
  15389. SSLClient accepting(HOST, port);
  15390. accepting.enable_server_certificate_verification(false);
  15391. // Set on another thread than the requests below.
  15392. thread([&]() {
  15393. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15394. accepting_calls++;
  15395. return true;
  15396. });
  15397. }).join();
  15398. // Requested on another thread than the verifier was set on.
  15399. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15400. EXPECT_GT(rejecting_calls, 0);
  15401. auto res = accepting.Get("/test");
  15402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15403. EXPECT_GT(accepting_calls, 0);
  15404. }
  15405. // A verifier replaced while a handshake runs it lives until it returns.
  15406. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15407. using namespace httplib::tls;
  15408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15409. ASSERT_TRUE(svr.is_valid());
  15410. svr.Get("/test", [](const Request &, Response &res) {
  15411. res.set_content("ok", "text/plain");
  15412. });
  15413. auto port = svr.bind_to_any_port(HOST);
  15414. thread t([&]() { svr.listen_after_bind(); });
  15415. auto se = detail::scope_exit([&] {
  15416. svr.stop();
  15417. t.join();
  15418. });
  15419. svr.wait_until_ready();
  15420. SSLClient cli(HOST, port);
  15421. cli.enable_server_certificate_verification(false);
  15422. std::promise<void> entered;
  15423. std::promise<void> replaced;
  15424. auto replaced_future = replaced.get_future();
  15425. auto first_call = true;
  15426. // Long enough to live on the heap
  15427. std::string expected(64, 'v');
  15428. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15429. if (first_call) {
  15430. first_call = false;
  15431. entered.set_value();
  15432. replaced_future.wait();
  15433. }
  15434. return expected == std::string(64, 'v');
  15435. });
  15436. thread request([&]() {
  15437. auto res = cli.Get("/test");
  15438. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15439. });
  15440. entered.get_future().wait();
  15441. cli.set_server_certificate_verifier(
  15442. [](const VerifyContext &) { return true; });
  15443. replaced.set_value();
  15444. request.join();
  15445. }
  15446. // VerifyContext::session is the same handle the other tls:: functions take.
  15447. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15448. using namespace httplib::tls;
  15449. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15450. ASSERT_TRUE(svr.is_valid());
  15451. svr.Get("/test", [](const Request &, Response &res) {
  15452. res.set_content("ok", "text/plain");
  15453. });
  15454. auto port = svr.bind_to_any_port(HOST);
  15455. thread t([&]() { svr.listen_after_bind(); });
  15456. auto se = detail::scope_exit([&] {
  15457. svr.stop();
  15458. t.join();
  15459. });
  15460. svr.wait_until_ready();
  15461. SSLClient cli(HOST, port);
  15462. cli.enable_server_certificate_verification(false);
  15463. session_t verifier_session = nullptr;
  15464. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15465. verifier_session = ctx.session;
  15466. return true;
  15467. });
  15468. session_t session_verifier_session = nullptr;
  15469. cli.set_session_verifier([&](session_t session) {
  15470. session_verifier_session = session;
  15471. return SSLVerifierResponse::NoDecisionMade;
  15472. });
  15473. auto res = cli.Get("/test");
  15474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15475. EXPECT_NE(nullptr, verifier_session);
  15476. EXPECT_EQ(session_verifier_session, verifier_session);
  15477. }
  15478. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15479. using httplib::tls::TlsError;
  15480. // Test that verify_error_to_string returns empty for success
  15481. std::string success_str = TlsError::verify_error_to_string(0);
  15482. EXPECT_TRUE(success_str.empty());
  15483. // Test that verify_error_to_string returns non-empty for error codes
  15484. // Using a common error code (certificate expired)
  15485. std::string error_str =
  15486. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15487. EXPECT_FALSE(error_str.empty());
  15488. }
  15489. TEST(SessionVerifierTest, CertificateAccepted) {
  15490. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15491. ASSERT_TRUE(svr.is_valid());
  15492. svr.Get("/test", [](const Request &, Response &res) {
  15493. res.set_content("ok", "text/plain");
  15494. });
  15495. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15496. auto se = detail::scope_exit([&] {
  15497. svr.stop();
  15498. t.join();
  15499. });
  15500. svr.wait_until_ready();
  15501. SSLClient cli(HOST, PORT);
  15502. cli.enable_server_certificate_verification(false);
  15503. cli.set_connection_timeout(30);
  15504. bool callback_called = false;
  15505. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15506. EXPECT_NE(session, nullptr);
  15507. callback_called = true;
  15508. return SSLVerifierResponse::CertificateAccepted;
  15509. });
  15510. auto res = cli.Get("/test");
  15511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15512. EXPECT_EQ(200, res->status);
  15513. EXPECT_TRUE(callback_called);
  15514. }
  15515. TEST(SessionVerifierTest, CertificateRejected) {
  15516. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15517. ASSERT_TRUE(svr.is_valid());
  15518. svr.Get("/test", [](const Request &, Response &res) {
  15519. res.set_content("ok", "text/plain");
  15520. });
  15521. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15522. auto se = detail::scope_exit([&] {
  15523. svr.stop();
  15524. t.join();
  15525. });
  15526. svr.wait_until_ready();
  15527. SSLClient cli(HOST, PORT);
  15528. cli.enable_server_certificate_verification(false);
  15529. cli.set_connection_timeout(30);
  15530. bool callback_called = false;
  15531. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15532. EXPECT_NE(session, nullptr);
  15533. callback_called = true;
  15534. return SSLVerifierResponse::CertificateRejected;
  15535. });
  15536. auto res = cli.Get("/test");
  15537. EXPECT_FALSE(res);
  15538. EXPECT_TRUE(callback_called);
  15539. }
  15540. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15542. ASSERT_TRUE(svr.is_valid());
  15543. svr.Get("/test", [](const Request &, Response &res) {
  15544. res.set_content("ok", "text/plain");
  15545. });
  15546. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15547. auto se = detail::scope_exit([&] {
  15548. svr.stop();
  15549. t.join();
  15550. });
  15551. svr.wait_until_ready();
  15552. // NoDecisionMade with verification disabled should succeed (no default check)
  15553. SSLClient cli(HOST, PORT);
  15554. cli.enable_server_certificate_verification(false);
  15555. cli.set_connection_timeout(30);
  15556. bool callback_called = false;
  15557. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15558. EXPECT_NE(session, nullptr);
  15559. callback_called = true;
  15560. return SSLVerifierResponse::NoDecisionMade;
  15561. });
  15562. auto res = cli.Get("/test");
  15563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15564. EXPECT_EQ(200, res->status);
  15565. EXPECT_TRUE(callback_called);
  15566. }
  15567. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15568. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15569. ASSERT_TRUE(svr.is_valid());
  15570. svr.Get("/test", [](const Request &, Response &res) {
  15571. res.set_content("ok", "text/plain");
  15572. });
  15573. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15574. auto se = detail::scope_exit([&] {
  15575. svr.stop();
  15576. t.join();
  15577. });
  15578. svr.wait_until_ready();
  15579. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15580. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15581. // so we only check that the request fails, not whether the callback was
  15582. // called.
  15583. SSLClient cli(HOST, PORT);
  15584. cli.enable_server_certificate_verification(true);
  15585. cli.set_connection_timeout(30);
  15586. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15587. EXPECT_NE(session, nullptr);
  15588. return SSLVerifierResponse::NoDecisionMade;
  15589. });
  15590. auto res = cli.Get("/test");
  15591. EXPECT_FALSE(res);
  15592. }
  15593. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15594. // Test SSL server using PemMemory constructor with client CA certificates
  15595. // Read PEM files
  15596. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15597. read_file(SERVER_CERT_FILE, server_cert_pem);
  15598. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15599. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15600. // Create SSLServer with PemMemory constructor including client CA
  15601. SSLServer::PemMemory server_pem = {
  15602. server_cert_pem.c_str(),
  15603. server_cert_pem.size(),
  15604. server_key_pem.c_str(),
  15605. server_key_pem.size(),
  15606. client_ca_pem.c_str(),
  15607. client_ca_pem.size(),
  15608. nullptr // no password for server key
  15609. };
  15610. SSLServer svr(server_pem);
  15611. ASSERT_TRUE(svr.is_valid());
  15612. // No SSL error should be recorded for valid setup
  15613. EXPECT_EQ(0, svr.ssl_last_error());
  15614. // Set up server endpoints
  15615. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15616. res.set_content("ok", "text/plain");
  15617. });
  15618. // Start server in a thread
  15619. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15620. svr.wait_until_ready();
  15621. // Connect with client certificate (using constructor with paths)
  15622. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15623. cli.enable_server_certificate_verification(false);
  15624. auto res = cli.Get("/test-pem-ca");
  15625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15626. EXPECT_EQ(200, res->status);
  15627. EXPECT_EQ("ok", res->body);
  15628. svr.stop();
  15629. server_thread.join();
  15630. }
  15631. #endif
  15632. #ifdef _WIN32
  15633. TEST(CleanupTest, WSACleanup) {
  15634. int ret = WSACleanup();
  15635. ASSERT_EQ(0, ret);
  15636. }
  15637. #endif
  15638. #ifndef CPPHTTPLIB_SSL_ENABLED
  15639. TEST(NoSSLSupport, SimpleInterface) {
  15640. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15641. }
  15642. #endif
  15643. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15644. TEST(InvalidScheme, SimpleInterface) {
  15645. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15646. }
  15647. #endif
  15648. TEST(NoScheme, SimpleInterface) {
  15649. Client cli("yahoo.com:80");
  15650. ASSERT_TRUE(cli.is_valid());
  15651. }
  15652. TEST(SendAPI, SimpleInterface_Online) {
  15653. Client cli("http://yahoo.com");
  15654. Request req;
  15655. req.method = "GET";
  15656. req.path = "/";
  15657. auto res = cli.send(req);
  15658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15659. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15660. }
  15661. TEST(SendAPI, WithParamsInRequest) {
  15662. Server svr;
  15663. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15664. EXPECT_TRUE(req.has_param("test"));
  15665. EXPECT_EQ("test_value", req.get_param_value("test"));
  15666. });
  15667. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15668. auto se = detail::scope_exit([&] {
  15669. svr.stop();
  15670. t.join();
  15671. ASSERT_FALSE(svr.is_running());
  15672. });
  15673. svr.wait_until_ready();
  15674. Client cli(HOST, PORT);
  15675. {
  15676. Request req;
  15677. req.method = "GET";
  15678. req.path = "/";
  15679. req.params.emplace("test", "test_value");
  15680. auto res = cli.send(req);
  15681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15682. }
  15683. {
  15684. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15686. }
  15687. }
  15688. TEST(ClientImplMethods, GetSocketTest) {
  15689. httplib::Server svr;
  15690. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15691. res.status = StatusCode::OK_200;
  15692. });
  15693. auto port = svr.bind_to_any_port("127.0.0.1");
  15694. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15695. auto se = detail::scope_exit([&] {
  15696. svr.stop();
  15697. thread.join();
  15698. ASSERT_FALSE(svr.is_running());
  15699. });
  15700. svr.wait_until_ready();
  15701. {
  15702. httplib::Client cli("127.0.0.1", port);
  15703. cli.set_keep_alive(true);
  15704. // Use the behavior of cpp-httplib of opening the connection
  15705. // only when the first request happens. If that changes,
  15706. // this test would be obsolete.
  15707. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15708. // This also implicitly tests the server. But other tests would fail much
  15709. // earlier than this one to be considered.
  15710. auto res = cli.Get("/");
  15711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15712. EXPECT_EQ(StatusCode::OK_200, res->status);
  15713. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15714. }
  15715. }
  15716. #ifdef CPPHTTPLIB_SSL_ENABLED
  15717. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15718. Client cli("http://yahoo.com");
  15719. auto res = cli.Get("/");
  15720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15721. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15722. cli.set_follow_location(true);
  15723. res = cli.Get("/");
  15724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15725. EXPECT_EQ(StatusCode::OK_200, res->status);
  15726. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15727. }
  15728. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15729. Client cli("https://yahoo.com");
  15730. auto res = cli.Get("/");
  15731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15732. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15733. cli.set_follow_location(true);
  15734. res = cli.Get("/");
  15735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15736. EXPECT_EQ(StatusCode::OK_200, res->status);
  15737. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15738. }
  15739. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15740. Client cli("https://yahoo.com");
  15741. auto res = cli.Get("/");
  15742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15743. ASSERT_FALSE(!res);
  15744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15745. ASSERT_FALSE(res == nullptr);
  15746. ASSERT_TRUE(res != nullptr);
  15747. EXPECT_EQ(Error::Success, res.error());
  15748. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15749. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15750. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15751. cli.set_follow_location(true);
  15752. res = cli.Get("/");
  15753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15754. EXPECT_EQ(Error::Success, res.error());
  15755. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15756. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15757. EXPECT_EQ(StatusCode::OK_200, res->status);
  15758. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15759. }
  15760. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15761. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15762. Client cli("https://cdnjs.cloudflare.com");
  15763. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15764. Headers{{"Accept-Encoding", "br"}});
  15765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15766. EXPECT_EQ(StatusCode::OK_200, res->status);
  15767. EXPECT_EQ(287630U, res->body.size());
  15768. EXPECT_EQ("application/javascript; charset=utf-8",
  15769. res->get_header_value("Content-Type"));
  15770. }
  15771. #endif
  15772. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15773. #undef REDIR_HOST // Silence compiler warning
  15774. #define REDIR_HOST "https://httpbingo.org"
  15775. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15776. Client cli(REDIR_HOST);
  15777. cli.set_follow_location(true);
  15778. auto res =
  15779. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15781. EXPECT_EQ(StatusCode::OK_200, res->status);
  15782. }
  15783. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15784. Client cli(REDIR_HOST);
  15785. cli.set_follow_location(true);
  15786. Params params;
  15787. params.emplace("url", "http://example.com");
  15788. params.emplace("status_code", "302");
  15789. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15791. EXPECT_EQ(StatusCode::OK_200, res->status);
  15792. }
  15793. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15794. Client cli(REDIR_HOST);
  15795. cli.set_follow_location(true);
  15796. Params params;
  15797. params.emplace("url", "http://example.com");
  15798. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15800. EXPECT_EQ(StatusCode::OK_200, res->status);
  15801. }
  15802. TEST(HttpToHttpsRedirectTest, CertFile) {
  15803. auto ssl_port = PORT + 1;
  15804. Server svr;
  15805. ASSERT_TRUE(svr.is_valid());
  15806. svr.Get("/index", [&](const Request &, Response &res) {
  15807. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15808. "/index");
  15809. svr.stop();
  15810. });
  15811. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15812. ASSERT_TRUE(ssl_svr.is_valid());
  15813. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15814. res.set_content("test", "text/plain");
  15815. ssl_svr.stop();
  15816. });
  15817. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15818. thread t2 =
  15819. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15820. auto se = detail::scope_exit([&] {
  15821. t2.join();
  15822. t.join();
  15823. ASSERT_FALSE(svr.is_running());
  15824. });
  15825. svr.wait_until_ready();
  15826. ssl_svr.wait_until_ready();
  15827. Client cli("127.0.0.1", PORT);
  15828. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15829. cli.enable_server_certificate_verification(true);
  15830. cli.set_follow_location(true);
  15831. cli.set_connection_timeout(30);
  15832. auto res = cli.Get("/index");
  15833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15834. ASSERT_EQ(StatusCode::OK_200, res->status);
  15835. }
  15836. TEST(SSLClientRedirectTest, CertFile) {
  15837. auto ssl_port = PORT + 1;
  15838. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15839. ASSERT_TRUE(ssl_svr1.is_valid());
  15840. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15841. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15842. "/index");
  15843. ssl_svr1.stop();
  15844. });
  15845. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15846. ASSERT_TRUE(ssl_svr2.is_valid());
  15847. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15848. res.set_content("test", "text/plain");
  15849. ssl_svr2.stop();
  15850. });
  15851. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15852. thread t2 =
  15853. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15854. auto se = detail::scope_exit([&] {
  15855. t2.join();
  15856. t.join();
  15857. ASSERT_FALSE(ssl_svr1.is_running());
  15858. });
  15859. ssl_svr1.wait_until_ready();
  15860. ssl_svr2.wait_until_ready();
  15861. SSLClient cli("127.0.0.1", PORT);
  15862. std::string cert;
  15863. read_file(SERVER_CERT2_FILE, cert);
  15864. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15865. cli.enable_server_certificate_verification(true);
  15866. cli.set_follow_location(true);
  15867. cli.set_connection_timeout(30);
  15868. auto res = cli.Get("/index");
  15869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15870. ASSERT_EQ(StatusCode::OK_200, res->status);
  15871. }
  15872. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15873. // another port, so the client follows it with a new client.
  15874. static Result GetThroughTlsRedirectToDifferentPort(
  15875. const std::function<void(SSLClient &)> &setup,
  15876. const char *target_cert = SERVER_CERT2_FILE,
  15877. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15878. auto ssl_port = PORT + 1;
  15879. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15880. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15881. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15882. "/index");
  15883. });
  15884. SSLServer ssl_svr2(target_cert, target_key);
  15885. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15886. res.set_content("test", "text/plain");
  15887. });
  15888. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15889. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15890. auto se = detail::scope_exit([&] {
  15891. ssl_svr2.stop();
  15892. ssl_svr1.stop();
  15893. t2.join();
  15894. t.join();
  15895. });
  15896. ssl_svr1.wait_until_ready();
  15897. ssl_svr2.wait_until_ready();
  15898. SSLClient cli("127.0.0.1", PORT);
  15899. cli.set_follow_location(true);
  15900. cli.set_connection_timeout(30);
  15901. setup(cli);
  15902. return cli.Get("/index");
  15903. }
  15904. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15905. auto calls = 0;
  15906. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15907. cli.enable_server_certificate_verification(false);
  15908. // Accept the first server only.
  15909. cli.set_session_verifier([&](tls::session_t) {
  15910. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15911. : SSLVerifierResponse::CertificateRejected;
  15912. });
  15913. });
  15914. ASSERT_FALSE(res);
  15915. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15916. EXPECT_EQ(2, calls);
  15917. }
  15918. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15919. std::string pinned;
  15920. auto res = GetThroughTlsRedirectToDifferentPort(
  15921. [&](SSLClient &cli) {
  15922. cli.enable_server_certificate_verification(false);
  15923. // Pin the first certificate seen.
  15924. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15925. if (pinned.empty()) { pinned = ctx.serial(); }
  15926. return ctx.serial() == pinned;
  15927. });
  15928. },
  15929. // A certificate other than the first server's.
  15930. SERVER_CERT_FILE);
  15931. EXPECT_FALSE(res);
  15932. EXPECT_FALSE(pinned.empty());
  15933. }
  15934. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15935. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15936. std::string cert;
  15937. read_file(SERVER_CERT2_FILE, cert);
  15938. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15939. });
  15940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15941. EXPECT_EQ(StatusCode::OK_200, res->status);
  15942. }
  15943. // The target's certificate is signed by the root CA, which the first server's
  15944. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15945. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15946. auto res = GetThroughTlsRedirectToDifferentPort(
  15947. [](SSLClient &cli) {
  15948. std::string root_ca, cert;
  15949. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15950. read_file(SERVER_CERT2_FILE, cert);
  15951. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15952. cli.load_ca_cert_store(cert.data(), cert.size());
  15953. cli.enable_server_hostname_verification(false);
  15954. },
  15955. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15957. EXPECT_EQ(StatusCode::OK_200, res->status);
  15958. }
  15959. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15960. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15961. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15962. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15963. auto res = GetThroughTlsRedirectToDifferentPort(
  15964. [](SSLClient &cli) {
  15965. std::string root_ca, cert;
  15966. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15967. read_file(SERVER_CERT2_FILE, cert);
  15968. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15969. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15970. cli.enable_server_hostname_verification(false);
  15971. },
  15972. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15973. ASSERT_FALSE(res);
  15974. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15975. }
  15976. #endif
  15977. #endif
  15978. #ifdef CPPHTTPLIB_SSL_ENABLED
  15979. // Test that set_ca_cert_store() skips system certs (consistent with
  15980. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15981. // should be trusted - system certs should NOT be loaded.
  15982. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15983. // Load a specific cert that is NOT a system CA cert
  15984. std::string cert;
  15985. read_file(SERVER_CERT2_FILE, cert);
  15986. SSLClient cli("google.com");
  15987. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15988. cli.enable_server_certificate_verification(true);
  15989. // This should FAIL because:
  15990. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15991. // 2. System certs should NOT be loaded when custom store is set
  15992. // If system certs WERE loaded, this would succeed
  15993. auto res = cli.Get("/");
  15994. ASSERT_FALSE(res);
  15995. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15996. }
  15997. // Same as above, but through the native store handle path. Regression test:
  15998. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15999. // merged system certs into the user-provided store.
  16000. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16001. std::string cert;
  16002. read_file(SERVER_CERT2_FILE, cert);
  16003. SSLClient cli("google.com");
  16004. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16005. cli.enable_server_certificate_verification(true);
  16006. auto res = cli.Get("/");
  16007. ASSERT_FALSE(res);
  16008. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16009. }
  16010. // A custom store set via the native handle must still verify a server whose
  16011. // cert it does contain.
  16012. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16013. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16014. ASSERT_TRUE(svr.is_valid());
  16015. svr.Get("/test", [&](const Request &, Response &res) {
  16016. res.set_content("test", "text/plain");
  16017. });
  16018. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16019. auto se = detail::scope_exit([&] {
  16020. svr.stop();
  16021. t.join();
  16022. ASSERT_FALSE(svr.is_running());
  16023. });
  16024. svr.wait_until_ready();
  16025. SSLClient cli("127.0.0.1", PORT);
  16026. std::string cert;
  16027. read_file(SERVER_CERT2_FILE, cert);
  16028. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16029. cli.enable_server_certificate_verification(true);
  16030. cli.set_connection_timeout(30);
  16031. auto res = cli.Get("/test");
  16032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16033. ASSERT_EQ(StatusCode::OK_200, res->status);
  16034. }
  16035. // CA certs loaded through the universal Client must be transferred to the
  16036. // client created internally for following an HTTPS redirect. Regression test:
  16037. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16038. // the CA data for redirect transfer.
  16039. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16040. auto ssl_port = PORT + 1;
  16041. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16042. ASSERT_TRUE(ssl_svr1.is_valid());
  16043. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16044. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16045. "/index");
  16046. });
  16047. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16048. ASSERT_TRUE(ssl_svr2.is_valid());
  16049. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16050. res.set_content("test", "text/plain");
  16051. });
  16052. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16053. thread t2 =
  16054. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16055. auto se = detail::scope_exit([&] {
  16056. ssl_svr2.stop();
  16057. ssl_svr1.stop();
  16058. t2.join();
  16059. t.join();
  16060. ASSERT_FALSE(ssl_svr1.is_running());
  16061. });
  16062. ssl_svr1.wait_until_ready();
  16063. ssl_svr2.wait_until_ready();
  16064. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16065. std::string cert;
  16066. read_file(SERVER_CERT2_FILE, cert);
  16067. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16068. cli.enable_server_certificate_verification(true);
  16069. cli.set_follow_location(true);
  16070. cli.set_connection_timeout(30);
  16071. auto res = cli.Get("/index");
  16072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16073. ASSERT_EQ(StatusCode::OK_200, res->status);
  16074. }
  16075. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16076. // so a host signed by a system CA verifies even though a custom CA is set
  16077. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16078. std::string cert;
  16079. read_file(SERVER_CERT2_FILE, cert);
  16080. SSLClient cli("google.com");
  16081. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16082. cli.enable_system_ca(true);
  16083. cli.enable_server_certificate_verification(true);
  16084. auto res = cli.Get("/");
  16085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16086. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16087. }
  16088. // The custom CA remains effective when combined with the system CA
  16089. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16090. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16091. ASSERT_TRUE(svr.is_valid());
  16092. svr.Get("/test", [&](const Request &, Response &res) {
  16093. res.set_content("test", "text/plain");
  16094. });
  16095. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16096. auto se = detail::scope_exit([&] {
  16097. svr.stop();
  16098. t.join();
  16099. ASSERT_FALSE(svr.is_running());
  16100. });
  16101. svr.wait_until_ready();
  16102. SSLClient cli("127.0.0.1", PORT);
  16103. std::string cert;
  16104. read_file(SERVER_CERT2_FILE, cert);
  16105. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16106. cli.enable_system_ca(true);
  16107. cli.enable_server_certificate_verification(true);
  16108. cli.set_connection_timeout(30);
  16109. auto res = cli.Get("/test");
  16110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16111. ASSERT_EQ(StatusCode::OK_200, res->status);
  16112. }
  16113. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16114. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16115. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16116. static CFDictionaryRef
  16117. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16118. const SecTrustSettingsResult *result) {
  16119. auto constraint =
  16120. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16121. &kCFTypeDictionaryValueCallBacks);
  16122. if (policy) {
  16123. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16124. }
  16125. if (policy_string) {
  16126. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16127. kCFStringEncodingUTF8);
  16128. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16129. CFRelease(str);
  16130. }
  16131. if (result) {
  16132. auto number_value = static_cast<SInt32>(*result);
  16133. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16134. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16135. CFRelease(number);
  16136. }
  16137. return constraint;
  16138. }
  16139. static SecTrustSettingsResult
  16140. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16141. auto trust_settings =
  16142. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16143. for (auto constraint : constraints) {
  16144. CFArrayAppendValue(trust_settings, constraint);
  16145. CFRelease(constraint);
  16146. }
  16147. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16148. CFRelease(trust_settings);
  16149. return result;
  16150. }
  16151. // The system CA loader takes a Keychain certificate as a trusted root only
  16152. // when its Trust Settings say so for SSL, not merely because it has some.
  16153. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16154. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16155. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16156. const auto deny = kSecTrustSettingsResultDeny;
  16157. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16158. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16159. auto x509_policy = SecPolicyCreateBasicX509();
  16160. // "Always Trust", which stores no constraint at all
  16161. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16162. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16163. ssl_trust_settings_result(
  16164. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16165. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16166. ssl_trust_settings_result(
  16167. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16168. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16169. ssl_trust_settings_result(
  16170. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16171. // "Never Trust", for everything or for SSL
  16172. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16173. ssl_trust_settings_result(
  16174. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16175. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16176. ssl_trust_settings_result(
  16177. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16178. // Trusted for another policy, for one host, or not at all
  16179. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16180. ssl_trust_settings_result(
  16181. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16182. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16183. ssl_trust_settings_result({make_usage_constraint(
  16184. ssl_policy, "www.example.com", &trust_root)}));
  16185. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16186. ssl_trust_settings_result(
  16187. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16188. // The first constraint that applies to SSL decides
  16189. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16190. ssl_trust_settings_result(
  16191. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16192. make_usage_constraint(nullptr, nullptr, &deny)}));
  16193. CFRelease(x509_policy);
  16194. CFRelease(ssl_policy);
  16195. }
  16196. #endif
  16197. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16198. // skip chain verification entirely (only the certificate identity was
  16199. // checked), so a server presenting an untrusted certificate with a matching
  16200. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16201. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16202. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16203. ASSERT_TRUE(svr.is_valid());
  16204. svr.Get("/test", [&](const Request &, Response &res) {
  16205. res.set_content("test", "text/plain");
  16206. });
  16207. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16208. auto se = detail::scope_exit([&] {
  16209. svr.stop();
  16210. t.join();
  16211. ASSERT_FALSE(svr.is_running());
  16212. });
  16213. svr.wait_until_ready();
  16214. SSLClient cli("127.0.0.1", PORT);
  16215. std::string cert;
  16216. // A trusted CA that did not sign the server certificate. The server cert
  16217. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16218. // this connection.
  16219. read_file(CLIENT_CA_CERT_FILE, cert);
  16220. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16221. cli.enable_server_certificate_verification(true);
  16222. cli.set_connection_timeout(30);
  16223. auto res = cli.Get("/test");
  16224. ASSERT_FALSE(res);
  16225. }
  16226. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16227. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16228. // CA that failed to come through fails verification instead of trusting them.
  16229. // (wolfSSL does not list the system CAs it loaded.)
  16230. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16231. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16232. ASSERT_TRUE(svr.is_valid());
  16233. auto port = svr.bind_to_any_port("127.0.0.1");
  16234. ASSERT_LT(0, port);
  16235. thread t = thread([&] { svr.listen_after_bind(); });
  16236. auto se = detail::scope_exit([&] {
  16237. svr.stop();
  16238. t.join();
  16239. ASSERT_FALSE(svr.is_running());
  16240. });
  16241. svr.wait_until_ready();
  16242. // The CAs a client trusts once its first request has loaded them
  16243. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16244. Client cli("https://127.0.0.1:" + std::to_string(port));
  16245. setup(cli);
  16246. cli.Get("/");
  16247. return tls::get_ca_names(cli.tls_context()).size();
  16248. };
  16249. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16250. EXPECT_EQ(0u,
  16251. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16252. }
  16253. #endif
  16254. // A TLS setting changed between requests applies to the next one, not just to
  16255. // the next connection
  16256. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16257. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16258. ASSERT_TRUE(svr.is_valid());
  16259. svr.Get("/", [](const Request &req, Response &res) {
  16260. res.set_content(std::to_string(req.remote_port), "text/plain");
  16261. });
  16262. auto port = svr.bind_to_any_port("127.0.0.1");
  16263. ASSERT_LT(0, port);
  16264. thread t = thread([&] { svr.listen_after_bind(); });
  16265. auto se = detail::scope_exit([&] {
  16266. svr.stop();
  16267. t.join();
  16268. ASSERT_FALSE(svr.is_running());
  16269. });
  16270. svr.wait_until_ready();
  16271. SSLClient cli("127.0.0.1", port);
  16272. cli.set_keep_alive(true);
  16273. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16274. cli.enable_server_certificate_verification(false);
  16275. // The port the request went out from, so a new one means a new connection
  16276. auto client_port = [&] {
  16277. auto res = cli.Get("/");
  16278. return res ? res->body : std::string();
  16279. };
  16280. auto last = client_port();
  16281. ASSERT_FALSE(last.empty());
  16282. // Setting a value it already has keeps the connection
  16283. cli.enable_server_certificate_verification(false);
  16284. cli.enable_server_hostname_verification(true);
  16285. EXPECT_EQ(last, client_port());
  16286. cli.enable_server_certificate_verification(true);
  16287. auto res = cli.Get("/");
  16288. EXPECT_FALSE(res);
  16289. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16290. std::string ca;
  16291. read_file(SERVER_CERT2_FILE, ca);
  16292. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16293. last = client_port();
  16294. ASSERT_FALSE(last.empty());
  16295. std::vector<std::function<void()>> setters = {
  16296. [&] { cli.enable_server_hostname_verification(false); },
  16297. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16298. [&] {
  16299. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16300. },
  16301. [&] {
  16302. cli.set_server_certificate_verifier(
  16303. [](const tls::VerifyContext &) { return true; });
  16304. },
  16305. [&] {
  16306. cli.set_session_verifier(
  16307. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16308. },
  16309. };
  16310. for (const auto &setter : setters) {
  16311. setter();
  16312. auto next = client_port();
  16313. ASSERT_FALSE(next.empty());
  16314. EXPECT_NE(last, next);
  16315. last = next;
  16316. }
  16317. cli.set_session_verifier(
  16318. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16319. auto handle = cli.open_stream("GET", "/");
  16320. EXPECT_FALSE(handle.is_valid());
  16321. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16322. }
  16323. // A PEM given to create_ca_store() needs no NUL after it
  16324. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16325. std::string pem;
  16326. read_file(SERVER_CERT2_FILE, pem);
  16327. auto buf = pem + "X";
  16328. auto store = tls::create_ca_store(buf.data(), pem.size());
  16329. EXPECT_TRUE(store != nullptr);
  16330. SSLClient cli("localhost");
  16331. cli.set_ca_cert_store(store);
  16332. }
  16333. // enable_system_ca(false) prevents system CA loading entirely
  16334. TEST(SSLClientTest, DisableSystemCa_Online) {
  16335. SSLClient cli("google.com");
  16336. cli.enable_system_ca(false);
  16337. cli.enable_server_certificate_verification(true);
  16338. auto res = cli.Get("/");
  16339. ASSERT_FALSE(res);
  16340. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16341. // itself when the CA chain is empty
  16342. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16343. res.error() == Error::SSLConnection);
  16344. }
  16345. // The universal Client forwards enable_system_ca()
  16346. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16347. std::string cert;
  16348. read_file(SERVER_CERT2_FILE, cert);
  16349. Client cli("https://google.com");
  16350. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16351. cli.enable_system_ca(true);
  16352. cli.enable_server_certificate_verification(true);
  16353. auto res = cli.Get("/");
  16354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16355. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16356. }
  16357. // The system CA policy must carry over to the client created internally for
  16358. // following a cross-host HTTPS redirect
  16359. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16360. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16361. ASSERT_TRUE(svr.is_valid());
  16362. svr.Get("/index", [&](const Request &, Response &res) {
  16363. res.set_redirect("https://www.google.com/");
  16364. });
  16365. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16366. auto se = detail::scope_exit([&] {
  16367. svr.stop();
  16368. t.join();
  16369. ASSERT_FALSE(svr.is_running());
  16370. });
  16371. svr.wait_until_ready();
  16372. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16373. std::string cert;
  16374. read_file(SERVER_CERT2_FILE, cert);
  16375. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16376. cli.enable_system_ca(true);
  16377. cli.enable_server_certificate_verification(true);
  16378. cli.set_follow_location(true);
  16379. cli.set_connection_timeout(30);
  16380. // Receiving any response proves the redirect client completed the TLS
  16381. // handshake with a system-CA-signed host
  16382. auto res = cli.Get("/index");
  16383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16384. }
  16385. TEST(MultipartFormDataTest, LargeData) {
  16386. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16387. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16388. const ContentReader &content_reader) {
  16389. if (req.is_multipart_form_data()) {
  16390. std::vector<FormData> items;
  16391. content_reader(
  16392. [&](const FormData &file) {
  16393. items.push_back(file);
  16394. return true;
  16395. },
  16396. [&](const char *data, size_t data_length) {
  16397. items.back().content.append(data, data_length);
  16398. return true;
  16399. });
  16400. EXPECT_TRUE(std::string(items[0].name) == "document");
  16401. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16402. EXPECT_TRUE(items[0].filename == "2MB_data");
  16403. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16404. EXPECT_TRUE(items[1].name == "hello");
  16405. EXPECT_TRUE(items[1].content == "world");
  16406. EXPECT_TRUE(items[1].filename == "");
  16407. EXPECT_TRUE(items[1].content_type == "");
  16408. } else {
  16409. std::string body;
  16410. content_reader([&](const char *data, size_t data_length) {
  16411. body.append(data, data_length);
  16412. return true;
  16413. });
  16414. }
  16415. });
  16416. auto port = svr.bind_to_any_port(HOST);
  16417. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16418. auto se = detail::scope_exit([&] {
  16419. svr.stop();
  16420. t.join();
  16421. ASSERT_FALSE(svr.is_running());
  16422. });
  16423. svr.wait_until_ready();
  16424. {
  16425. std::string data(1024 * 1024 * 2, '.');
  16426. std::stringstream buffer;
  16427. buffer << data;
  16428. SSLClient cli(HOST, port);
  16429. cli.enable_server_certificate_verification(false);
  16430. UploadFormDataItems items{
  16431. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16432. {"hello", "world", "", ""},
  16433. };
  16434. auto res = cli.Post("/post", items);
  16435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16436. ASSERT_EQ(StatusCode::OK_200, res->status);
  16437. }
  16438. }
  16439. TEST(MultipartFormDataTest, DataProviderItems) {
  16440. std::random_device seed_gen;
  16441. std::mt19937 random(seed_gen());
  16442. std::string rand1;
  16443. rand1.resize(1000);
  16444. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16445. std::string rand2;
  16446. rand2.resize(3000);
  16447. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16449. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16450. const ContentReader &content_reader) {
  16451. ASSERT_FALSE(req.is_multipart_form_data());
  16452. std::string body;
  16453. content_reader([&](const char *data, size_t data_length) {
  16454. body.append(data, data_length);
  16455. return true;
  16456. });
  16457. EXPECT_EQ(body, "");
  16458. });
  16459. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16460. const ContentReader &content_reader) {
  16461. ASSERT_TRUE(req.is_multipart_form_data());
  16462. std::vector<FormData> items;
  16463. content_reader(
  16464. [&](const FormData &file) {
  16465. items.push_back(file);
  16466. return true;
  16467. },
  16468. [&](const char *data, size_t data_length) {
  16469. items.back().content.append(data, data_length);
  16470. return true;
  16471. });
  16472. ASSERT_TRUE(items.size() == 2);
  16473. EXPECT_EQ(std::string(items[0].name), "name1");
  16474. EXPECT_EQ(items[0].content, "Testing123");
  16475. EXPECT_EQ(items[0].filename, "filename1");
  16476. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16477. EXPECT_EQ(items[1].name, "name2");
  16478. EXPECT_EQ(items[1].content, "Testing456");
  16479. EXPECT_EQ(items[1].filename, "");
  16480. EXPECT_EQ(items[1].content_type, "");
  16481. });
  16482. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16483. const ContentReader &content_reader) {
  16484. ASSERT_TRUE(req.is_multipart_form_data());
  16485. std::vector<FormData> items;
  16486. content_reader(
  16487. [&](const FormData &file) {
  16488. items.push_back(file);
  16489. return true;
  16490. },
  16491. [&](const char *data, size_t data_length) {
  16492. items.back().content.append(data, data_length);
  16493. return true;
  16494. });
  16495. ASSERT_TRUE(items.size() == 2);
  16496. EXPECT_EQ(items[0].name, "name3");
  16497. EXPECT_EQ(items[0].content, rand1);
  16498. EXPECT_EQ(items[0].filename, "filename3");
  16499. EXPECT_EQ(items[0].content_type, "");
  16500. EXPECT_EQ(items[1].name, "name4");
  16501. EXPECT_EQ(items[1].content, rand2);
  16502. EXPECT_EQ(items[1].filename, "filename4");
  16503. EXPECT_EQ(items[1].content_type, "");
  16504. });
  16505. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16506. const ContentReader &content_reader) {
  16507. ASSERT_TRUE(req.is_multipart_form_data());
  16508. std::vector<FormData> items;
  16509. content_reader(
  16510. [&](const FormData &file) {
  16511. items.push_back(file);
  16512. return true;
  16513. },
  16514. [&](const char *data, size_t data_length) {
  16515. items.back().content.append(data, data_length);
  16516. return true;
  16517. });
  16518. ASSERT_TRUE(items.size() == 4);
  16519. EXPECT_EQ(std::string(items[0].name), "name1");
  16520. EXPECT_EQ(items[0].content, "Testing123");
  16521. EXPECT_EQ(items[0].filename, "filename1");
  16522. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16523. EXPECT_EQ(items[1].name, "name2");
  16524. EXPECT_EQ(items[1].content, "Testing456");
  16525. EXPECT_EQ(items[1].filename, "");
  16526. EXPECT_EQ(items[1].content_type, "");
  16527. EXPECT_EQ(items[2].name, "name3");
  16528. EXPECT_EQ(items[2].content, rand1);
  16529. EXPECT_EQ(items[2].filename, "filename3");
  16530. EXPECT_EQ(items[2].content_type, "");
  16531. EXPECT_EQ(items[3].name, "name4");
  16532. EXPECT_EQ(items[3].content, rand2);
  16533. EXPECT_EQ(items[3].filename, "filename4");
  16534. EXPECT_EQ(items[3].content_type, "");
  16535. });
  16536. auto port = svr.bind_to_any_port("localhost");
  16537. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16538. auto se = detail::scope_exit([&] {
  16539. svr.stop();
  16540. t.join();
  16541. ASSERT_FALSE(svr.is_running());
  16542. });
  16543. svr.wait_until_ready();
  16544. {
  16545. SSLClient cli("localhost", port);
  16546. cli.enable_server_certificate_verification(false);
  16547. UploadFormDataItems items{
  16548. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16549. {"name2", "Testing456", "", ""}, // not a file
  16550. };
  16551. {
  16552. auto res = cli.Post("/post-none", {}, {}, {});
  16553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16554. ASSERT_EQ(StatusCode::OK_200, res->status);
  16555. }
  16556. FormDataProviderItems providers;
  16557. {
  16558. auto res =
  16559. cli.Post("/post-items", {}, items, providers); // empty providers
  16560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16561. ASSERT_EQ(StatusCode::OK_200, res->status);
  16562. }
  16563. providers.push_back({"name3",
  16564. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16565. // test the offset is given correctly at each step
  16566. if (!offset)
  16567. sink.os.write(rand1.data(), 30);
  16568. else if (offset == 30)
  16569. sink.os.write(rand1.data() + 30, 300);
  16570. else if (offset == 330)
  16571. sink.os.write(rand1.data() + 330, 670);
  16572. else if (offset == rand1.size())
  16573. sink.done();
  16574. return true;
  16575. },
  16576. "filename3",
  16577. {}});
  16578. providers.push_back({"name4",
  16579. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16580. // test the offset is given correctly at each step
  16581. if (!offset)
  16582. sink.os.write(rand2.data(), 2000);
  16583. else if (offset == 2000)
  16584. sink.os.write(rand2.data() + 2000, 1);
  16585. else if (offset == 2001)
  16586. sink.os.write(rand2.data() + 2001, 999);
  16587. else if (offset == rand2.size())
  16588. sink.done();
  16589. return true;
  16590. },
  16591. "filename4",
  16592. {}});
  16593. {
  16594. auto res = cli.Post("/post-providers", {}, {}, providers);
  16595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16596. ASSERT_EQ(StatusCode::OK_200, res->status);
  16597. }
  16598. {
  16599. auto res = cli.Post("/post-both", {}, items, providers);
  16600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16601. ASSERT_EQ(StatusCode::OK_200, res->status);
  16602. }
  16603. }
  16604. }
  16605. TEST(MultipartFormDataTest, BadHeader) {
  16606. Server svr;
  16607. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16608. res.set_content("ok", "text/plain");
  16609. });
  16610. thread t = thread([&] { svr.listen(HOST, PORT); });
  16611. auto se = detail::scope_exit([&] {
  16612. svr.stop();
  16613. t.join();
  16614. ASSERT_FALSE(svr.is_running());
  16615. });
  16616. svr.wait_until_ready();
  16617. const std::string body =
  16618. "This is the preamble. It is to be ignored, though it\r\n"
  16619. "is a handy place for composition agents to include an\r\n"
  16620. "explanatory note to non-MIME conformant readers.\r\n"
  16621. "\r\n"
  16622. "\r\n"
  16623. "--simple boundary\r\n"
  16624. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16625. ": BAD...\r\n"
  16626. "\r\n"
  16627. "value1\r\n"
  16628. "--simple boundary\r\n"
  16629. "Content-Disposition: form-data; name=\"field2\"; "
  16630. "filename=\"example.txt\"\r\n"
  16631. "\r\n"
  16632. "value2\r\n"
  16633. "--simple boundary--\r\n"
  16634. "This is the epilogue. It is also to be ignored.\r\n";
  16635. std::string content_type =
  16636. R"(multipart/form-data; boundary="simple boundary")";
  16637. Client cli(HOST, PORT);
  16638. auto res = cli.Post("/post", body, content_type.c_str());
  16639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16640. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16641. }
  16642. TEST(MultipartFormDataTest, WithPreamble) {
  16643. Server svr;
  16644. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16645. res.set_content("ok", "text/plain");
  16646. });
  16647. thread t = thread([&] { svr.listen(HOST, PORT); });
  16648. auto se = detail::scope_exit([&] {
  16649. svr.stop();
  16650. t.join();
  16651. ASSERT_FALSE(svr.is_running());
  16652. });
  16653. svr.wait_until_ready();
  16654. const std::string body =
  16655. "This is the preamble. It is to be ignored, though it\r\n"
  16656. "is a handy place for composition agents to include an\r\n"
  16657. "explanatory note to non-MIME conformant readers.\r\n"
  16658. "\r\n"
  16659. "\r\n"
  16660. "--simple boundary\r\n"
  16661. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16662. "\r\n"
  16663. "value1\r\n"
  16664. "--simple boundary\r\n"
  16665. "Content-Disposition: form-data; name=\"field2\"; "
  16666. "filename=\"example.txt\"\r\n"
  16667. "\r\n"
  16668. "value2\r\n"
  16669. "--simple boundary--\r\n"
  16670. "This is the epilogue. It is also to be ignored.\r\n";
  16671. std::string content_type =
  16672. R"(multipart/form-data; boundary="simple boundary")";
  16673. Client cli(HOST, PORT);
  16674. auto res = cli.Post("/post", body, content_type.c_str());
  16675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16676. EXPECT_EQ(StatusCode::OK_200, res->status);
  16677. }
  16678. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16679. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16680. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16681. const ContentReader &content_reader) {
  16682. if (req.is_multipart_form_data()) {
  16683. std::vector<FormData> items;
  16684. content_reader(
  16685. [&](const FormData &file) {
  16686. items.push_back(file);
  16687. return true;
  16688. },
  16689. [&](const char *data, size_t data_length) {
  16690. items.back().content.append(data, data_length);
  16691. return true;
  16692. });
  16693. EXPECT_TRUE(std::string(items[0].name) == "document");
  16694. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16695. EXPECT_TRUE(items[0].filename == "2MB_data");
  16696. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16697. EXPECT_TRUE(items[1].name == "hello");
  16698. EXPECT_TRUE(items[1].content == "world");
  16699. EXPECT_TRUE(items[1].filename == "");
  16700. EXPECT_TRUE(items[1].content_type == "");
  16701. } else {
  16702. std::string body;
  16703. content_reader([&](const char *data, size_t data_length) {
  16704. body.append(data, data_length);
  16705. return true;
  16706. });
  16707. }
  16708. });
  16709. auto port = svr.bind_to_any_port("localhost");
  16710. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16711. auto se = detail::scope_exit([&] {
  16712. svr.stop();
  16713. t.join();
  16714. ASSERT_FALSE(svr.is_running());
  16715. });
  16716. svr.wait_until_ready();
  16717. {
  16718. std::string data(1024 * 1024 * 2, '.');
  16719. std::stringstream buffer;
  16720. buffer << data;
  16721. SSLClient cli("localhost", port);
  16722. cli.enable_server_certificate_verification(false);
  16723. UploadFormDataItems items{
  16724. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16725. {"hello", "world", "", ""},
  16726. };
  16727. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16729. ASSERT_EQ(StatusCode::OK_200, res->status);
  16730. }
  16731. }
  16732. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16733. std::string data(1024 * 1024 * 2, '&');
  16734. std::stringstream buffer;
  16735. buffer << data;
  16736. Client cli("https://localhost:8080");
  16737. UploadFormDataItems items{
  16738. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16739. {"hello", "world", "", ""},
  16740. };
  16741. for (const char &c : " \t\r\n") {
  16742. auto res =
  16743. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16744. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16745. ASSERT_FALSE(res);
  16746. }
  16747. }
  16748. TEST(MultipartFormDataTest, PutFormData) {
  16749. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16750. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16751. const ContentReader &content_reader) {
  16752. if (req.is_multipart_form_data()) {
  16753. std::vector<FormData> items;
  16754. content_reader(
  16755. [&](const FormData &file) {
  16756. items.push_back(file);
  16757. return true;
  16758. },
  16759. [&](const char *data, size_t data_length) {
  16760. items.back().content.append(data, data_length);
  16761. return true;
  16762. });
  16763. EXPECT_TRUE(std::string(items[0].name) == "document");
  16764. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16765. EXPECT_TRUE(items[0].filename == "2MB_data");
  16766. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16767. EXPECT_TRUE(items[1].name == "hello");
  16768. EXPECT_TRUE(items[1].content == "world");
  16769. EXPECT_TRUE(items[1].filename == "");
  16770. EXPECT_TRUE(items[1].content_type == "");
  16771. } else {
  16772. std::string body;
  16773. content_reader([&](const char *data, size_t data_length) {
  16774. body.append(data, data_length);
  16775. return true;
  16776. });
  16777. }
  16778. });
  16779. auto port = svr.bind_to_any_port("localhost");
  16780. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16781. auto se = detail::scope_exit([&] {
  16782. svr.stop();
  16783. t.join();
  16784. ASSERT_FALSE(svr.is_running());
  16785. });
  16786. svr.wait_until_ready();
  16787. {
  16788. std::string data(1024 * 1024 * 2, '&');
  16789. std::stringstream buffer;
  16790. buffer << data;
  16791. SSLClient cli("localhost", port);
  16792. cli.enable_server_certificate_verification(false);
  16793. UploadFormDataItems items{
  16794. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16795. {"hello", "world", "", ""},
  16796. };
  16797. auto res = cli.Put("/put", items);
  16798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16799. ASSERT_EQ(StatusCode::OK_200, res->status);
  16800. }
  16801. }
  16802. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16804. svr.Put("/put_customboundary",
  16805. [&](const Request &req, const Response & /*res*/,
  16806. const ContentReader &content_reader) {
  16807. if (req.is_multipart_form_data()) {
  16808. std::vector<FormData> items;
  16809. content_reader(
  16810. [&](const FormData &file) {
  16811. items.push_back(file);
  16812. return true;
  16813. },
  16814. [&](const char *data, size_t data_length) {
  16815. items.back().content.append(data, data_length);
  16816. return true;
  16817. });
  16818. EXPECT_TRUE(std::string(items[0].name) == "document");
  16819. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16820. EXPECT_TRUE(items[0].filename == "2MB_data");
  16821. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16822. EXPECT_TRUE(items[1].name == "hello");
  16823. EXPECT_TRUE(items[1].content == "world");
  16824. EXPECT_TRUE(items[1].filename == "");
  16825. EXPECT_TRUE(items[1].content_type == "");
  16826. } else {
  16827. std::string body;
  16828. content_reader([&](const char *data, size_t data_length) {
  16829. body.append(data, data_length);
  16830. return true;
  16831. });
  16832. }
  16833. });
  16834. auto port = svr.bind_to_any_port("localhost");
  16835. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16836. auto se = detail::scope_exit([&] {
  16837. svr.stop();
  16838. t.join();
  16839. ASSERT_FALSE(svr.is_running());
  16840. });
  16841. svr.wait_until_ready();
  16842. {
  16843. std::string data(1024 * 1024 * 2, '&');
  16844. std::stringstream buffer;
  16845. buffer << data;
  16846. SSLClient cli("localhost", port);
  16847. cli.enable_server_certificate_verification(false);
  16848. UploadFormDataItems items{
  16849. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16850. {"hello", "world", "", ""},
  16851. };
  16852. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16854. ASSERT_EQ(StatusCode::OK_200, res->status);
  16855. }
  16856. }
  16857. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16858. std::string data(1024 * 1024 * 2, '&');
  16859. std::stringstream buffer;
  16860. buffer << data;
  16861. Client cli("https://localhost:8080");
  16862. cli.enable_server_certificate_verification(false);
  16863. UploadFormDataItems items{
  16864. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16865. {"hello", "world", "", ""},
  16866. };
  16867. for (const char &c : " \t\r\n") {
  16868. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16869. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16870. ASSERT_FALSE(res);
  16871. }
  16872. }
  16873. TEST(MultipartFormDataTest, AlternateFilename) {
  16874. auto handled = false;
  16875. Server svr;
  16876. svr.Post("/test", [&](const Request &req, Response &res) {
  16877. ASSERT_EQ(2u, req.form.files.size());
  16878. ASSERT_EQ(1u, req.form.fields.size());
  16879. // Test files
  16880. const auto &file1 = req.form.get_file("file1");
  16881. ASSERT_EQ("file1", file1.name);
  16882. ASSERT_EQ("A.txt", file1.filename);
  16883. ASSERT_EQ("text/plain", file1.content_type);
  16884. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16885. const auto &file2 = req.form.get_file("file2");
  16886. ASSERT_EQ("file2", file2.name);
  16887. ASSERT_EQ("a.html", file2.filename);
  16888. ASSERT_EQ("text/html", file2.content_type);
  16889. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16890. file2.content);
  16891. // Test text field
  16892. const auto &text = req.form.get_field("text");
  16893. ASSERT_EQ("text default", text);
  16894. res.set_content("ok", "text/plain");
  16895. handled = true;
  16896. });
  16897. thread t = thread([&] { svr.listen(HOST, PORT); });
  16898. auto se = detail::scope_exit([&] {
  16899. svr.stop();
  16900. t.join();
  16901. ASSERT_FALSE(svr.is_running());
  16902. ASSERT_TRUE(handled);
  16903. });
  16904. svr.wait_until_ready();
  16905. auto req = "POST /test HTTP/1.1\r\n"
  16906. "Host: localhost\r\n"
  16907. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16908. "Content-Length: 399\r\n"
  16909. "\r\n"
  16910. "----------\r\n"
  16911. "Content-Disposition: form-data; name=\"text\"\r\n"
  16912. "\r\n"
  16913. "text default\r\n"
  16914. "----------\r\n"
  16915. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16916. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16917. "Content-Type: text/plain\r\n"
  16918. "\r\n"
  16919. "Content of a.txt.\r\n"
  16920. "\r\n"
  16921. "----------\r\n"
  16922. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16923. "\"a.html\"\r\n"
  16924. "Content-Type: text/html\r\n"
  16925. "\r\n"
  16926. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16927. "\r\n"
  16928. "------------\r\n";
  16929. ASSERT_TRUE(send_request(1, req));
  16930. }
  16931. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16932. auto handled = false;
  16933. Server svr;
  16934. svr.Post("/test", [&](const Request &req, Response &res) {
  16935. // Case-insensitive "utf-8''" prefix with a long value
  16936. const auto &file = req.form.get_file("file1");
  16937. ASSERT_EQ("file1", file.name);
  16938. // 8000 chars exercises both the Content-Disposition parser and the
  16939. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16940. // Prior to the fix, std::regex_match on this header would cause O(N)
  16941. // stack recursion in libstdc++, leading to SIGSEGV.
  16942. std::string expected_filename(8000, 'A');
  16943. ASSERT_EQ(expected_filename, file.filename);
  16944. res.set_content("ok", "text/plain");
  16945. handled = true;
  16946. });
  16947. thread t = thread([&] { svr.listen(HOST, PORT); });
  16948. auto se = detail::scope_exit([&] {
  16949. svr.stop();
  16950. t.join();
  16951. ASSERT_FALSE(svr.is_running());
  16952. ASSERT_TRUE(handled);
  16953. });
  16954. svr.wait_until_ready();
  16955. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16956. // Regression test for GHSA-qq6v-r583-3h69
  16957. std::string long_filename(8000, 'A');
  16958. std::string body = "----------\r\n"
  16959. "Content-Disposition: form-data; name=\"file1\"; "
  16960. "filename*=\"Utf-8''" +
  16961. long_filename +
  16962. "\"\r\n"
  16963. "\r\n"
  16964. "hello\r\n"
  16965. "------------\r\n";
  16966. auto req = "POST /test HTTP/1.1\r\n"
  16967. "Host: localhost\r\n"
  16968. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16969. "Content-Length: " +
  16970. std::to_string(body.size()) + "\r\n\r\n" + body;
  16971. ASSERT_TRUE(send_request(1, req));
  16972. }
  16973. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16974. auto handled = false;
  16975. Server svr;
  16976. svr.Post("/test", [&](const Request &req, Response &) {
  16977. ASSERT_EQ(2u, req.form.fields.size());
  16978. const auto &text1 = req.form.get_field("text1");
  16979. ASSERT_EQ("text1", text1);
  16980. const auto &text2 = req.form.get_field("text2");
  16981. ASSERT_EQ("text2", text2);
  16982. handled = true;
  16983. });
  16984. thread t = thread([&] { svr.listen(HOST, PORT); });
  16985. auto se = detail::scope_exit([&] {
  16986. svr.stop();
  16987. t.join();
  16988. ASSERT_FALSE(svr.is_running());
  16989. ASSERT_TRUE(handled);
  16990. });
  16991. svr.wait_until_ready();
  16992. auto req = "POST /test HTTP/1.1\r\n"
  16993. "Host: localhost\r\n"
  16994. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16995. "Content-Length: 146\r\n"
  16996. "\r\n----------\r\n"
  16997. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16998. "\r\n"
  16999. "text1"
  17000. "\r\n----------\r\n"
  17001. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17002. "\r\n"
  17003. "text2"
  17004. "\r\n------------";
  17005. std::string response;
  17006. ASSERT_TRUE(send_request(1, req, &response));
  17007. ASSERT_EQ("200", response.substr(9, 3));
  17008. }
  17009. TEST(MultipartFormDataTest, ContentLength) {
  17010. auto handled = false;
  17011. Server svr;
  17012. svr.Post("/test", [&](const Request &req, Response &) {
  17013. ASSERT_EQ(2u, req.form.fields.size());
  17014. const auto &text1 = req.form.get_field("text1");
  17015. ASSERT_EQ("text1", text1);
  17016. const auto &text2 = req.form.get_field("text2");
  17017. ASSERT_EQ("text2", text2);
  17018. handled = true;
  17019. });
  17020. thread t = thread([&] { svr.listen(HOST, PORT); });
  17021. auto se = detail::scope_exit([&] {
  17022. svr.stop();
  17023. t.join();
  17024. ASSERT_FALSE(svr.is_running());
  17025. ASSERT_TRUE(handled);
  17026. });
  17027. svr.wait_until_ready();
  17028. auto req = "POST /test HTTP/1.1\r\n"
  17029. "Host: localhost\r\n"
  17030. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17031. "Content-Length: 167\r\n"
  17032. "\r\n----------\r\n"
  17033. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17034. "Content-Length: 5\r\n"
  17035. "\r\n"
  17036. "text1"
  17037. "\r\n----------\r\n"
  17038. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17039. "\r\n"
  17040. "text2"
  17041. "\r\n------------\r\n";
  17042. std::string response;
  17043. ASSERT_TRUE(send_request(1, req, &response));
  17044. ASSERT_EQ("200", response.substr(9, 3));
  17045. }
  17046. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17047. auto handled = false;
  17048. Server svr;
  17049. svr.Post("/test", [&](const Request &req, Response &) {
  17050. ASSERT_EQ(2u, req.form.fields.size());
  17051. const auto &text1 = req.form.get_field("text1");
  17052. ASSERT_EQ("text1", text1);
  17053. // TODO: Add header access for text fields if needed
  17054. const auto &text2 = req.form.get_field("text2");
  17055. ASSERT_EQ("text2", text2);
  17056. // TODO: Header access for text fields needs to be implemented
  17057. // auto &headers = it->second.headers;
  17058. // ASSERT_EQ(3U, headers.size());
  17059. // auto custom_header = headers.find("x-whatever");
  17060. // ASSERT_TRUE(custom_header != headers.end());
  17061. // ASSERT_NE("customvalue", custom_header->second);
  17062. // ASSERT_EQ("CustomValue", custom_header->second);
  17063. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  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: 232\r\n"
  17078. "\r\n----------\r\n"
  17079. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17080. "Content-Length: 5\r\n"
  17081. "X-Test: 1\r\n"
  17082. "\r\n"
  17083. "text1"
  17084. "\r\n----------\r\n"
  17085. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17086. "Content-Type: text/plain\r\n"
  17087. "X-Whatever: CustomValue\r\n"
  17088. "\r\n"
  17089. "text2"
  17090. "\r\n------------\r\n"
  17091. "That should be disregarded. Not even read";
  17092. std::string response;
  17093. ASSERT_TRUE(send_request(1, req, &response));
  17094. ASSERT_EQ("200", response.substr(9, 3));
  17095. }
  17096. TEST(MultipartFormDataTest, LargeHeader) {
  17097. auto handled = false;
  17098. Server svr;
  17099. svr.Post("/test", [&](const Request &req, Response &) {
  17100. ASSERT_EQ(1u, req.form.fields.size());
  17101. const auto &text = req.form.get_field("name1");
  17102. ASSERT_EQ("text1", text);
  17103. handled = true;
  17104. });
  17105. thread t = thread([&] { svr.listen(HOST, PORT); });
  17106. auto se = detail::scope_exit([&] {
  17107. svr.stop();
  17108. t.join();
  17109. ASSERT_FALSE(svr.is_running());
  17110. ASSERT_TRUE(handled);
  17111. });
  17112. svr.wait_until_ready();
  17113. auto boundary = std::string("cpp-httplib-multipart-data");
  17114. std::string content = "--" + boundary +
  17115. "\r\n"
  17116. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17117. "\r\n"
  17118. "text1\r\n"
  17119. "--" +
  17120. boundary + "--\r\n";
  17121. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17122. "Host: localhost\r\n"
  17123. "Content-Type: multipart/form-data;boundary=" +
  17124. boundary +
  17125. "\r\n"
  17126. "Content-Length: " +
  17127. std::to_string(content.size()) +
  17128. "\r\n"
  17129. "Dummy-Header: ";
  17130. std::string header_suffix = "\r\n"
  17131. "\r\n";
  17132. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17133. size_t header_dummy_size =
  17134. read_buff_size -
  17135. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17136. auto header_dummy = std::string(header_dummy_size, '@');
  17137. auto req = header_prefix + header_dummy + header_suffix + content;
  17138. std::string response;
  17139. ASSERT_TRUE(send_request(1, req, &response));
  17140. ASSERT_EQ("200", response.substr(9, 3));
  17141. }
  17142. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17143. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17144. // (not chunked Transfer-Encoding) after the streaming refactor.
  17145. auto handled = false;
  17146. Server svr;
  17147. svr.Post("/upload", [&](const Request &req, Response &res) {
  17148. auto cl_it = req.headers.find("Content-Length");
  17149. EXPECT_TRUE(cl_it != req.headers.end());
  17150. auto te_it = req.headers.find("Transfer-Encoding");
  17151. EXPECT_TRUE(te_it == req.headers.end());
  17152. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17153. res.set_content("ok", "text/plain");
  17154. handled = true;
  17155. });
  17156. auto port = svr.bind_to_any_port(HOST);
  17157. auto t = thread([&] { svr.listen_after_bind(); });
  17158. auto se = detail::scope_exit([&] {
  17159. svr.stop();
  17160. t.join();
  17161. ASSERT_FALSE(svr.is_running());
  17162. ASSERT_TRUE(handled);
  17163. });
  17164. svr.wait_until_ready();
  17165. UploadFormDataItems items = {
  17166. {"field1", "hello", "", "text/plain"},
  17167. {"file1", "world", "test.txt", "application/octet-stream"},
  17168. };
  17169. Client cli(HOST, port);
  17170. auto res = cli.Post("/upload", {}, items);
  17171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17172. EXPECT_EQ(StatusCode::OK_200, res->status);
  17173. }
  17174. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17175. // Verify that make_multipart_content_provider coalesces many small segments
  17176. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17177. constexpr size_t kItemCount = 1000;
  17178. UploadFormDataItems items;
  17179. items.reserve(kItemCount);
  17180. for (size_t i = 0; i < kItemCount; i++) {
  17181. items.push_back(
  17182. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17183. }
  17184. const std::string boundary = "----test-boundary";
  17185. auto content_length = detail::get_multipart_content_length(items, boundary);
  17186. auto provider = detail::make_multipart_content_provider(items, boundary);
  17187. // Drive the provider the same way write_content_with_progress does
  17188. size_t write_count = 0;
  17189. size_t total_bytes = 0;
  17190. DataSink sink;
  17191. size_t offset = 0;
  17192. sink.write = [&](const char *d, size_t l) -> bool {
  17193. (void)d;
  17194. write_count++;
  17195. total_bytes += l;
  17196. offset += l;
  17197. return true;
  17198. };
  17199. sink.is_writable = []() -> bool { return true; };
  17200. while (offset < content_length) {
  17201. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17202. }
  17203. EXPECT_EQ(content_length, total_bytes);
  17204. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17205. // With buffering into 64KB blocks, write_count should be much smaller.
  17206. auto segment_count = 3 * kItemCount + 1;
  17207. EXPECT_LT(write_count, segment_count / 10);
  17208. }
  17209. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17210. // Integration test: send many UploadFormDataItems and verify the server
  17211. // receives all of them correctly (#2410).
  17212. constexpr size_t kItemCount = 500;
  17213. auto handled = false;
  17214. Server svr;
  17215. svr.Post("/upload", [&](const Request &req, Response &res) {
  17216. EXPECT_EQ(kItemCount, req.form.fields.size());
  17217. for (size_t i = 0; i < kItemCount; i++) {
  17218. auto key = "field" + std::to_string(i);
  17219. auto val = "value" + std::to_string(i);
  17220. auto it = req.form.fields.find(key);
  17221. if (it != req.form.fields.end()) {
  17222. EXPECT_EQ(val, it->second.content);
  17223. } else {
  17224. ADD_FAILURE() << "Missing field: " << key;
  17225. }
  17226. }
  17227. res.set_content("ok", "text/plain");
  17228. handled = true;
  17229. });
  17230. auto port = svr.bind_to_any_port(HOST);
  17231. auto t = thread([&] { svr.listen_after_bind(); });
  17232. auto se = detail::scope_exit([&] {
  17233. svr.stop();
  17234. t.join();
  17235. ASSERT_FALSE(svr.is_running());
  17236. ASSERT_TRUE(handled);
  17237. });
  17238. svr.wait_until_ready();
  17239. UploadFormDataItems items;
  17240. items.reserve(kItemCount);
  17241. for (size_t i = 0; i < kItemCount; i++) {
  17242. items.push_back(
  17243. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17244. }
  17245. Client cli(HOST, port);
  17246. auto res = cli.Post("/upload", items);
  17247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17248. EXPECT_EQ(StatusCode::OK_200, res->status);
  17249. }
  17250. TEST(MultipartFormDataTest, MakeFileProvider) {
  17251. // Verify make_file_provider sends a file's contents correctly.
  17252. const std::string file_content(4096, 'Z');
  17253. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17254. {
  17255. std::ofstream ofs(tmp_path, std::ios::binary);
  17256. ofs.write(file_content.data(),
  17257. static_cast<std::streamsize>(file_content.size()));
  17258. }
  17259. auto handled = false;
  17260. Server svr;
  17261. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17262. const ContentReader &content_reader) {
  17263. ASSERT_TRUE(req.is_multipart_form_data());
  17264. std::vector<FormData> items;
  17265. content_reader(
  17266. [&](const FormData &file) {
  17267. items.push_back(file);
  17268. return true;
  17269. },
  17270. [&](const char *data, size_t data_length) {
  17271. items.back().content.append(data, data_length);
  17272. return true;
  17273. });
  17274. ASSERT_EQ(1u, items.size());
  17275. EXPECT_EQ("myfile", items[0].name);
  17276. EXPECT_EQ("data.bin", items[0].filename);
  17277. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17278. EXPECT_EQ(file_content, items[0].content);
  17279. handled = true;
  17280. });
  17281. auto port = svr.bind_to_any_port(HOST);
  17282. auto t = thread([&] { svr.listen_after_bind(); });
  17283. auto se = detail::scope_exit([&] {
  17284. svr.stop();
  17285. t.join();
  17286. ASSERT_FALSE(svr.is_running());
  17287. ASSERT_TRUE(handled);
  17288. std::remove(tmp_path.c_str());
  17289. });
  17290. svr.wait_until_ready();
  17291. FormDataProviderItems providers;
  17292. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17293. "application/octet-stream"));
  17294. Client cli(HOST, port);
  17295. auto res = cli.Post("/upload", {}, {}, providers);
  17296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17297. EXPECT_EQ(StatusCode::OK_200, res->status);
  17298. }
  17299. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17300. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17301. // (100) headers is rejected with a 400 Bad Request response.
  17302. Server svr;
  17303. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17304. res.set_content("ok", "text/plain");
  17305. });
  17306. thread t = thread([&] { svr.listen(HOST, PORT); });
  17307. auto se = detail::scope_exit([&] {
  17308. svr.stop();
  17309. t.join();
  17310. ASSERT_FALSE(svr.is_running());
  17311. });
  17312. svr.wait_until_ready();
  17313. // Build a multipart part with 101 custom headers (exceeding
  17314. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17315. std::stringstream body;
  17316. body << "--simpleboundary\r\n"
  17317. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17318. for (int i = 0; i < 101; i++) {
  17319. body << "X-Custom-Header-" << i << ": value\r\n";
  17320. }
  17321. body << "\r\n"
  17322. << "value1\r\n"
  17323. << "--simpleboundary--\r\n";
  17324. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17325. Client cli(HOST, PORT);
  17326. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17328. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17329. }
  17330. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17331. // A body that never contains the declared boundary must not be accumulated
  17332. // while the parser waits for it. Buffering it would also make every read
  17333. // rescan everything seen so far, which is quadratic in the body size.
  17334. Server svr;
  17335. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17336. res.set_content("ok", "text/plain");
  17337. });
  17338. auto port = svr.bind_to_any_port(HOST);
  17339. thread t = thread([&] { svr.listen_after_bind(); });
  17340. auto se = detail::scope_exit([&] {
  17341. svr.stop();
  17342. t.join();
  17343. ASSERT_FALSE(svr.is_running());
  17344. });
  17345. svr.wait_until_ready();
  17346. Client cli(HOST, port);
  17347. cli.set_read_timeout(60, 0);
  17348. cli.set_write_timeout(60, 0);
  17349. // '-' is the worst case: it matches the first character of the boundary, so
  17350. // every position has to be checked against it.
  17351. auto post_dashes = [&](size_t size) {
  17352. const std::string body(size, '-');
  17353. auto start = std::chrono::steady_clock::now();
  17354. auto res =
  17355. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17356. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17357. std::chrono::steady_clock::now() - start)
  17358. .count();
  17359. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17360. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17361. return ms;
  17362. };
  17363. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17364. // Windows.
  17365. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17366. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17367. // Comparing the two sizes rather than checking an absolute duration keeps
  17368. // this meaningful across build types and CI load, both of which move the
  17369. // absolute numbers by more than an order of magnitude. Four times the bytes
  17370. // costs about four times the time when parsing is linear, and about sixteen
  17371. // times when the body is buffered and rescanned.
  17372. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17373. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17374. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17375. << "ms, which suggests the body is being buffered and rescanned";
  17376. }
  17377. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17378. // A boundary can only be followed by CRLF or by "--", so anything else is
  17379. // malformed no matter what comes next. The parser must say so right away
  17380. // instead of buffering the rest of the declared body.
  17381. Server svr;
  17382. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17383. res.set_content("ok", "text/plain");
  17384. });
  17385. auto port = svr.bind_to_any_port(HOST);
  17386. thread t = thread([&] { svr.listen_after_bind(); });
  17387. auto se = detail::scope_exit([&] {
  17388. svr.stop();
  17389. t.join();
  17390. ASSERT_FALSE(svr.is_running());
  17391. });
  17392. svr.wait_until_ready();
  17393. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17394. // buffers instead of failing would still be waiting for the remaining bytes.
  17395. const std::string body = "--zzzz\r\n"
  17396. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17397. "\r\n"
  17398. "text1"
  17399. "\r\n--zzzzXX";
  17400. const std::string req = "POST /post HTTP/1.1\r\n"
  17401. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17402. "Content-Length: 1048576\r\n"
  17403. "\r\n" +
  17404. body;
  17405. std::string response;
  17406. ASSERT_TRUE(send_request(3, req, &response, port));
  17407. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17408. EXPECT_EQ("400", response.substr(9, 3));
  17409. }
  17410. // Posts a multipart body split into two writes, so that the server sees the
  17411. // split at whatever offset the caller chose, and expects the single "text1"
  17412. // field to come through.
  17413. static void expect_split_multipart_ok(const std::string &body1,
  17414. const std::string &body2) {
  17415. auto handled = false;
  17416. Server svr;
  17417. svr.Post("/post", [&](const Request &req, Response &) {
  17418. EXPECT_EQ(1u, req.form.fields.size());
  17419. EXPECT_EQ("text1", req.form.get_field("text1"));
  17420. handled = true;
  17421. });
  17422. auto port = svr.bind_to_any_port(HOST);
  17423. thread t = thread([&] { svr.listen_after_bind(); });
  17424. auto se = detail::scope_exit([&] {
  17425. svr.stop();
  17426. t.join();
  17427. ASSERT_FALSE(svr.is_running());
  17428. ASSERT_TRUE(handled);
  17429. });
  17430. svr.wait_until_ready();
  17431. // "Connection: close" makes the server close once it has answered, so the
  17432. // response drain ends immediately instead of idling until the read timeout.
  17433. const std::string head =
  17434. "POST /post HTTP/1.1\r\n"
  17435. "Host: localhost\r\n"
  17436. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17437. "Connection: close\r\n"
  17438. "Content-Length: " +
  17439. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17440. std::string response;
  17441. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17442. ASSERT_GE(response.size(), 12u) << "no response";
  17443. EXPECT_EQ("200", response.substr(9, 3));
  17444. }
  17445. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17446. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17447. // ignored, including when it does not arrive in the same read as the
  17448. // close-delimiter itself.
  17449. expect_split_multipart_ok("--zzzz\r\n"
  17450. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17451. "\r\n"
  17452. "text1"
  17453. "\r\n--zzzz--",
  17454. "\r\nthis epilogue must be ignored\r\n");
  17455. }
  17456. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17457. // The initial boundary may be preceded by a preamble of any length and may
  17458. // straddle a read boundary. Discarding data while waiting for it must not
  17459. // throw away a partial boundary sitting at the end of the buffer.
  17460. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17461. "zz\r\n"
  17462. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17463. "\r\n"
  17464. "text1"
  17465. "\r\n--zzzz--\r\n");
  17466. }
  17467. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17468. // The received boundary was only checked for being non-empty, so it could be
  17469. // as long as a header is allowed to be. The parser scans the body for
  17470. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17471. // costs a nearly full comparison at nearly every position, making the
  17472. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17473. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17474. Server svr;
  17475. svr.Post("/post", [](const Request &req, Response &res) {
  17476. EXPECT_EQ(1u, req.form.fields.size());
  17477. EXPECT_EQ("text1", req.form.get_field("text1"));
  17478. res.set_content("ok", "text/plain");
  17479. });
  17480. auto port = svr.bind_to_any_port(HOST);
  17481. thread t = thread([&] { svr.listen_after_bind(); });
  17482. auto se = detail::scope_exit([&] {
  17483. svr.stop();
  17484. t.join();
  17485. ASSERT_FALSE(svr.is_running());
  17486. });
  17487. svr.wait_until_ready();
  17488. Client cli(HOST, port);
  17489. auto post_with_boundary_of_length = [&](size_t len) {
  17490. const std::string boundary(len, 'a');
  17491. const std::string body =
  17492. "--" + boundary +
  17493. "\r\n"
  17494. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17495. "\r\n"
  17496. "text1"
  17497. "\r\n--" +
  17498. boundary + "--\r\n";
  17499. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17500. };
  17501. auto res = post_with_boundary_of_length(70);
  17502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17503. EXPECT_EQ(StatusCode::OK_200, res->status);
  17504. res = post_with_boundary_of_length(71);
  17505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17506. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17507. }
  17508. TEST(MakeFileBodyTest, Basic) {
  17509. const std::string file_content(4096, 'Z');
  17510. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17511. {
  17512. std::ofstream ofs(tmp_path, std::ios::binary);
  17513. ofs.write(file_content.data(),
  17514. static_cast<std::streamsize>(file_content.size()));
  17515. }
  17516. auto handled = false;
  17517. Server svr;
  17518. svr.Post("/upload", [&](const Request &req, Response &res) {
  17519. EXPECT_EQ(file_content, req.body);
  17520. handled = true;
  17521. res.status = StatusCode::OK_200;
  17522. });
  17523. auto port = svr.bind_to_any_port(HOST);
  17524. auto t = thread([&] { svr.listen_after_bind(); });
  17525. auto se = detail::scope_exit([&] {
  17526. svr.stop();
  17527. t.join();
  17528. ASSERT_FALSE(svr.is_running());
  17529. ASSERT_TRUE(handled);
  17530. std::remove(tmp_path.c_str());
  17531. });
  17532. svr.wait_until_ready();
  17533. auto fb = make_file_body(tmp_path);
  17534. ASSERT_GT(fb.first, 0u);
  17535. Client cli(HOST, port);
  17536. auto res =
  17537. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17539. EXPECT_EQ(StatusCode::OK_200, res->status);
  17540. }
  17541. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17542. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17543. {
  17544. std::ofstream ofs(path, std::ios::binary);
  17545. const std::string content(100, 'A');
  17546. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17547. }
  17548. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17549. auto body = make_file_body(path);
  17550. ASSERT_EQ(100u, body.first);
  17551. ASSERT_TRUE(static_cast<bool>(body.second));
  17552. // Rewritten shorter after its length was measured - and, on a server, after
  17553. // that length has already gone out as Content-Length.
  17554. {
  17555. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17556. const std::string content(10, 'A');
  17557. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17558. }
  17559. std::string written;
  17560. DataSink sink;
  17561. sink.write = [&](const char *d, size_t l) {
  17562. written.append(d, l);
  17563. return true;
  17564. };
  17565. // The provider has to report failure. write_content_with_progress() advances
  17566. // its offset only by what was written, so a provider that returns true
  17567. // without completing the length it promised is called again straight away,
  17568. // and again.
  17569. EXPECT_FALSE(body.second(0, body.first, sink));
  17570. EXPECT_EQ(std::string(10, 'A'), written);
  17571. }
  17572. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17573. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17574. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17575. {
  17576. std::ofstream ofs(path, std::ios::binary);
  17577. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17578. }
  17579. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17580. auto body = make_file_body(path);
  17581. ASSERT_EQ(content.size(), body.first);
  17582. ASSERT_TRUE(static_cast<bool>(body.second));
  17583. std::string written;
  17584. DataSink sink;
  17585. sink.write = [&](const char *d, size_t l) {
  17586. written.append(d, l);
  17587. return true;
  17588. };
  17589. EXPECT_TRUE(body.second(0, body.first, sink));
  17590. EXPECT_EQ(content, written);
  17591. }
  17592. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17593. static constexpr unsigned int number_of_tasks{1000000};
  17594. std::atomic_uint count{0};
  17595. std::unique_ptr<TaskQueue> task_queue{
  17596. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17597. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17598. auto queued = task_queue->enqueue(
  17599. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17600. EXPECT_TRUE(queued);
  17601. }
  17602. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17603. task_queue->shutdown();
  17604. #else
  17605. EXPECT_NO_THROW(task_queue->shutdown());
  17606. #endif
  17607. EXPECT_EQ(number_of_tasks, count.load());
  17608. }
  17609. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17610. static constexpr unsigned int number_of_tasks{1000000};
  17611. static constexpr unsigned int qlimit{2};
  17612. unsigned int queued_count{0};
  17613. std::atomic_uint count{0};
  17614. std::unique_ptr<TaskQueue> task_queue{
  17615. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17616. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17617. if (task_queue->enqueue(
  17618. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17619. queued_count++;
  17620. }
  17621. }
  17622. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17623. task_queue->shutdown();
  17624. #else
  17625. EXPECT_NO_THROW(task_queue->shutdown());
  17626. #endif
  17627. EXPECT_EQ(queued_count, count.load());
  17628. EXPECT_TRUE(queued_count <= number_of_tasks);
  17629. EXPECT_TRUE(queued_count >= qlimit);
  17630. }
  17631. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17632. // Use a short idle timeout so a dynamic thread spawns, times out and
  17633. // exits during the test, and the pool keeps working afterwards.
  17634. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17635. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17636. /*idle_timeout_sec=*/1}};
  17637. std::atomic_uint count{0};
  17638. std::condition_variable cv;
  17639. std::mutex mtx;
  17640. bool release = false;
  17641. // Block the base thread so the second task spawns a dynamic thread.
  17642. EXPECT_TRUE(task_queue->enqueue([&] {
  17643. std::unique_lock<std::mutex> lock(mtx);
  17644. while (!release) {
  17645. cv.wait(lock);
  17646. }
  17647. count++;
  17648. }));
  17649. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17650. // Let the dynamic thread finish its task and exceed the idle timeout.
  17651. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17652. {
  17653. std::unique_lock<std::mutex> lock(mtx);
  17654. release = true;
  17655. }
  17656. cv.notify_all();
  17657. // The pool must still accept and run tasks after the dynamic thread exited.
  17658. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17659. task_queue->shutdown();
  17660. EXPECT_EQ(3u, count.load());
  17661. }
  17662. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17663. static constexpr size_t number_of_tasks{32};
  17664. std::unique_ptr<TaskQueue> task_queue{
  17665. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17666. // Let the base threads go idle so the burst below finds them waiting.
  17667. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17668. std::mutex mtx;
  17669. std::condition_variable cv;
  17670. size_t running = 0;
  17671. bool release = false;
  17672. for (size_t i = 0; i < number_of_tasks; i++) {
  17673. EXPECT_TRUE(task_queue->enqueue([&] {
  17674. std::unique_lock<std::mutex> lock(mtx);
  17675. running++;
  17676. cv.notify_all();
  17677. cv.wait(lock, [&] { return release; });
  17678. }));
  17679. }
  17680. {
  17681. std::unique_lock<std::mutex> lock(mtx);
  17682. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17683. [&] { return running == number_of_tasks; }));
  17684. release = true;
  17685. }
  17686. cv.notify_all();
  17687. task_queue->shutdown();
  17688. }
  17689. TEST(TaskQueueTest, MaxQueuedRequests) {
  17690. static constexpr unsigned int qlimit{3};
  17691. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17692. std::condition_variable sem_cv;
  17693. std::mutex sem_mtx;
  17694. int credits = 0;
  17695. bool queued;
  17696. /* Fill up the queue with tasks that will block until we give them credits to
  17697. * complete. */
  17698. for (unsigned int n = 0; n <= qlimit;) {
  17699. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17700. std::unique_lock<std::mutex> lock(sem_mtx);
  17701. while (credits <= 0) {
  17702. sem_cv.wait(lock);
  17703. }
  17704. /* Consume the credit and signal the test code if they are all gone. */
  17705. if (--credits == 0) { sem_cv.notify_one(); }
  17706. });
  17707. if (n < qlimit) {
  17708. /* The first qlimit enqueues must succeed. */
  17709. EXPECT_TRUE(queued);
  17710. } else {
  17711. /* The last one will succeed only when the worker thread
  17712. * starts and dequeues the first blocking task. Although
  17713. * not necessary for the correctness of this test, we sleep for
  17714. * a short while to avoid busy waiting. */
  17715. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17716. }
  17717. if (queued) { n++; }
  17718. }
  17719. /* Further enqueues must fail since the queue is full. */
  17720. for (auto i = 0; i < 4; i++) {
  17721. queued = task_queue->enqueue([] {});
  17722. EXPECT_FALSE(queued);
  17723. }
  17724. /* Give the credits to allow the previous tasks to complete. */
  17725. {
  17726. std::unique_lock<std::mutex> lock(sem_mtx);
  17727. credits += qlimit + 1;
  17728. }
  17729. sem_cv.notify_all();
  17730. /* Wait for all the credits to be consumed. */
  17731. {
  17732. std::unique_lock<std::mutex> lock(sem_mtx);
  17733. while (credits > 0) {
  17734. sem_cv.wait(lock);
  17735. }
  17736. }
  17737. /* Check that we are able again to enqueue at least qlimit tasks. */
  17738. for (unsigned int i = 0; i < qlimit; i++) {
  17739. queued = task_queue->enqueue([] {});
  17740. EXPECT_TRUE(queued);
  17741. }
  17742. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17743. task_queue->shutdown();
  17744. #else
  17745. EXPECT_NO_THROW(task_queue->shutdown());
  17746. #endif
  17747. }
  17748. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17749. Server svr;
  17750. std::string method;
  17751. std::string body;
  17752. auto has_content_length = false;
  17753. auto has_transfer_encoding = false;
  17754. std::atomic<int> bad_requests{0};
  17755. // Leftover body bytes get parsed as a malformed request and answered with
  17756. // 400
  17757. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17758. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17759. });
  17760. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17761. res.set_redirect("/down", StatusCode::SeeOther_303);
  17762. });
  17763. svr.Get("/down", [&](const Request &req, Response &res) {
  17764. method = req.method;
  17765. body = req.body;
  17766. has_content_length = req.has_header("Content-Length");
  17767. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17768. res.set_content("ok", "text/plain");
  17769. });
  17770. auto port = svr.bind_to_any_port(HOST);
  17771. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17772. auto se = detail::scope_exit([&] {
  17773. svr.stop();
  17774. thread.join();
  17775. ASSERT_FALSE(svr.is_running());
  17776. });
  17777. svr.wait_until_ready();
  17778. const std::string payload = "SECRET-BODY";
  17779. auto check = [&](Client &cli, const Result &res) {
  17780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17781. EXPECT_EQ(StatusCode::OK_200, res->status);
  17782. EXPECT_EQ("ok", res->body);
  17783. EXPECT_EQ("GET", method);
  17784. EXPECT_TRUE(body.empty());
  17785. EXPECT_FALSE(has_content_length);
  17786. EXPECT_FALSE(has_transfer_encoding);
  17787. // Nothing of the original body may be left on the connection
  17788. auto res2 = cli.Get("/down");
  17789. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17790. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17791. EXPECT_EQ("ok", res2->body);
  17792. EXPECT_EQ(0, bad_requests);
  17793. };
  17794. // With content length
  17795. {
  17796. Client cli(HOST, port);
  17797. cli.set_keep_alive(true);
  17798. cli.set_follow_location(true);
  17799. auto res = cli.Post(
  17800. "/up", payload.size(),
  17801. [&](size_t offset, size_t length, DataSink &sink) {
  17802. return sink.write(payload.data() + offset, length);
  17803. },
  17804. "text/plain");
  17805. check(cli, res);
  17806. }
  17807. // Without content length (chunked)
  17808. {
  17809. Client cli(HOST, port);
  17810. cli.set_keep_alive(true);
  17811. cli.set_follow_location(true);
  17812. auto res = cli.Post(
  17813. "/up",
  17814. [&](size_t /*offset*/, DataSink &sink) {
  17815. sink.write(payload.data(), payload.size());
  17816. sink.done();
  17817. return true;
  17818. },
  17819. "text/plain");
  17820. check(cli, res);
  17821. }
  17822. }
  17823. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17824. Server svr;
  17825. std::string target;
  17826. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17827. // Echo the still-encoded name back in the Location
  17828. const std::string prefix = "/start/";
  17829. res.status = StatusCode::Found_302;
  17830. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17831. });
  17832. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17833. target = req.target;
  17834. res.set_content("ok", "text/plain");
  17835. });
  17836. auto port = svr.bind_to_any_port(HOST);
  17837. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17838. auto se = detail::scope_exit([&] {
  17839. svr.stop();
  17840. thread.join();
  17841. ASSERT_FALSE(svr.is_running());
  17842. });
  17843. svr.wait_until_ready();
  17844. // Decoding the Location path would turn the first four into a path
  17845. // separator, a query delimiter, a fragment delimiter and a different
  17846. // percent-encoded octet. The rest must keep reaching the server as they are.
  17847. const std::vector<std::string> names = {
  17848. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17849. };
  17850. for (auto path_encode : {true, false}) {
  17851. Client cli(HOST, port);
  17852. cli.set_follow_location(true);
  17853. cli.set_path_encode(path_encode);
  17854. for (const auto &name : names) {
  17855. target.clear();
  17856. auto res = cli.Get("/start/" + name);
  17857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17858. EXPECT_EQ(StatusCode::OK_200, res->status);
  17859. EXPECT_EQ("/dest/" + name, target);
  17860. }
  17861. }
  17862. }
  17863. TEST(RedirectTest, NotModifiedIsReturned) {
  17864. Server svr;
  17865. svr.Get("/cached", [](const Request &, Response &res) {
  17866. res.status = StatusCode::NotModified_304;
  17867. });
  17868. auto port = svr.bind_to_any_port(HOST);
  17869. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17870. auto se = detail::scope_exit([&] {
  17871. svr.stop();
  17872. thread.join();
  17873. ASSERT_FALSE(svr.is_running());
  17874. });
  17875. svr.wait_until_ready();
  17876. Client cli(HOST, port);
  17877. cli.set_follow_location(true);
  17878. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17880. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17881. }
  17882. TEST(RedirectTest, NoLocationIsReturned) {
  17883. Server svr;
  17884. svr.Get("/no-location", [](const Request &, Response &res) {
  17885. res.status = StatusCode::Found_302;
  17886. res.set_content("no location", "text/plain");
  17887. });
  17888. auto port = svr.bind_to_any_port(HOST);
  17889. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17890. auto se = detail::scope_exit([&] {
  17891. svr.stop();
  17892. thread.join();
  17893. ASSERT_FALSE(svr.is_running());
  17894. });
  17895. svr.wait_until_ready();
  17896. Client cli(HOST, port);
  17897. cli.set_follow_location(true);
  17898. auto res = cli.Get("/no-location");
  17899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17900. EXPECT_EQ(StatusCode::Found_302, res->status);
  17901. EXPECT_EQ("no location", res->body);
  17902. // The callbacks see the body of the response that is returned
  17903. auto handler_called = false;
  17904. auto progress_called = false;
  17905. std::string body;
  17906. auto res2 = cli.Get(
  17907. "/no-location",
  17908. [&](const Response &) {
  17909. handler_called = true;
  17910. return true;
  17911. },
  17912. [&](const char *data, size_t data_length) {
  17913. body.append(data, data_length);
  17914. return true;
  17915. },
  17916. [&](size_t, size_t) {
  17917. progress_called = true;
  17918. return true;
  17919. });
  17920. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17921. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17922. EXPECT_TRUE(handler_called);
  17923. EXPECT_TRUE(progress_called);
  17924. EXPECT_EQ("no location", body);
  17925. }
  17926. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17927. Server svr;
  17928. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17929. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17930. });
  17931. svr.Get("/hello", [](const Request &req, Response &res) {
  17932. res.set_content(req.get_param_value("key"), "text/plain");
  17933. });
  17934. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17935. auto se = detail::scope_exit([&] {
  17936. svr.stop();
  17937. thread.join();
  17938. ASSERT_FALSE(svr.is_running());
  17939. });
  17940. svr.wait_until_ready();
  17941. {
  17942. Client cli(HOST, PORT);
  17943. cli.set_follow_location(true);
  17944. auto res = cli.Get("/");
  17945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17946. EXPECT_EQ(StatusCode::OK_200, res->status);
  17947. EXPECT_EQ("val&key2=val2", res->body);
  17948. }
  17949. }
  17950. #endif
  17951. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17952. Server svr;
  17953. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17954. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17955. });
  17956. svr.Get("/hello", [](const Request &req, Response &res) {
  17957. res.set_content(req.get_param_value("key"), "text/plain");
  17958. });
  17959. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17960. auto se = detail::scope_exit([&] {
  17961. svr.stop();
  17962. thread.join();
  17963. ASSERT_FALSE(svr.is_running());
  17964. });
  17965. svr.wait_until_ready();
  17966. {
  17967. Client cli(HOST, PORT);
  17968. cli.set_follow_location(true);
  17969. auto res = cli.Get("/");
  17970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17971. EXPECT_EQ(StatusCode::OK_200, res->status);
  17972. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17973. }
  17974. }
  17975. TEST(RedirectTest, RedirectWithPlusInPath) {
  17976. Server svr;
  17977. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17978. res.set_redirect("/a+b");
  17979. });
  17980. // Route pattern uses regex; escape + as \\+
  17981. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17982. res.set_content(req.path, "text/plain");
  17983. });
  17984. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17985. auto se = detail::scope_exit([&] {
  17986. svr.stop();
  17987. thread.join();
  17988. ASSERT_FALSE(svr.is_running());
  17989. });
  17990. svr.wait_until_ready();
  17991. {
  17992. Client cli(HOST, PORT);
  17993. cli.set_follow_location(true);
  17994. auto res = cli.Get("/");
  17995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17996. EXPECT_EQ(StatusCode::OK_200, res->status);
  17997. EXPECT_EQ("/a+b", res->body);
  17998. }
  17999. }
  18000. TEST(RedirectTest, ResolveRelativeLocation) {
  18001. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18002. const std::vector<std::pair<std::string, std::string>> cases = {
  18003. {"g", "/b/c/g"},
  18004. {"./g", "/b/c/g"},
  18005. {"g/", "/b/c/g/"},
  18006. {"?y", "/b/c/d;p?y"},
  18007. {"g?y", "/b/c/g?y"},
  18008. {"#s", "/b/c/d;p?q#s"},
  18009. {"g#s", "/b/c/g#s"},
  18010. {"g?y#s", "/b/c/g?y#s"},
  18011. {";x", "/b/c/;x"},
  18012. {"g;x", "/b/c/g;x"},
  18013. {".", "/b/c/"},
  18014. {"./", "/b/c/"},
  18015. {"..", "/b/"},
  18016. {"../", "/b/"},
  18017. {"../g", "/b/g"},
  18018. {"../..", "/"},
  18019. {"../../", "/"},
  18020. {"../../g", "/g"},
  18021. {"../../../g", "/g"},
  18022. {"g.", "/b/c/g."},
  18023. {".g", "/b/c/.g"},
  18024. {"g..", "/b/c/g.."},
  18025. {"..g", "/b/c/..g"},
  18026. {"./../g", "/b/g"},
  18027. {"./g/.", "/b/c/g/"},
  18028. {"g/./h", "/b/c/g/h"},
  18029. {"g/../h", "/b/c/h"},
  18030. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18031. {"g;x=1/../y", "/b/c/y"},
  18032. {"g?y/./x", "/b/c/g?y/./x"},
  18033. {"g#s/../x", "/b/c/g#s/../x"},
  18034. // Not relative-path references, so left for parse_url.
  18035. {"/g", "/g"},
  18036. {"//g", "//g"},
  18037. {"http://g/x", "http://g/x"},
  18038. {"g:h", "g:h"},
  18039. };
  18040. for (const auto &c : cases) {
  18041. EXPECT_EQ(c.second,
  18042. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18043. << c.first;
  18044. }
  18045. // A result starting with "//" is still a path, not a network-path reference
  18046. EXPECT_EQ("/.//g",
  18047. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18048. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18049. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18050. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18051. }
  18052. TEST(RedirectTest, RemoveDotSegments) {
  18053. // RFC 3986 section 5.2.4
  18054. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18055. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18056. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18057. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18058. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18059. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18060. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18061. }
  18062. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18063. Server svr;
  18064. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18065. res.set_redirect("/dir/../target?x=1");
  18066. });
  18067. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18068. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18069. "/dir/./../target");
  18070. });
  18071. svr.Get("/target", [](const Request &req, Response &res) {
  18072. res.set_content(req.path, "text/plain");
  18073. });
  18074. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18075. auto se = detail::scope_exit([&] {
  18076. svr.stop();
  18077. th.join();
  18078. ASSERT_FALSE(svr.is_running());
  18079. });
  18080. svr.wait_until_ready();
  18081. Client cli("localhost", PORT);
  18082. cli.set_follow_location(true);
  18083. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18084. auto res = cli.Get(path);
  18085. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18086. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18087. EXPECT_EQ("/target", res->body) << path;
  18088. }
  18089. }
  18090. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18091. Server svr;
  18092. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18093. res.set_redirect(req.get_param_value("to"));
  18094. });
  18095. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18096. res.set_content(req.target, "text/plain");
  18097. });
  18098. svr.Get("/other", [](const Request &req, Response &res) {
  18099. res.set_content(req.target, "text/plain");
  18100. });
  18101. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18102. auto se = detail::scope_exit([&] {
  18103. svr.stop();
  18104. thread.join();
  18105. ASSERT_FALSE(svr.is_running());
  18106. });
  18107. svr.wait_until_ready();
  18108. const std::vector<std::pair<std::string, std::string>> cases = {
  18109. {"next", "/dir/next"},
  18110. {"./next?x=1", "/dir/next?x=1"},
  18111. {"../other", "/other"},
  18112. };
  18113. for (const auto &c : cases) {
  18114. Client cli(HOST, PORT);
  18115. cli.set_follow_location(true);
  18116. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18117. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18118. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18119. EXPECT_EQ(c.second, res->body) << c.first;
  18120. }
  18121. }
  18122. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18123. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18124. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18125. Server other;
  18126. std::atomic<int> other_hits{0};
  18127. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18128. other_hits++;
  18129. res.set_content("other", "text/plain");
  18130. });
  18131. auto other_port = other.bind_to_any_port("127.0.0.1");
  18132. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18133. Server svr;
  18134. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18135. res.set_redirect(req.get_param_value("to"));
  18136. });
  18137. svr.Get(".*", [](const Request &req, Response &res) {
  18138. res.set_content(req.path, "text/plain");
  18139. });
  18140. auto port = svr.bind_to_any_port(HOST);
  18141. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18142. auto se = detail::scope_exit([&] {
  18143. svr.stop();
  18144. thread.join();
  18145. other.stop();
  18146. other_thread.join();
  18147. ASSERT_FALSE(svr.is_running());
  18148. ASSERT_FALSE(other.is_running());
  18149. });
  18150. svr.wait_until_ready();
  18151. other.wait_until_ready();
  18152. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18153. for (const auto &to :
  18154. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18155. Client cli(HOST, port);
  18156. cli.set_follow_location(true);
  18157. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18158. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18159. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18160. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18161. }
  18162. EXPECT_EQ(0, other_hits.load());
  18163. }
  18164. #ifdef CPPHTTPLIB_SSL_ENABLED
  18165. TEST(RedirectTest, Issue2185_Online) {
  18166. SSLClient client("github.com");
  18167. client.set_follow_location(true);
  18168. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18169. "Coollab-Windows.zip");
  18170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18171. EXPECT_EQ(StatusCode::OK_200, res->status);
  18172. EXPECT_EQ(9920427U, res->body.size());
  18173. }
  18174. #endif
  18175. TEST(VulnerabilityTest, CRLFInjection) {
  18176. Server svr;
  18177. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18178. res.set_content("Hello 1", "text/plain");
  18179. });
  18180. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18181. res.set_content("Hello 2", "text/plain");
  18182. });
  18183. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18184. res.set_content("Hello 3", "text/plain");
  18185. });
  18186. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18187. res.set_content("Hello 4", "text/plain");
  18188. });
  18189. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18190. for (const auto &x : req.headers) {
  18191. auto key = x.first;
  18192. EXPECT_STRNE("evil", key.c_str());
  18193. }
  18194. });
  18195. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18196. auto se = detail::scope_exit([&] {
  18197. svr.stop();
  18198. thread.join();
  18199. ASSERT_FALSE(svr.is_running());
  18200. });
  18201. svr.wait_until_ready();
  18202. {
  18203. Client cli(HOST, PORT);
  18204. cli.Post("/test1", "A=B",
  18205. "application/x-www-form-urlencoded\r\nevil: hello1");
  18206. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18207. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18208. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18209. }
  18210. }
  18211. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18212. auto server_thread = std::thread([] {
  18213. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18214. default_socket_options(srv);
  18215. sockaddr_in addr{};
  18216. addr.sin_family = AF_INET;
  18217. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18218. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18219. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18220. ::listen(srv, 1);
  18221. sockaddr_in cli_addr{};
  18222. socklen_t cli_len = sizeof(cli_addr);
  18223. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18224. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18225. std::string buf_all;
  18226. char buf[2048];
  18227. ssize_t n;
  18228. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18229. buf_all.append(buf, static_cast<size_t>(n));
  18230. size_t pos;
  18231. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18232. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18233. auto e = request_block.find("\r\n");
  18234. if (e != std::string::npos) {
  18235. auto request_line = request_block.substr(0, e);
  18236. std::string msg =
  18237. "CRLF injection detected in request line: '" + request_line + "'";
  18238. EXPECT_FALSE(true) << msg;
  18239. }
  18240. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18241. ::send(cli,
  18242. #ifdef _WIN32
  18243. static_cast<const char *>(resp.c_str()),
  18244. static_cast<int>(resp.size()),
  18245. #else
  18246. resp.c_str(), resp.size(),
  18247. #endif
  18248. 0);
  18249. buf_all.erase(0, pos + 4);
  18250. }
  18251. }
  18252. detail::close_socket(cli);
  18253. detail::close_socket(srv);
  18254. });
  18255. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18256. auto cli = Client("127.0.0.1", PORT + 1);
  18257. auto headers = Headers{
  18258. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18259. {"Connection", "keep-alive"}};
  18260. auto res = cli.Get("/hi", headers);
  18261. EXPECT_FALSE(res);
  18262. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18263. server_thread.join();
  18264. }
  18265. // A request rejected before any byte reaches the socket must fail right away
  18266. // instead of waiting for a response the server will never send.
  18267. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18268. // The kernel completes the TCP handshake from the listen backlog, so the
  18269. // client connects, but nothing ever reads, responds or closes.
  18270. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18271. default_socket_options(srv);
  18272. sockaddr_in addr{};
  18273. addr.sin_family = AF_INET;
  18274. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18275. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18276. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18277. ASSERT_EQ(0, ::listen(srv, 8));
  18278. auto cli = Client("127.0.0.1", PORT + 1);
  18279. cli.set_read_timeout(10, 0);
  18280. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18281. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18282. std::chrono::steady_clock::now() - start)
  18283. .count();
  18284. };
  18285. {
  18286. Request req;
  18287. req.method = "GE T";
  18288. req.path = "/";
  18289. auto start = std::chrono::steady_clock::now();
  18290. auto res = cli.send(req);
  18291. EXPECT_FALSE(res);
  18292. EXPECT_EQ(Error::Write, res.error());
  18293. EXPECT_LT(elapsed_ms(start), 1000);
  18294. }
  18295. {
  18296. auto start = std::chrono::steady_clock::now();
  18297. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18298. EXPECT_FALSE(res);
  18299. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18300. EXPECT_LT(elapsed_ms(start), 1000);
  18301. }
  18302. EXPECT_FALSE(cli.is_socket_open());
  18303. detail::close_socket(srv);
  18304. }
  18305. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18306. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18307. default_socket_options(srv);
  18308. sockaddr_in addr{};
  18309. addr.sin_family = AF_INET;
  18310. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18311. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18312. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18313. ASSERT_EQ(0, ::listen(srv, 1));
  18314. std::string received;
  18315. auto server_thread = std::thread([&] {
  18316. auto sock = ::accept(srv, nullptr, nullptr);
  18317. if (sock == INVALID_SOCKET) { return; }
  18318. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18319. char buf[2048];
  18320. ssize_t n;
  18321. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18322. received.append(buf, static_cast<size_t>(n));
  18323. }
  18324. detail::close_socket(sock);
  18325. });
  18326. {
  18327. auto cli = Client("127.0.0.1", PORT + 1);
  18328. // "Z" sorts after the default headers, so writing straight to the socket
  18329. // would have sent the request line and those headers before the rejection.
  18330. auto handle =
  18331. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18332. EXPECT_FALSE(handle.is_valid());
  18333. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18334. }
  18335. server_thread.join();
  18336. detail::close_socket(srv);
  18337. EXPECT_TRUE(received.empty()) << received;
  18338. }
  18339. TEST(PathParamsTest, StaticMatch) {
  18340. const auto pattern = "/users/all";
  18341. detail::PathParamsMatcher matcher(pattern);
  18342. Request request;
  18343. request.path = "/users/all";
  18344. ASSERT_TRUE(matcher.match(request));
  18345. std::unordered_map<std::string, std::string> expected_params = {};
  18346. EXPECT_EQ(request.path_params, expected_params);
  18347. }
  18348. TEST(PathParamsTest, StaticMismatch) {
  18349. const auto pattern = "/users/all";
  18350. detail::PathParamsMatcher matcher(pattern);
  18351. Request request;
  18352. request.path = "/users/1";
  18353. ASSERT_FALSE(matcher.match(request));
  18354. }
  18355. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18356. const auto pattern = "/users/:id/subscriptions";
  18357. detail::PathParamsMatcher matcher(pattern);
  18358. Request request;
  18359. request.path = "/users/42/subscriptions";
  18360. ASSERT_TRUE(matcher.match(request));
  18361. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18362. EXPECT_EQ(request.path_params, expected_params);
  18363. }
  18364. TEST(PathParamsTest, SingleParamInTheEnd) {
  18365. const auto pattern = "/users/:id";
  18366. detail::PathParamsMatcher matcher(pattern);
  18367. Request request;
  18368. request.path = "/users/24";
  18369. ASSERT_TRUE(matcher.match(request));
  18370. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18371. EXPECT_EQ(request.path_params, expected_params);
  18372. }
  18373. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18374. const auto pattern = "/users/:id/";
  18375. detail::PathParamsMatcher matcher(pattern);
  18376. Request request;
  18377. request.path = "/users/42/";
  18378. ASSERT_TRUE(matcher.match(request));
  18379. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18380. EXPECT_EQ(request.path_params, expected_params);
  18381. }
  18382. TEST(PathParamsTest, EmptyParam) {
  18383. const auto pattern = "/users/:id/";
  18384. detail::PathParamsMatcher matcher(pattern);
  18385. Request request;
  18386. request.path = "/users//";
  18387. ASSERT_TRUE(matcher.match(request));
  18388. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18389. EXPECT_EQ(request.path_params, expected_params);
  18390. }
  18391. TEST(PathParamsTest, FragmentMismatch) {
  18392. const auto pattern = "/users/:id/";
  18393. detail::PathParamsMatcher matcher(pattern);
  18394. Request request;
  18395. request.path = "/admins/24/";
  18396. ASSERT_FALSE(matcher.match(request));
  18397. }
  18398. TEST(PathParamsTest, ExtraFragments) {
  18399. const auto pattern = "/users/:id";
  18400. detail::PathParamsMatcher matcher(pattern);
  18401. Request request;
  18402. request.path = "/users/42/subscriptions";
  18403. ASSERT_FALSE(matcher.match(request));
  18404. }
  18405. TEST(PathParamsTest, MissingTrailingParam) {
  18406. const auto pattern = "/users/:id";
  18407. detail::PathParamsMatcher matcher(pattern);
  18408. Request request;
  18409. request.path = "/users";
  18410. ASSERT_FALSE(matcher.match(request));
  18411. }
  18412. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18413. const auto pattern = "/users/:id/subscriptions";
  18414. detail::PathParamsMatcher matcher(pattern);
  18415. Request request;
  18416. request.path = "/users/subscriptions";
  18417. ASSERT_FALSE(matcher.match(request));
  18418. }
  18419. TEST(PathParamsTest, MultipleParams) {
  18420. const auto pattern = "/users/:userid/subscriptions/:subid";
  18421. detail::PathParamsMatcher matcher(pattern);
  18422. Request request;
  18423. request.path = "/users/42/subscriptions/2";
  18424. ASSERT_TRUE(matcher.match(request));
  18425. std::unordered_map<std::string, std::string> expected_params = {
  18426. {"userid", "42"}, {"subid", "2"}};
  18427. EXPECT_EQ(request.path_params, expected_params);
  18428. }
  18429. TEST(PathParamsTest, SequenceOfParams) {
  18430. const auto pattern = "/values/:x/:y/:z";
  18431. detail::PathParamsMatcher matcher(pattern);
  18432. Request request;
  18433. request.path = "/values/1/2/3";
  18434. ASSERT_TRUE(matcher.match(request));
  18435. std::unordered_map<std::string, std::string> expected_params = {
  18436. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18437. EXPECT_EQ(request.path_params, expected_params);
  18438. }
  18439. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18440. const auto pattern = "/prefix:suffix";
  18441. detail::PathParamsMatcher matcher(pattern);
  18442. Request request;
  18443. request.path = "/prefix:suffix";
  18444. ASSERT_TRUE(matcher.match(request));
  18445. const std::unordered_map<std::string, std::string> expected_params = {};
  18446. EXPECT_EQ(request.path_params, expected_params);
  18447. }
  18448. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18449. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18450. // calling thread's stack on a long enough path for a quantified pattern;
  18451. // RegexMatcher must refuse to run regex matching on paths beyond
  18452. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18453. detail::RegexMatcher matcher("/files/(.*)");
  18454. Request within_limit;
  18455. within_limit.path = "/files/" + std::string(10, 'A');
  18456. EXPECT_TRUE(matcher.match(within_limit));
  18457. Request over_limit;
  18458. over_limit.path =
  18459. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18460. EXPECT_FALSE(matcher.match(over_limit));
  18461. }
  18462. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18463. Server svr;
  18464. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18465. res.set_content("ok", "text/plain");
  18466. });
  18467. auto port = svr.bind_to_any_port(HOST);
  18468. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18469. auto se = detail::scope_exit([&] {
  18470. svr.stop();
  18471. thread.join();
  18472. ASSERT_FALSE(svr.is_running());
  18473. });
  18474. svr.wait_until_ready();
  18475. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18476. // request URI limit; this used to be able to crash the process.
  18477. std::string path =
  18478. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18479. std::string req = "GET " + path +
  18480. " HTTP/1.1\r\n"
  18481. "Host: " +
  18482. std::string(HOST) + ":" + std::to_string(port) +
  18483. "\r\n"
  18484. "Connection: close\r\n"
  18485. "\r\n";
  18486. std::string response;
  18487. ASSERT_TRUE(send_request(5, req, &response, port));
  18488. EXPECT_NE(std::string::npos, response.find("404"));
  18489. }
  18490. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18491. Server svr;
  18492. auto handler = [](const Request & /*req*/, Response &res) {
  18493. res.set_content("hit", "text/plain");
  18494. };
  18495. // No regex metacharacter, so this one is compared literally
  18496. svr.Get("/literal/route", handler);
  18497. // '.' is a regex metacharacter, so this one must keep regex semantics
  18498. svr.Get("/a.c", handler);
  18499. auto port = svr.bind_to_any_port(HOST);
  18500. std::thread t([&]() { svr.listen_after_bind(); });
  18501. auto se = detail::scope_exit([&] {
  18502. svr.stop();
  18503. t.join();
  18504. ASSERT_FALSE(svr.is_running());
  18505. });
  18506. svr.wait_until_ready();
  18507. Client cli(HOST, port);
  18508. struct {
  18509. const char *path;
  18510. int status;
  18511. } cases[] = {
  18512. {"/literal/route", StatusCode::OK_200},
  18513. {"/literal/routes", StatusCode::NotFound_404},
  18514. {"/literal/rout", StatusCode::NotFound_404},
  18515. {"/abc", StatusCode::OK_200},
  18516. {"/a.c", StatusCode::OK_200},
  18517. };
  18518. for (const auto &x : cases) {
  18519. auto res = cli.Get(x.path);
  18520. ASSERT_TRUE(res) << x.path;
  18521. EXPECT_EQ(x.status, res->status) << x.path;
  18522. }
  18523. }
  18524. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18525. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18526. // from exhausting the stack, so it must only constrain routes that actually
  18527. // run a regular expression. A literal route is matched by comparison and
  18528. // stays usable at any length.
  18529. Server svr;
  18530. const std::string pattern =
  18531. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18532. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18533. res.set_content("hit", "text/plain");
  18534. });
  18535. auto port = svr.bind_to_any_port(HOST);
  18536. std::thread t([&]() { svr.listen_after_bind(); });
  18537. auto se = detail::scope_exit([&] {
  18538. svr.stop();
  18539. t.join();
  18540. ASSERT_FALSE(svr.is_running());
  18541. });
  18542. svr.wait_until_ready();
  18543. Client cli(HOST, port);
  18544. auto res = cli.Get(pattern);
  18545. ASSERT_TRUE(res);
  18546. EXPECT_EQ(StatusCode::OK_200, res->status);
  18547. }
  18548. TEST(ParseUrlTest, VariousPatterns) {
  18549. {
  18550. detail::UrlComponents uc;
  18551. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18552. EXPECT_EQ("http", uc.scheme);
  18553. EXPECT_EQ("example.com", uc.host);
  18554. EXPECT_EQ("8080", uc.port);
  18555. EXPECT_EQ("/path", uc.path);
  18556. EXPECT_EQ("?q=1", uc.query);
  18557. }
  18558. {
  18559. detail::UrlComponents uc;
  18560. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18561. EXPECT_EQ("https", uc.scheme);
  18562. EXPECT_EQ("example.com", uc.host);
  18563. EXPECT_TRUE(uc.port.empty());
  18564. EXPECT_EQ("/path", uc.path);
  18565. }
  18566. {
  18567. detail::UrlComponents uc;
  18568. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18569. EXPECT_EQ("::1", uc.host);
  18570. EXPECT_EQ("8080", uc.port);
  18571. EXPECT_EQ("/path", uc.path);
  18572. }
  18573. {
  18574. detail::UrlComponents uc;
  18575. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18576. }
  18577. {
  18578. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18579. // the path while the connection still targets the bracketed host.
  18580. detail::UrlComponents uc;
  18581. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18582. }
  18583. {
  18584. detail::UrlComponents uc;
  18585. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18586. }
  18587. {
  18588. detail::UrlComponents uc;
  18589. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18590. EXPECT_EQ("::1", uc.host);
  18591. EXPECT_TRUE(uc.port.empty());
  18592. EXPECT_EQ("/path", uc.path);
  18593. }
  18594. {
  18595. detail::UrlComponents uc;
  18596. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18597. EXPECT_TRUE(uc.scheme.empty());
  18598. EXPECT_EQ("example.com", uc.host);
  18599. EXPECT_EQ("/path", uc.path);
  18600. EXPECT_EQ("?q=1", uc.query);
  18601. }
  18602. {
  18603. detail::UrlComponents uc;
  18604. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18605. EXPECT_TRUE(uc.host.empty());
  18606. EXPECT_EQ("/path", uc.path);
  18607. EXPECT_EQ("?q=1", uc.query);
  18608. }
  18609. {
  18610. detail::UrlComponents uc;
  18611. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18612. EXPECT_EQ("example.com", uc.host);
  18613. EXPECT_EQ("8080", uc.port);
  18614. }
  18615. {
  18616. // Unix socket path — must not be parsed as host
  18617. detail::UrlComponents uc;
  18618. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18619. EXPECT_TRUE(uc.host.empty());
  18620. }
  18621. {
  18622. detail::UrlComponents uc;
  18623. ASSERT_TRUE(detail::parse_url("", uc));
  18624. EXPECT_TRUE(uc.host.empty());
  18625. EXPECT_TRUE(uc.path.empty());
  18626. }
  18627. {
  18628. detail::UrlComponents uc;
  18629. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  18630. }
  18631. {
  18632. detail::UrlComponents uc;
  18633. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18634. }
  18635. {
  18636. // Accepted by parse_url; callers restrict to http/https
  18637. detail::UrlComponents uc;
  18638. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18639. EXPECT_EQ("ftp", uc.scheme);
  18640. }
  18641. {
  18642. detail::UrlComponents uc;
  18643. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18644. }
  18645. {
  18646. detail::UrlComponents uc;
  18647. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18648. }
  18649. }
  18650. TEST(ParseUrlTest, FragmentHandling) {
  18651. {
  18652. detail::UrlComponents uc;
  18653. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18654. EXPECT_EQ("/path", uc.path);
  18655. EXPECT_TRUE(uc.query.empty());
  18656. }
  18657. {
  18658. detail::UrlComponents uc;
  18659. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18660. EXPECT_TRUE(uc.path.empty());
  18661. EXPECT_TRUE(uc.query.empty());
  18662. }
  18663. }
  18664. TEST(ParseUrlTest, UserinfoHandling) {
  18665. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18666. // parsers would see evil.com as the host.
  18667. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18668. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18669. for (auto url : urls) {
  18670. detail::UrlComponents uc;
  18671. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18672. }
  18673. }
  18674. TEST(ParseUrlTest, IPv6EdgeCases) {
  18675. {
  18676. detail::UrlComponents uc;
  18677. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18678. EXPECT_TRUE(uc.scheme.empty());
  18679. EXPECT_EQ("::1", uc.host);
  18680. EXPECT_EQ("8080", uc.port);
  18681. }
  18682. {
  18683. // Zone ID '%25' is not in [a-fA-F0-9:]
  18684. detail::UrlComponents uc;
  18685. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18686. }
  18687. }
  18688. TEST(ParseUrlTest, SchemeEdgeCases) {
  18689. {
  18690. detail::UrlComponents uc;
  18691. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18692. }
  18693. {
  18694. detail::UrlComponents uc;
  18695. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18696. }
  18697. {
  18698. detail::UrlComponents uc;
  18699. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18700. }
  18701. }
  18702. TEST(ParseUrlTest, PortEdgeCases) {
  18703. {
  18704. detail::UrlComponents uc;
  18705. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18706. EXPECT_TRUE(uc.port.empty());
  18707. EXPECT_EQ("/path", uc.path);
  18708. }
  18709. {
  18710. // parse_url accepts any port string; validation is done by parse_port
  18711. detail::UrlComponents uc;
  18712. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18713. EXPECT_EQ("abc", uc.port);
  18714. }
  18715. }
  18716. TEST(ParseUrlTest, WebSocketPatterns) {
  18717. {
  18718. detail::UrlComponents uc;
  18719. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18720. EXPECT_EQ("ws", uc.scheme);
  18721. EXPECT_EQ("echo.example.com", uc.host);
  18722. EXPECT_EQ("8080", uc.port);
  18723. EXPECT_EQ("/ws", uc.path);
  18724. }
  18725. {
  18726. detail::UrlComponents uc;
  18727. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18728. EXPECT_EQ("wss", uc.scheme);
  18729. EXPECT_EQ("echo.example.com", uc.host);
  18730. EXPECT_TRUE(uc.port.empty());
  18731. EXPECT_EQ("/ws", uc.path);
  18732. }
  18733. }
  18734. TEST(ParseUrlTest, QueryOnly) {
  18735. detail::UrlComponents uc;
  18736. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18737. EXPECT_TRUE(uc.host.empty());
  18738. EXPECT_TRUE(uc.path.empty());
  18739. EXPECT_EQ("?q=1&r=2", uc.query);
  18740. }
  18741. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18742. detail::UrlComponents uc;
  18743. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18744. EXPECT_TRUE(uc.scheme.empty());
  18745. EXPECT_EQ("example.com", uc.host);
  18746. EXPECT_EQ("443", uc.port);
  18747. EXPECT_EQ("/path", uc.path);
  18748. }
  18749. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18750. // If ipv6 regex working, regex match codepath is taken.
  18751. // else port will default to 80 in Client impl
  18752. int clientImplMagicPort = 80;
  18753. int port = 4321;
  18754. // above ports must be different to avoid false negative
  18755. EXPECT_NE(clientImplMagicPort, port);
  18756. std::string ipV6TestURL = "http://[ff06::c3]";
  18757. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18758. CLIENT_PRIVATE_KEY_FILE);
  18759. EXPECT_EQ(cli.port(), port);
  18760. }
  18761. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18762. auto file_path = "./www/dir/index.html";
  18763. auto dir_path = "./www/dir";
  18764. detail::FileStat stat_file(file_path);
  18765. EXPECT_TRUE(stat_file.is_file());
  18766. EXPECT_FALSE(stat_file.is_dir());
  18767. detail::FileStat stat_dir(dir_path);
  18768. EXPECT_FALSE(stat_dir.is_file());
  18769. EXPECT_TRUE(stat_dir.is_dir());
  18770. }
  18771. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18772. // IPv4 with default HTTP port (80)
  18773. EXPECT_EQ("example.com",
  18774. detail::make_host_and_port_string("example.com", 80, false));
  18775. // IPv4 with default HTTPS port (443)
  18776. EXPECT_EQ("example.com",
  18777. detail::make_host_and_port_string("example.com", 443, true));
  18778. // IPv4 with non-default HTTP port
  18779. EXPECT_EQ("example.com:8080",
  18780. detail::make_host_and_port_string("example.com", 8080, false));
  18781. // IPv4 with non-default HTTPS port
  18782. EXPECT_EQ("example.com:8443",
  18783. detail::make_host_and_port_string("example.com", 8443, true));
  18784. // IPv6 with default HTTP port (80)
  18785. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18786. // IPv6 with default HTTPS port (443)
  18787. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18788. // IPv6 with non-default HTTP port
  18789. EXPECT_EQ("[::1]:8080",
  18790. detail::make_host_and_port_string("::1", 8080, false));
  18791. // IPv6 with non-default HTTPS port
  18792. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18793. // IPv6 full address with default port
  18794. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18795. detail::make_host_and_port_string(
  18796. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18797. // IPv6 full address with non-default port
  18798. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18799. detail::make_host_and_port_string(
  18800. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18801. // IPv6 localhost with non-default port
  18802. EXPECT_EQ("[::1]:3000",
  18803. detail::make_host_and_port_string("::1", 3000, false));
  18804. // IPv6 with zone ID (link-local address) with default port
  18805. EXPECT_EQ("[fe80::1%eth0]",
  18806. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18807. // IPv6 with zone ID (link-local address) with non-default port
  18808. EXPECT_EQ("[fe80::1%eth0]:8080",
  18809. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18810. // Edge case: Port 443 with is_ssl=false (should add port)
  18811. EXPECT_EQ("example.com:443",
  18812. detail::make_host_and_port_string("example.com", 443, false));
  18813. // Edge case: Port 80 with is_ssl=true (should add port)
  18814. EXPECT_EQ("example.com:80",
  18815. detail::make_host_and_port_string("example.com", 80, true));
  18816. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18817. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18818. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18819. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18820. // Security fix: Already bracketed IPv6 should not get double brackets
  18821. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18822. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18823. EXPECT_EQ("[::1]:8080",
  18824. detail::make_host_and_port_string("[::1]", 8080, false));
  18825. EXPECT_EQ("[2001:db8::1]:8080",
  18826. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18827. EXPECT_EQ("[fe80::1%eth0]",
  18828. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18829. EXPECT_EQ("[fe80::1%eth0]:8080",
  18830. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18831. // Edge case: Empty host (should return as-is)
  18832. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18833. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18834. // This is a known limitation but shouldn't crash
  18835. EXPECT_EQ("[host:name]",
  18836. detail::make_host_and_port_string("host:name", 80, false));
  18837. // Port number edge cases (no validation, but should not crash)
  18838. EXPECT_EQ("example.com:0",
  18839. detail::make_host_and_port_string("example.com", 0, false));
  18840. EXPECT_EQ("example.com:-1",
  18841. detail::make_host_and_port_string("example.com", -1, false));
  18842. EXPECT_EQ("example.com:65535",
  18843. detail::make_host_and_port_string("example.com", 65535, false));
  18844. EXPECT_EQ("example.com:65536",
  18845. detail::make_host_and_port_string("example.com", 65536, false));
  18846. }
  18847. namespace httplib {
  18848. namespace detail {
  18849. std::string
  18850. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  18851. const std::string &host, int port);
  18852. } // namespace detail
  18853. } // namespace httplib
  18854. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  18855. std::map<std::string, std::string> addr_map = {
  18856. {"ipv4.example", "192.0.2.10"},
  18857. {"ipv6.example", "2001:db8::1"},
  18858. {"name.example", "internal.example.lan"},
  18859. {"empty.example", ""}};
  18860. EXPECT_EQ("192.0.2.10:443",
  18861. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  18862. EXPECT_EQ("[2001:db8::1]:443",
  18863. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  18864. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  18865. addr_map, "name.example", 8443));
  18866. // An empty or absent mapping keeps the hostname as the target
  18867. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  18868. addr_map, "empty.example", 443));
  18869. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  18870. addr_map, "other.example", 443));
  18871. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  18872. }
  18873. #ifdef CPPHTTPLIB_SSL_ENABLED
  18874. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18875. httplib::SSLClient cli("roblox.com", 443);
  18876. cli.set_follow_location(true);
  18877. auto res = cli.Get("/");
  18878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18879. EXPECT_EQ(StatusCode::OK_200, res->status);
  18880. }
  18881. #endif
  18882. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18883. Server svr;
  18884. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18885. EXPECT_EQ(res.status, 400);
  18886. });
  18887. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18888. auto se = detail::scope_exit([&] {
  18889. svr.stop();
  18890. thread.join();
  18891. ASSERT_FALSE(svr.is_running());
  18892. });
  18893. svr.wait_until_ready();
  18894. Client cli(HOST, PORT);
  18895. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18896. }
  18897. TEST(InvalidHeaderCharsTest, is_field_name) {
  18898. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18899. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18900. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18901. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18902. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18903. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18904. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18905. EXPECT_FALSE(detail::fields::is_field_name(""));
  18906. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18907. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18908. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18909. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18910. }
  18911. TEST(InvalidHeaderCharsTest, is_field_value) {
  18912. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18913. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18914. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18915. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18916. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18917. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18918. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18919. EXPECT_TRUE(detail::fields::is_field_value(""));
  18920. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18921. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18922. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18923. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18924. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18925. }
  18926. TEST(InvalidHeaderCharsTest, OnServer) {
  18927. Server svr;
  18928. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18929. std::string header = "Not Set";
  18930. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18931. res.set_header(header, "value");
  18932. res.set_content("Page Content Page Content", "text/plain");
  18933. });
  18934. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18935. std::string header = "Not Set";
  18936. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18937. res.set_header("X-Test", header);
  18938. res.set_content("Page Content Page Content", "text/plain");
  18939. });
  18940. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18941. auto se = detail::scope_exit([&] {
  18942. svr.stop();
  18943. thread.join();
  18944. ASSERT_FALSE(svr.is_running());
  18945. });
  18946. svr.wait_until_ready();
  18947. Client cli(HOST, PORT);
  18948. {
  18949. auto res = cli.Get(
  18950. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18952. EXPECT_EQ("Page Content Page Content", res->body);
  18953. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18954. }
  18955. {
  18956. auto res = cli.Get(
  18957. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18959. EXPECT_EQ("Page Content Page Content", res->body);
  18960. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18961. }
  18962. }
  18963. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18964. auto handled = false;
  18965. Server svr;
  18966. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18967. thread t = thread([&] { svr.listen(HOST, PORT); });
  18968. auto se = detail::scope_exit([&] {
  18969. svr.stop();
  18970. t.join();
  18971. ASSERT_FALSE(svr.is_running());
  18972. ASSERT_FALSE(handled);
  18973. });
  18974. svr.wait_until_ready();
  18975. auto req = "POST /test HTTP/1.1\r\n"
  18976. "Content-Length: x\r\n"
  18977. "\r\n";
  18978. std::string response;
  18979. ASSERT_TRUE(send_request(1, req, &response));
  18980. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18981. response.substr(0, response.find("\r\n")));
  18982. }
  18983. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18984. // case-insensitive, and a server that receives a 100-continue expectation in
  18985. // an HTTP/1.0 request MUST ignore it.
  18986. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18987. std::string response;
  18988. ASSERT_TRUE(send_request(1, req, &response, port));
  18989. *got_100 = response.find("100 Continue") != std::string::npos;
  18990. }
  18991. class ExpectTokenTest : public ::testing::Test {
  18992. protected:
  18993. void SetUp() override {
  18994. svr_.Post("/p", [](const Request &, Response &res) {
  18995. res.set_content("ok", "text/plain");
  18996. });
  18997. port_ = svr_.bind_to_any_port(HOST);
  18998. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18999. svr_.wait_until_ready();
  19000. }
  19001. void TearDown() override {
  19002. svr_.stop();
  19003. if (thread_.joinable()) { thread_.join(); }
  19004. }
  19005. std::string request(const char *version, const char *expect_value) const {
  19006. return std::string("POST /p ") + version +
  19007. "\r\n"
  19008. "Host: localhost\r\n"
  19009. "Content-Length: 2\r\n"
  19010. "Connection: close\r\n"
  19011. "Expect: " +
  19012. expect_value +
  19013. "\r\n"
  19014. "\r\n"
  19015. "hi";
  19016. }
  19017. Server svr_;
  19018. int port_ = 0;
  19019. thread thread_;
  19020. };
  19021. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19022. bool got_100 = false;
  19023. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19024. EXPECT_TRUE(got_100);
  19025. }
  19026. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19027. bool got_100 = true;
  19028. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19029. EXPECT_FALSE(got_100);
  19030. }
  19031. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19032. bool got_100 = false;
  19033. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19034. EXPECT_TRUE(got_100);
  19035. }
  19036. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19037. bool got_100 = false;
  19038. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19039. EXPECT_TRUE(got_100);
  19040. }
  19041. // `100 Continue` is sent only when the server starts reading the body, so a
  19042. // request rejected before that never invites the client to send it. The
  19043. // requests below carry the expectation but withhold the body, as a client
  19044. // waiting for `100 Continue` would.
  19045. // A POST that expects `100 Continue` and withholds its two-byte body.
  19046. static std::string expect_headers_only(const std::string &path) {
  19047. return "POST " + path +
  19048. " HTTP/1.1\r\n"
  19049. "Host: localhost\r\n"
  19050. "Content-Length: 2\r\n"
  19051. "Expect: 100-continue\r\n"
  19052. "\r\n";
  19053. }
  19054. class ExpectLazyContinueTest : public ::testing::Test {
  19055. protected:
  19056. void SetUp() override {
  19057. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19058. if (req.path == "/pre-routing") {
  19059. res.status = StatusCode::Unauthorized_401;
  19060. return Server::HandlerResponse::Handled;
  19061. }
  19062. return Server::HandlerResponse::Unhandled;
  19063. });
  19064. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19065. if (req.matched_route == "/pre-request") {
  19066. res.status = StatusCode::Forbidden_403;
  19067. return Server::HandlerResponse::Handled;
  19068. }
  19069. return Server::HandlerResponse::Unhandled;
  19070. });
  19071. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19072. res.set_content("ok", "text/plain");
  19073. });
  19074. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19075. res.set_content("ok", "text/plain");
  19076. });
  19077. svr_.Post("/reader-used", [](const Request &, Response &res,
  19078. const ContentReader &content_reader) {
  19079. std::string body;
  19080. content_reader([&](const char *data, size_t len) {
  19081. body.append(data, len);
  19082. return true;
  19083. });
  19084. res.set_content(body, "text/plain");
  19085. });
  19086. svr_.Post("/reader-unused",
  19087. [](const Request &, Response &res, const ContentReader &) {
  19088. res.set_content("ignored", "text/plain");
  19089. });
  19090. port_ = svr_.bind_to_any_port(HOST);
  19091. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19092. svr_.wait_until_ready();
  19093. }
  19094. void TearDown() override {
  19095. svr_.stop();
  19096. if (thread_.joinable()) { thread_.join(); }
  19097. }
  19098. // Sends `req` and reads until the server closes the connection. Returns
  19099. // false if the read had to wait for the client-side timeout instead.
  19100. bool send_until_closed(const std::string &req, std::string *resp) const {
  19101. auto start = std::chrono::steady_clock::now();
  19102. if (!send_request(3, req, resp, port_)) { return false; }
  19103. auto elapsed = std::chrono::steady_clock::now() - start;
  19104. return elapsed < std::chrono::seconds(2);
  19105. }
  19106. // The final response comes without `100 Continue`, and the server closes
  19107. // the connection since the body may or may not follow.
  19108. void expect_final_without_interim(const std::string &path,
  19109. const char *status_line) const {
  19110. std::string resp;
  19111. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19112. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19113. EXPECT_EQ(0u, resp.find(status_line));
  19114. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19115. }
  19116. Server svr_;
  19117. int port_ = 0;
  19118. thread thread_;
  19119. };
  19120. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19121. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19122. }
  19123. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19124. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19125. }
  19126. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19127. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19128. }
  19129. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19130. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19131. }
  19132. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19133. // The body follows once `100 Continue` has had time to arrive.
  19134. auto req = expect_headers_only("/reader-used");
  19135. req.insert(req.size() - 2, "Connection: close\r\n");
  19136. std::string resp;
  19137. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19138. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19139. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19140. EXPECT_NE(std::string::npos, resp.find("hi"));
  19141. }
  19142. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19143. // Large enough for the client to add `Expect: 100-continue` itself.
  19144. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19145. std::atomic<bool> body_sent{false};
  19146. Client cli(HOST, port_);
  19147. auto res = cli.Post(
  19148. "/pre-request", length,
  19149. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19150. body_sent = true;
  19151. std::string chunk(len, 'x');
  19152. sink.write(chunk.data(), chunk.size());
  19153. return true;
  19154. },
  19155. "application/octet-stream");
  19156. ASSERT_TRUE(res);
  19157. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19158. EXPECT_FALSE(body_sent);
  19159. }
  19160. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19161. Server svr;
  19162. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19163. return StatusCode::ExpectationFailed_417;
  19164. });
  19165. svr.Post("/p", [](const Request &, Response &res) {
  19166. res.set_content("ok", "text/plain");
  19167. });
  19168. auto port = svr.bind_to_any_port(HOST);
  19169. thread t = thread([&] { svr.listen_after_bind(); });
  19170. auto se = detail::scope_exit([&] {
  19171. svr.stop();
  19172. t.join();
  19173. });
  19174. svr.wait_until_ready();
  19175. std::string resp;
  19176. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19177. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19178. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19179. // Exactly one response: the route handler must not run after the 417.
  19180. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19181. }
  19182. #ifndef _WIN32
  19183. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19184. static constexpr char reject[] = "Unauthorized";
  19185. static constexpr char accept[] = "Upload accepted";
  19186. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19187. Server svr;
  19188. svr.set_expect_100_continue_handler(
  19189. [](const Request & /*req*/, Response &res) {
  19190. res.status = StatusCode::Unauthorized_401;
  19191. res.set_content(reject, "text/plain");
  19192. return res.status;
  19193. });
  19194. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19195. res.set_content(accept, "text/plain");
  19196. });
  19197. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19198. auto se = detail::scope_exit([&] {
  19199. svr.stop();
  19200. thread.join();
  19201. ASSERT_FALSE(svr.is_running());
  19202. });
  19203. svr.wait_until_ready();
  19204. {
  19205. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19206. curl_easy_init(), &curl_easy_cleanup};
  19207. ASSERT_NE(curl, nullptr);
  19208. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19209. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19210. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19211. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19212. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19213. &curl_slist_free_all};
  19214. ASSERT_NE(list, nullptr);
  19215. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19216. struct read_data {
  19217. uint64_t read_size;
  19218. uint64_t total_size;
  19219. } data = {0, total_size};
  19220. using read_callback_t =
  19221. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19222. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19223. void *userdata) -> size_t {
  19224. read_data *d = (read_data *)userdata;
  19225. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19226. std::fill_n(ptr, size * nmemb, 'A');
  19227. d->read_size += size * nmemb;
  19228. return size * nmemb;
  19229. };
  19230. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19231. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19232. std::vector<char> buffer;
  19233. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19234. using write_callback_t =
  19235. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19236. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19237. void *userdata) -> size_t {
  19238. std::vector<char> *buf = (std::vector<char> *)userdata;
  19239. buf->reserve(buf->size() + size * nmemb + 1);
  19240. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19241. return size * nmemb;
  19242. };
  19243. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19244. {
  19245. const auto res = curl_easy_perform(curl.get());
  19246. ASSERT_EQ(res, CURLE_OK);
  19247. }
  19248. {
  19249. auto response_code = long{};
  19250. const auto res =
  19251. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19252. ASSERT_EQ(res, CURLE_OK);
  19253. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19254. }
  19255. {
  19256. auto dl = curl_off_t{};
  19257. const auto res =
  19258. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19259. ASSERT_EQ(res, CURLE_OK);
  19260. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19261. }
  19262. {
  19263. buffer.push_back('\0');
  19264. ASSERT_STRCASEEQ(buffer.data(), reject);
  19265. }
  19266. }
  19267. }
  19268. #endif
  19269. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19270. // Regression test for #2458.
  19271. //
  19272. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19273. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19274. // ticket can make the client socket spuriously readable during the
  19275. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19276. // the client withholds the body and then blocks reading a response that never
  19277. // comes, failing with `Failed to read connection`.
  19278. //
  19279. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19280. // within the timeout. This raw OpenSSL server deliberately never sends
  19281. // `100 Continue`; the client must still deliver the body and receive 200.
  19282. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19283. signal(SIGPIPE, SIG_IGN);
  19284. const auto port = PORT + 4;
  19285. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19286. ASSERT_NE(srv, INVALID_SOCKET);
  19287. int opt = 1;
  19288. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19289. sockaddr_in addr{};
  19290. addr.sin_family = AF_INET;
  19291. addr.sin_port = htons(static_cast<uint16_t>(port));
  19292. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19293. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19294. ASSERT_EQ(0, ::listen(srv, 1));
  19295. std::atomic<size_t> server_body_bytes{0};
  19296. auto server_thread = std::thread([&] {
  19297. sockaddr_in cli_addr{};
  19298. socklen_t cli_len = sizeof(cli_addr);
  19299. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19300. if (cli == INVALID_SOCKET) { return; }
  19301. // Bound the lifetime of the server side so a buggy client (which never
  19302. // sends the body) cannot make this thread block forever on join.
  19303. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19304. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19305. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19306. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19307. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19308. SSL *ssl = SSL_new(ctx);
  19309. SSL_set_fd(ssl, static_cast<int>(cli));
  19310. if (SSL_accept(ssl) > 0) {
  19311. // Read the request headers. Reading here also flushes the TLS 1.3
  19312. // session tickets to the client. Deliberately do NOT send
  19313. // `100 Continue`.
  19314. std::string buf;
  19315. char tmp[1024];
  19316. while (buf.find("\r\n\r\n") == std::string::npos) {
  19317. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19318. if (n <= 0) { break; }
  19319. buf.append(tmp, static_cast<size_t>(n));
  19320. }
  19321. // A correct client sends the body now; count what arrives.
  19322. auto pos = buf.find("\r\n\r\n");
  19323. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19324. while (body < 4096) {
  19325. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19326. if (n <= 0) { break; }
  19327. body += static_cast<size_t>(n);
  19328. }
  19329. server_body_bytes = body;
  19330. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19331. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19332. SSL_shutdown(ssl);
  19333. }
  19334. SSL_free(ssl);
  19335. detail::close_socket(cli);
  19336. SSL_CTX_free(ctx);
  19337. });
  19338. auto se = detail::scope_exit([&] {
  19339. server_thread.join();
  19340. detail::close_socket(srv);
  19341. });
  19342. SSLClient cli("127.0.0.1", port);
  19343. cli.enable_server_certificate_verification(false);
  19344. cli.set_connection_timeout(5, 0);
  19345. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19346. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19347. std::string body(4096, 'A');
  19348. auto res = cli.Put("/api/test", body, "application/json");
  19349. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19350. EXPECT_EQ(StatusCode::OK_200, res->status);
  19351. EXPECT_EQ(body.size(), server_body_bytes.load());
  19352. }
  19353. #endif
  19354. template <typename S, typename C>
  19355. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19356. svr.Get("/stream", [&](const Request &, Response &res) {
  19357. auto data = new std::string("01234567890123456789");
  19358. res.set_content_provider(
  19359. data->size(), "text/plain",
  19360. [&, data](size_t offset, size_t length, DataSink &sink) {
  19361. const size_t DATA_CHUNK_SIZE = 4;
  19362. const auto &d = *data;
  19363. std::this_thread::sleep_for(std::chrono::seconds(1));
  19364. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19365. return true;
  19366. },
  19367. [data](bool success) {
  19368. EXPECT_FALSE(success);
  19369. delete data;
  19370. });
  19371. });
  19372. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19373. auto i = new size_t(0);
  19374. res.set_content_provider(
  19375. "text/plain",
  19376. [i](size_t, DataSink &sink) {
  19377. if (*i < 5) {
  19378. std::this_thread::sleep_for(std::chrono::seconds(1));
  19379. sink.write("abcd", 4);
  19380. (*i)++;
  19381. } else {
  19382. sink.done();
  19383. }
  19384. return true;
  19385. },
  19386. [i](bool success) {
  19387. EXPECT_FALSE(success);
  19388. delete i;
  19389. });
  19390. });
  19391. svr.Get("/chunked", [&](const Request &, Response &res) {
  19392. auto i = new size_t(0);
  19393. res.set_chunked_content_provider(
  19394. "text/plain",
  19395. [i](size_t, DataSink &sink) {
  19396. if (*i < 5) {
  19397. std::this_thread::sleep_for(std::chrono::seconds(1));
  19398. sink.os << "abcd";
  19399. (*i)++;
  19400. } else {
  19401. sink.done();
  19402. }
  19403. return true;
  19404. },
  19405. [i](bool success) {
  19406. EXPECT_FALSE(success);
  19407. delete i;
  19408. });
  19409. });
  19410. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19411. auto se = detail::scope_exit([&] {
  19412. svr.stop();
  19413. listen_thread.join();
  19414. ASSERT_FALSE(svr.is_running());
  19415. });
  19416. svr.wait_until_ready();
  19417. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19418. {
  19419. auto start = std::chrono::steady_clock::now();
  19420. auto res = cli.Get("/stream");
  19421. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19422. std::chrono::steady_clock::now() - start)
  19423. .count();
  19424. ASSERT_FALSE(res);
  19425. EXPECT_EQ(Error::Read, res.error());
  19426. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19427. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19428. }
  19429. {
  19430. auto start = std::chrono::steady_clock::now();
  19431. auto res = cli.Get("/stream_without_length");
  19432. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19433. std::chrono::steady_clock::now() - start)
  19434. .count();
  19435. ASSERT_FALSE(res);
  19436. EXPECT_EQ(Error::Read, res.error());
  19437. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19438. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19439. }
  19440. {
  19441. auto start = std::chrono::steady_clock::now();
  19442. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19443. EXPECT_EQ("abcd", string(data, data_length));
  19444. return true;
  19445. });
  19446. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19447. std::chrono::steady_clock::now() - start)
  19448. .count();
  19449. ASSERT_FALSE(res);
  19450. EXPECT_EQ(Error::Read, res.error());
  19451. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19452. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19453. }
  19454. }
  19455. TEST(MaxTimeoutTest, ContentStream) {
  19456. time_t timeout = 2000;
  19457. time_t threshold = 200;
  19458. Server svr;
  19459. Client cli("localhost", PORT);
  19460. max_timeout_test(svr, cli, timeout, threshold);
  19461. }
  19462. #ifdef CPPHTTPLIB_SSL_ENABLED
  19463. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19464. time_t timeout = 2000;
  19465. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19466. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19467. SSLClient cli("localhost", PORT);
  19468. cli.enable_server_certificate_verification(false);
  19469. max_timeout_test(svr, cli, timeout, threshold);
  19470. }
  19471. #endif
  19472. class EventDispatcher {
  19473. public:
  19474. EventDispatcher() {}
  19475. bool wait_event(DataSink *sink) {
  19476. unique_lock<mutex> lk(m_);
  19477. int id = id_;
  19478. // Wait with timeout to prevent hanging if client disconnects
  19479. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19480. [&] { return cid_ == id; })) {
  19481. return false; // Timeout occurred
  19482. }
  19483. sink->write(message_.data(), message_.size());
  19484. return true;
  19485. }
  19486. void send_event(const string &message) {
  19487. lock_guard<mutex> lk(m_);
  19488. cid_ = id_++;
  19489. message_ = message;
  19490. cv_.notify_all();
  19491. }
  19492. private:
  19493. mutex m_;
  19494. condition_variable cv_;
  19495. atomic_int id_{0};
  19496. atomic_int cid_{-1};
  19497. string message_;
  19498. };
  19499. TEST(ClientInThreadTest, Issue2068) {
  19500. EventDispatcher ed;
  19501. Server svr;
  19502. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19503. res.set_chunked_content_provider("text/event-stream",
  19504. [&](size_t /*offset*/, DataSink &sink) {
  19505. return ed.wait_event(&sink);
  19506. });
  19507. });
  19508. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19509. svr.wait_until_ready();
  19510. thread event_thread([&] {
  19511. int id = 0;
  19512. while (svr.is_running()) {
  19513. this_thread::sleep_for(chrono::milliseconds(500));
  19514. std::stringstream ss;
  19515. ss << "data: " << id << "\n\n";
  19516. ed.send_event(ss.str());
  19517. id++;
  19518. }
  19519. });
  19520. auto se = detail::scope_exit([&] {
  19521. svr.stop();
  19522. listen_thread.join();
  19523. event_thread.join();
  19524. ASSERT_FALSE(svr.is_running());
  19525. });
  19526. {
  19527. auto client = detail::make_unique<Client>(HOST, PORT);
  19528. client->set_read_timeout(std::chrono::minutes(10));
  19529. std::atomic<bool> stop{false};
  19530. std::thread t([&] {
  19531. client->Get("/event1",
  19532. [&](const char *, size_t) -> bool { return !stop; });
  19533. });
  19534. std::this_thread::sleep_for(std::chrono::seconds(2));
  19535. stop = true;
  19536. client->stop();
  19537. t.join();
  19538. // Reset client after thread has finished
  19539. client.reset();
  19540. }
  19541. }
  19542. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19543. auto handled = false;
  19544. Server svr;
  19545. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19546. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19547. auto se = detail::scope_exit([&] {
  19548. svr.stop();
  19549. t.join();
  19550. ASSERT_FALSE(svr.is_running());
  19551. ASSERT_FALSE(handled);
  19552. });
  19553. svr.wait_until_ready();
  19554. // Two Content-Length headers with different values — must be rejected
  19555. auto req = "POST /test HTTP/1.1\r\n"
  19556. "Content-Length: 5\r\n"
  19557. "Content-Length: 10\r\n"
  19558. "\r\n"
  19559. "hello";
  19560. std::string response;
  19561. ASSERT_TRUE(send_request(1, req, &response));
  19562. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19563. response.substr(0, response.find("\r\n")));
  19564. }
  19565. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19566. auto handled = false;
  19567. Server svr;
  19568. svr.Post("/test", [&](const Request &, Response &res) {
  19569. handled = true;
  19570. res.set_content("ok", "text/plain");
  19571. });
  19572. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19573. auto se = detail::scope_exit([&] {
  19574. svr.stop();
  19575. t.join();
  19576. ASSERT_FALSE(svr.is_running());
  19577. ASSERT_TRUE(handled);
  19578. });
  19579. svr.wait_until_ready();
  19580. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19581. auto req = "POST /test HTTP/1.1\r\n"
  19582. "Host: localhost\r\n"
  19583. "Content-Length: 5\r\n"
  19584. "Content-Length: 5\r\n"
  19585. "\r\n"
  19586. "hello";
  19587. std::string response;
  19588. ASSERT_TRUE(send_request(1, req, &response));
  19589. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19590. }
  19591. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19592. Server svr;
  19593. svr.Get("/test", [](const Request &, Response &res) {
  19594. res.set_content("ok", "text/plain");
  19595. });
  19596. auto port = svr.bind_to_any_port(HOST);
  19597. thread t = thread([&] { svr.listen_after_bind(); });
  19598. auto se = detail::scope_exit([&] {
  19599. svr.stop();
  19600. t.join();
  19601. ASSERT_FALSE(svr.is_running());
  19602. });
  19603. svr.wait_until_ready();
  19604. auto status_line = [&](const std::string &host_lines) {
  19605. std::string res;
  19606. send_request(
  19607. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19608. &res, port);
  19609. return res.substr(0, res.find("\r\n"));
  19610. };
  19611. const char *accepted[] = {
  19612. "Host: localhost\r\n",
  19613. "Host: a.example:8080\r\n",
  19614. "Host: my_service\r\n",
  19615. "Host: [::1]:8080\r\n",
  19616. "Host: [fe80::1%25eth0]\r\n",
  19617. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19618. };
  19619. for (auto host_lines : accepted) {
  19620. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19621. }
  19622. const char *rejected[] = {
  19623. "Host: a.example\r\nHost: b.example\r\n",
  19624. "Host: a.example\r\nHost: a.example\r\n",
  19625. "Host: a@b.example\r\n",
  19626. "Host: a.example/b\r\n",
  19627. "Host: a.example\\b\r\n",
  19628. "Host: a.example?b\r\n",
  19629. "Host: a.example#b\r\n",
  19630. "Host: a.example b.example\r\n",
  19631. };
  19632. for (auto host_lines : rejected) {
  19633. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19634. << host_lines;
  19635. }
  19636. }
  19637. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19638. Server svr;
  19639. svr.Get("/", [](const Request &req, Response &res) {
  19640. EXPECT_EQ(2U, req.trailers.size());
  19641. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19642. // Denied
  19643. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19644. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19645. // Accepted
  19646. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19647. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19648. EXPECT_TRUE(req.has_trailer("X-World"));
  19649. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19650. res.set_content("ok", "text/plain");
  19651. });
  19652. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19653. auto se = detail::scope_exit([&] {
  19654. svr.stop();
  19655. t.join();
  19656. ASSERT_FALSE(svr.is_running());
  19657. });
  19658. svr.wait_until_ready();
  19659. const std::string req = "GET / HTTP/1.1\r\n"
  19660. "Transfer-Encoding: chunked\r\n"
  19661. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19662. "\r\n"
  19663. "0\r\n"
  19664. "Content-Length: 10\r\n"
  19665. "Host: internal.local\r\n"
  19666. "Content-Type: malicious/content\r\n"
  19667. "Cookie: any\r\n"
  19668. "Set-Cookie: any\r\n"
  19669. "X-Forwarded-For: attacker.com\r\n"
  19670. "X-Real-Ip: 1.1.1.1\r\n"
  19671. "X-Hello: hello\r\n"
  19672. "X-World: world\r\n"
  19673. "\r\n";
  19674. std::string res;
  19675. ASSERT_TRUE(send_request(1, req, &res));
  19676. }
  19677. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19678. // several field lines, and the combined value is what has to be parsed. A
  19679. // Trailer field split across lines therefore declares every name it lists;
  19680. // reading only the first line silently drops the trailers the later lines
  19681. // declare. The prohibited-trailer filter still applies to every line.
  19682. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19683. Server svr;
  19684. size_t observed_trailer_count = 0;
  19685. std::string observed_hello;
  19686. std::string observed_world;
  19687. bool observed_content_length = true;
  19688. svr.Get("/", [&](const Request &req, Response &res) {
  19689. observed_trailer_count = req.trailers.size();
  19690. observed_hello = req.get_trailer_value("X-Hello");
  19691. observed_world = req.get_trailer_value("X-World");
  19692. observed_content_length = req.has_trailer("Content-Length");
  19693. res.set_content("ok", "text/plain");
  19694. });
  19695. auto port = svr.bind_to_any_port(HOST);
  19696. thread t = thread([&]() { svr.listen_after_bind(); });
  19697. auto se = detail::scope_exit([&] {
  19698. svr.stop();
  19699. t.join();
  19700. ASSERT_FALSE(svr.is_running());
  19701. });
  19702. svr.wait_until_ready();
  19703. const std::string req = "GET / HTTP/1.1\r\n"
  19704. "Host: localhost\r\n"
  19705. "Transfer-Encoding: chunked\r\n"
  19706. "Trailer: X-Hello\r\n"
  19707. "Trailer: X-World, Content-Length\r\n"
  19708. "\r\n"
  19709. "0\r\n"
  19710. "X-Hello: hello\r\n"
  19711. "X-World: world\r\n"
  19712. "Content-Length: 10\r\n"
  19713. "\r\n";
  19714. std::string res;
  19715. ASSERT_TRUE(send_request(1, req, &res, port));
  19716. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19717. // Accepted: both field lines contribute to the declared set
  19718. EXPECT_EQ(2U, observed_trailer_count);
  19719. EXPECT_EQ(observed_hello, "hello");
  19720. EXPECT_EQ(observed_world, "world");
  19721. // Denied: a prohibited name stays prohibited on a later field line
  19722. EXPECT_FALSE(observed_content_length);
  19723. }
  19724. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19725. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19726. // unbounded run of fields that are never declared, because the counter would
  19727. // only advance for declared fields.
  19728. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19729. Server svr;
  19730. bool handler_called = false;
  19731. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19732. handler_called = true;
  19733. res.set_content("ok", "text/plain");
  19734. });
  19735. auto port = svr.bind_to_any_port(HOST);
  19736. thread t = thread([&]() { svr.listen_after_bind(); });
  19737. auto se = detail::scope_exit([&] {
  19738. svr.stop();
  19739. t.join();
  19740. ASSERT_FALSE(svr.is_running());
  19741. });
  19742. svr.wait_until_ready();
  19743. // Declare nothing, then send far more undeclared trailer fields than the
  19744. // header-count limit. Parsing must stop and reject the request rather than
  19745. // read every line.
  19746. std::string req = "GET / HTTP/1.1\r\n"
  19747. "Transfer-Encoding: chunked\r\n"
  19748. "\r\n"
  19749. "0\r\n";
  19750. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19751. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19752. }
  19753. req += "\r\n";
  19754. std::string res;
  19755. ASSERT_TRUE(send_request(1, req, &res, port));
  19756. // The request is rejected before the handler runs.
  19757. EXPECT_FALSE(handler_called);
  19758. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19759. }
  19760. // The set of declared trailer names is capped so a peer cannot grow it without
  19761. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19762. // declared past the cap is not honored, even if the field is actually sent.
  19763. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19764. Server svr;
  19765. // One name inside the cap and one past it, so the test tracks the cap rather
  19766. // than a fixed count.
  19767. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19768. const std::string within_cap_name = "X-T-0";
  19769. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19770. bool observed_within_cap = false;
  19771. bool observed_past_cap = false;
  19772. svr.Get("/", [&](const Request &req, Response &res) {
  19773. observed_within_cap = req.has_trailer(within_cap_name);
  19774. observed_past_cap = req.has_trailer(past_cap_name);
  19775. res.set_content("ok", "text/plain");
  19776. });
  19777. auto port = svr.bind_to_any_port(HOST);
  19778. thread t = thread([&]() { svr.listen_after_bind(); });
  19779. auto se = detail::scope_exit([&] {
  19780. svr.stop();
  19781. t.join();
  19782. ASSERT_FALSE(svr.is_running());
  19783. });
  19784. svr.wait_until_ready();
  19785. // Declare more trailer names than the cap in a single Trailer field, then
  19786. // actually send the first (within the cap) and the last (past it).
  19787. std::string trailer_decl = "Trailer: ";
  19788. for (int i = 0; i < declared_count; i++) {
  19789. if (i != 0) { trailer_decl += ", "; }
  19790. trailer_decl += "X-T-" + std::to_string(i);
  19791. }
  19792. trailer_decl += "\r\n";
  19793. const std::string req = "GET / HTTP/1.1\r\n"
  19794. "Host: localhost\r\n"
  19795. "Transfer-Encoding: chunked\r\n" +
  19796. trailer_decl +
  19797. "\r\n"
  19798. "0\r\n" +
  19799. within_cap_name + ": a\r\n" + past_cap_name +
  19800. ": b\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, res.find("\r\n")));
  19805. // A name within the cap is honored; one declared past the cap is dropped.
  19806. EXPECT_TRUE(observed_within_cap);
  19807. EXPECT_FALSE(observed_past_cap);
  19808. }
  19809. // A direct client that is not listed in trusted_proxies must not be able to
  19810. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19811. // the peer address on the actual TCP connection determines whether the
  19812. // header is honored.
  19813. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19814. Server svr;
  19815. // Deliberately does NOT include the loopback address the test client
  19816. // actually connects from, so the direct connection is not a trusted proxy.
  19817. svr.set_trusted_proxies({"203.0.113.66"});
  19818. std::string observed_remote_addr;
  19819. svr.Get("/ip", [&](const Request &req, Response &res) {
  19820. observed_remote_addr = req.remote_addr;
  19821. res.set_content("ok", "text/plain");
  19822. });
  19823. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19824. auto se = detail::scope_exit([&] {
  19825. svr.stop();
  19826. t.join();
  19827. ASSERT_FALSE(svr.is_running());
  19828. });
  19829. svr.wait_until_ready();
  19830. Client cli(HOST, PORT);
  19831. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19833. EXPECT_EQ(StatusCode::OK_200, res->status);
  19834. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19835. // ignored entirely and the real connection-level address retained.
  19836. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19837. observed_remote_addr == "127.0.0.1");
  19838. }
  19839. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19840. Server svr;
  19841. std::string observed_remote_addr;
  19842. std::string observed_xff;
  19843. svr.Get("/ip", [&](const Request &req, Response &res) {
  19844. observed_remote_addr = req.remote_addr;
  19845. observed_xff = req.get_header_value("X-Forwarded-For");
  19846. res.set_content("ok", "text/plain");
  19847. });
  19848. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19849. auto se = detail::scope_exit([&] {
  19850. svr.stop();
  19851. t.join();
  19852. ASSERT_FALSE(svr.is_running());
  19853. });
  19854. svr.wait_until_ready();
  19855. Client cli(HOST, PORT);
  19856. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19858. EXPECT_EQ(StatusCode::OK_200, res->status);
  19859. EXPECT_EQ(observed_xff, "203.0.113.66");
  19860. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19861. observed_remote_addr == "127.0.0.1");
  19862. }
  19863. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19864. Server svr;
  19865. svr.set_trusted_proxies({"203.0.113.66"});
  19866. std::string observed_remote_addr;
  19867. std::string observed_xff;
  19868. svr.Get("/ip", [&](const Request &req, Response &res) {
  19869. observed_remote_addr = req.remote_addr;
  19870. observed_xff = req.get_header_value("X-Forwarded-For");
  19871. res.set_content("ok", "text/plain");
  19872. });
  19873. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19874. auto se = detail::scope_exit([&] {
  19875. svr.stop();
  19876. t.join();
  19877. ASSERT_FALSE(svr.is_running());
  19878. });
  19879. svr.wait_until_ready();
  19880. Client cli(HOST, PORT);
  19881. auto res = cli.Get("/ip");
  19882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19883. EXPECT_EQ(StatusCode::OK_200, res->status);
  19884. EXPECT_EQ(observed_xff, "");
  19885. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19886. observed_remote_addr == "127.0.0.1");
  19887. }
  19888. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19889. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19890. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19891. Server svr;
  19892. svr.set_trusted_proxies({"127.0.0.1"});
  19893. svr.Get("/ip", [](const Request &req, Response &res) {
  19894. res.set_content(req.remote_addr, "text/plain");
  19895. });
  19896. auto port = svr.bind_to_any_port("::");
  19897. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19898. thread t = thread([&] { svr.listen_after_bind(); });
  19899. auto se = detail::scope_exit([&] {
  19900. svr.stop();
  19901. t.join();
  19902. ASSERT_FALSE(svr.is_running());
  19903. });
  19904. svr.wait_until_ready();
  19905. Client cli("127.0.0.1", port);
  19906. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19908. EXPECT_EQ("198.51.100.23", res->body);
  19909. }
  19910. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19911. Server svr;
  19912. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19913. svr.Get("/ip", [](const Request &req, Response &res) {
  19914. res.set_content(req.remote_addr, "text/plain");
  19915. });
  19916. auto port = svr.bind_to_any_port(HOST);
  19917. ASSERT_GT(port, 0);
  19918. thread t = thread([&] { svr.listen_after_bind(); });
  19919. auto se = detail::scope_exit([&] {
  19920. svr.stop();
  19921. t.join();
  19922. ASSERT_FALSE(svr.is_running());
  19923. });
  19924. svr.wait_until_ready();
  19925. Client cli(HOST, port);
  19926. auto res = cli.Get(
  19927. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19929. EXPECT_EQ("198.51.100.23", res->body);
  19930. }
  19931. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19932. Server svr;
  19933. // Include the loopback address the test client actually connects from, so
  19934. // the direct connection itself is recognized as the trusted proxy hop.
  19935. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19936. std::string observed_remote_addr;
  19937. std::string observed_xff;
  19938. svr.Get("/ip", [&](const Request &req, Response &res) {
  19939. observed_remote_addr = req.remote_addr;
  19940. observed_xff = req.get_header_value("X-Forwarded-For");
  19941. res.set_content("ok", "text/plain");
  19942. });
  19943. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19944. auto se = detail::scope_exit([&] {
  19945. svr.stop();
  19946. t.join();
  19947. ASSERT_FALSE(svr.is_running());
  19948. });
  19949. svr.wait_until_ready();
  19950. Client cli(HOST, PORT);
  19951. auto res = cli.Get(
  19952. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19954. EXPECT_EQ(StatusCode::OK_200, res->status);
  19955. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19956. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19957. }
  19958. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19959. Server svr;
  19960. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19961. std::string observed_remote_addr;
  19962. std::string observed_xff;
  19963. svr.Get("/ip", [&](const Request &req, Response &res) {
  19964. observed_remote_addr = req.remote_addr;
  19965. observed_xff = req.get_header_value("X-Forwarded-For");
  19966. res.set_content("ok", "text/plain");
  19967. });
  19968. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19969. auto se = detail::scope_exit([&] {
  19970. svr.stop();
  19971. t.join();
  19972. ASSERT_FALSE(svr.is_running());
  19973. });
  19974. svr.wait_until_ready();
  19975. Client cli(HOST, PORT);
  19976. auto res = cli.Get(
  19977. "/ip",
  19978. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19980. EXPECT_EQ(StatusCode::OK_200, res->status);
  19981. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19982. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19983. }
  19984. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19985. Server svr;
  19986. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19987. std::string observed_remote_addr;
  19988. std::string observed_xff;
  19989. svr.Get("/ip", [&](const Request &req, Response &res) {
  19990. observed_remote_addr = req.remote_addr;
  19991. observed_xff = req.get_header_value("X-Forwarded-For");
  19992. res.set_content("ok", "text/plain");
  19993. });
  19994. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19995. auto se = detail::scope_exit([&] {
  19996. svr.stop();
  19997. t.join();
  19998. ASSERT_FALSE(svr.is_running());
  19999. });
  20000. svr.wait_until_ready();
  20001. Client cli(HOST, PORT);
  20002. auto res = cli.Get(
  20003. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20005. EXPECT_EQ(StatusCode::OK_200, res->status);
  20006. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20007. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20008. // and must not be selected.
  20009. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20010. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20011. }
  20012. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20013. Server svr;
  20014. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20015. std::string observed_remote_addr;
  20016. svr.Get("/ip", [&](const Request &req, Response &res) {
  20017. observed_remote_addr = req.remote_addr;
  20018. res.set_content("ok", "text/plain");
  20019. });
  20020. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20021. auto se = detail::scope_exit([&] {
  20022. svr.stop();
  20023. t.join();
  20024. ASSERT_FALSE(svr.is_running());
  20025. });
  20026. svr.wait_until_ready();
  20027. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20028. // a forged address and the trusted proxy's own address; the forged value must
  20029. // not win over the address the trusted proxy actually recorded.
  20030. Client cli(HOST, PORT);
  20031. auto res = cli.Get(
  20032. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20034. EXPECT_EQ(StatusCode::OK_200, res->status);
  20035. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20036. }
  20037. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20038. Server svr;
  20039. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20040. std::string observed_remote_addr;
  20041. std::string observed_xff;
  20042. svr.Get("/ip", [&](const Request &req, Response &res) {
  20043. observed_remote_addr = req.remote_addr;
  20044. observed_xff = req.get_header_value("X-Forwarded-For");
  20045. res.set_content("ok", "text/plain");
  20046. });
  20047. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20048. auto se = detail::scope_exit([&] {
  20049. svr.stop();
  20050. t.join();
  20051. ASSERT_FALSE(svr.is_running());
  20052. });
  20053. svr.wait_until_ready();
  20054. Client cli(HOST, PORT);
  20055. auto res = cli.Get(
  20056. "/ip",
  20057. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20059. EXPECT_EQ(StatusCode::OK_200, res->status);
  20060. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20061. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20062. }
  20063. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20064. Server svr;
  20065. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20066. std::string observed_remote_addr;
  20067. std::string observed_xff;
  20068. svr.Get("/ip", [&](const Request &req, Response &res) {
  20069. observed_remote_addr = req.remote_addr;
  20070. observed_xff = req.get_header_value("X-Forwarded-For");
  20071. res.set_content("ok", "text/plain");
  20072. });
  20073. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20074. auto se = detail::scope_exit([&] {
  20075. svr.stop();
  20076. t.join();
  20077. ASSERT_FALSE(svr.is_running());
  20078. });
  20079. svr.wait_until_ready();
  20080. std::string raw_req =
  20081. "GET /ip HTTP/1.1\r\n"
  20082. "Host: localhost\r\n"
  20083. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20084. "Connection: close\r\n"
  20085. "\r\n";
  20086. std::string out;
  20087. ASSERT_TRUE(send_request(5, raw_req, &out));
  20088. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20089. // Header parser trims surrounding whitespace of the header value
  20090. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20091. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20092. }
  20093. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20094. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20095. // their own X-Forwarded-For as a separate field line rather than extending the
  20096. // one the client sent, so every occurrence has to be taken into account.
  20097. // Reading only the first one hands back the address the client chose.
  20098. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20099. Server svr;
  20100. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20101. std::string observed_remote_addr;
  20102. size_t observed_xff_count = 0;
  20103. svr.Get("/ip", [&](const Request &req, Response &res) {
  20104. observed_remote_addr = req.remote_addr;
  20105. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20106. res.set_content("ok", "text/plain");
  20107. });
  20108. auto port = svr.bind_to_any_port(HOST);
  20109. thread t = thread([&]() { svr.listen_after_bind(); });
  20110. auto se = detail::scope_exit([&] {
  20111. svr.stop();
  20112. t.join();
  20113. ASSERT_FALSE(svr.is_running());
  20114. });
  20115. svr.wait_until_ready();
  20116. // The client supplies the first field line; the trusted proxy appends the
  20117. // address it observed as a second one.
  20118. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20119. "Host: localhost\r\n"
  20120. "X-Forwarded-For: 1.2.3.4\r\n"
  20121. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20122. "Connection: close\r\n"
  20123. "\r\n";
  20124. std::string out;
  20125. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20126. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20127. EXPECT_EQ(observed_xff_count, 2U);
  20128. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20129. // The same chain spread over one field line per hop derives the same client
  20130. // address, i.e. the split and the comma-joined representations agree.
  20131. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20132. "Host: localhost\r\n"
  20133. "X-Forwarded-For: 1.2.3.4\r\n"
  20134. "X-Forwarded-For: 198.51.100.23\r\n"
  20135. "X-Forwarded-For: 192.0.2.45\r\n"
  20136. "Connection: close\r\n"
  20137. "\r\n";
  20138. out.clear();
  20139. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20140. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20141. EXPECT_EQ(observed_xff_count, 3U);
  20142. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20143. }
  20144. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20145. // crash the server (it used to call front() on an empty vector inside
  20146. // get_client_ip). The connection-level remote address must be retained instead.
  20147. static void run_malformed_xff_test(const std::string &xff_value) {
  20148. Server svr;
  20149. svr.set_trusted_proxies({"192.0.2.45"});
  20150. std::string observed_remote_addr;
  20151. svr.Get("/ip", [&](const Request &req, Response &res) {
  20152. observed_remote_addr = req.remote_addr;
  20153. res.set_content("ok", "text/plain");
  20154. });
  20155. int port = 0;
  20156. thread t = thread([&]() {
  20157. port = svr.bind_to_any_port(HOST);
  20158. svr.listen_after_bind();
  20159. });
  20160. auto se = detail::scope_exit([&] {
  20161. svr.stop();
  20162. t.join();
  20163. ASSERT_FALSE(svr.is_running());
  20164. });
  20165. svr.wait_until_ready();
  20166. Client cli(HOST, port);
  20167. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20169. EXPECT_EQ(StatusCode::OK_200, res->status);
  20170. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20171. observed_remote_addr == "127.0.0.1");
  20172. }
  20173. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20174. run_malformed_xff_test("");
  20175. }
  20176. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20177. run_malformed_xff_test(",");
  20178. }
  20179. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20180. run_malformed_xff_test(", , ,");
  20181. }
  20182. // The same rule applies to Accept: a request whose acceptable types are spread
  20183. // over several field lines must be negotiated against all of them.
  20184. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20185. // case-insensitive connection options. Comparing the whole field value against
  20186. // one option misses a client that sends several of them, and misses every
  20187. // casing but the one written in the comparison.
  20188. //
  20189. // Sends req, reads the response, then reuses the same socket for a second
  20190. // request to find out whether the server kept the connection.
  20191. static void probe_connection_reuse(int port, const std::string &req,
  20192. bool *announced_close, bool *reusable) {
  20193. auto error = Error::Success;
  20194. auto sock = detail::create_client_socket(
  20195. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20196. /*connection_timeout_sec=*/5, 0,
  20197. /*read_timeout_sec=*/1, 0,
  20198. /*write_timeout_sec=*/5, 0, std::string(), error);
  20199. ASSERT_NE(sock, INVALID_SOCKET);
  20200. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20201. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20202. "Host: localhost\r\n"
  20203. "Connection: close\r\n"
  20204. "\r\n";
  20205. std::string first_response;
  20206. std::string second_response;
  20207. detail::process_client_socket(
  20208. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20209. [&](Stream &strm) {
  20210. if (strm.write(req.data(), req.size()) !=
  20211. static_cast<ssize_t>(req.size())) {
  20212. return false;
  20213. }
  20214. char buf[512];
  20215. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20216. // Headers plus the two-byte body of the handler below
  20217. while (reader.getline()) {
  20218. first_response += reader.ptr();
  20219. if (first_response.find("ok") != std::string::npos) { break; }
  20220. }
  20221. if (strm.write(second.data(), second.size()) !=
  20222. static_cast<ssize_t>(second.size())) {
  20223. return true;
  20224. }
  20225. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20226. while (reader2.getline()) {
  20227. second_response += reader2.ptr();
  20228. if (second_response.find("ok") != std::string::npos) { break; }
  20229. }
  20230. return true;
  20231. });
  20232. *announced_close =
  20233. first_response.find("Connection: close") != std::string::npos;
  20234. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20235. }
  20236. class ConnectionTokenTest : public ::testing::Test {
  20237. protected:
  20238. void SetUp() override {
  20239. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20240. res.set_content("ok", "text/plain");
  20241. });
  20242. port_ = svr_.bind_to_any_port(HOST);
  20243. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20244. svr_.wait_until_ready();
  20245. }
  20246. void TearDown() override {
  20247. svr_.stop();
  20248. if (thread_.joinable()) { thread_.join(); }
  20249. }
  20250. Server svr_;
  20251. int port_ = 0;
  20252. thread thread_;
  20253. };
  20254. // "close" alongside another option still closes the connection, and the
  20255. // response says so rather than leaving the peer to discover it.
  20256. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20257. bool announced_close = false;
  20258. bool reusable = true;
  20259. probe_connection_reuse(port_,
  20260. "GET /keepalive HTTP/1.1\r\n"
  20261. "Host: localhost\r\n"
  20262. "Connection: keep-alive, close\r\n"
  20263. "\r\n",
  20264. &announced_close, &reusable);
  20265. EXPECT_TRUE(announced_close);
  20266. EXPECT_FALSE(reusable);
  20267. }
  20268. // "close" split over two field lines is the same list, so it is honored too.
  20269. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20270. bool announced_close = false;
  20271. bool reusable = true;
  20272. probe_connection_reuse(port_,
  20273. "GET /keepalive HTTP/1.1\r\n"
  20274. "Host: localhost\r\n"
  20275. "Connection: keep-alive\r\n"
  20276. "Connection: close\r\n"
  20277. "\r\n",
  20278. &announced_close, &reusable);
  20279. EXPECT_TRUE(announced_close);
  20280. EXPECT_FALSE(reusable);
  20281. }
  20282. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20283. // keep-alive in the spelling everyone actually sends keeps its connection.
  20284. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20285. bool announced_close = false;
  20286. bool reusable = false;
  20287. probe_connection_reuse(port_,
  20288. "GET /keepalive HTTP/1.0\r\n"
  20289. "Host: localhost\r\n"
  20290. "Connection: keep-alive\r\n"
  20291. "\r\n",
  20292. &announced_close, &reusable);
  20293. EXPECT_FALSE(announced_close);
  20294. EXPECT_TRUE(reusable);
  20295. }
  20296. // A token the value merely contains is not the token itself.
  20297. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20298. bool announced_close = false;
  20299. bool reusable = false;
  20300. probe_connection_reuse(port_,
  20301. "GET /keepalive HTTP/1.1\r\n"
  20302. "Host: localhost\r\n"
  20303. "Connection: notclose\r\n"
  20304. "\r\n",
  20305. &announced_close, &reusable);
  20306. EXPECT_FALSE(announced_close);
  20307. EXPECT_TRUE(reusable);
  20308. }
  20309. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20310. Server svr;
  20311. std::vector<std::string> observed_types;
  20312. svr.Get("/", [&](const Request &req, Response &res) {
  20313. observed_types = req.accept_content_types;
  20314. res.set_content("ok", "text/plain");
  20315. });
  20316. auto port = svr.bind_to_any_port(HOST);
  20317. thread t = thread([&]() { svr.listen_after_bind(); });
  20318. auto se = detail::scope_exit([&] {
  20319. svr.stop();
  20320. t.join();
  20321. ASSERT_FALSE(svr.is_running());
  20322. });
  20323. svr.wait_until_ready();
  20324. Client cli(HOST, port);
  20325. Headers headers;
  20326. headers.emplace("Accept", "text/plain;q=0.5");
  20327. headers.emplace("Accept", "application/json");
  20328. auto res = cli.Get("/", headers);
  20329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20330. EXPECT_EQ(StatusCode::OK_200, res->status);
  20331. // Sorted by q-value, so the second field line's type comes first
  20332. ASSERT_EQ(2U, observed_types.size());
  20333. EXPECT_EQ("application/json", observed_types[0]);
  20334. EXPECT_EQ("text/plain", observed_types[1]);
  20335. }
  20336. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20337. // empty field line must not contribute a bare comma to the combined value.
  20338. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20339. Server svr;
  20340. std::vector<std::string> observed_types;
  20341. svr.Get("/", [&](const Request &req, Response &res) {
  20342. observed_types = req.accept_content_types;
  20343. res.set_content("ok", "text/plain");
  20344. });
  20345. auto port = svr.bind_to_any_port(HOST);
  20346. thread t = thread([&]() { svr.listen_after_bind(); });
  20347. auto se = detail::scope_exit([&] {
  20348. svr.stop();
  20349. t.join();
  20350. ASSERT_FALSE(svr.is_running());
  20351. });
  20352. svr.wait_until_ready();
  20353. // Empty first field line, then a real one
  20354. std::string raw_req = "GET / HTTP/1.1\r\n"
  20355. "Host: localhost\r\n"
  20356. "Accept:\r\n"
  20357. "Accept: application/json\r\n"
  20358. "Connection: close\r\n"
  20359. "\r\n";
  20360. std::string out;
  20361. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20362. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20363. ASSERT_EQ(1U, observed_types.size());
  20364. EXPECT_EQ("application/json", observed_types[0]);
  20365. }
  20366. // The skip in get_combined_header_value() is what keeps an empty field line
  20367. // from contributing a bare comma. Only a trailing empty field line exercises
  20368. // it: a leading one is already covered by the "combined is still empty" check,
  20369. // and parse_accept_header() now ignores the empty element either way, so the
  20370. // request-level test above can no longer tell the two apart.
  20371. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20372. Headers headers;
  20373. headers.emplace("Accept", "text/html");
  20374. headers.emplace("Accept", "");
  20375. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20376. headers.clear();
  20377. headers.emplace("Accept", "");
  20378. headers.emplace("Accept", "application/json");
  20379. EXPECT_EQ("application/json",
  20380. detail::get_combined_header_value(headers, "Accept"));
  20381. }
  20382. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20383. // An encoding offered on a later Accept-Encoding field line is still offered.
  20384. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20385. Server svr;
  20386. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20387. res.set_content(std::string(1024, 'x'), "text/plain");
  20388. });
  20389. auto port = svr.bind_to_any_port(HOST);
  20390. thread t = thread([&]() { svr.listen_after_bind(); });
  20391. auto se = detail::scope_exit([&] {
  20392. svr.stop();
  20393. t.join();
  20394. ASSERT_FALSE(svr.is_running());
  20395. });
  20396. svr.wait_until_ready();
  20397. Client cli(HOST, port);
  20398. cli.set_decompress(false);
  20399. Headers headers;
  20400. headers.emplace("Accept-Encoding", "identity");
  20401. headers.emplace("Accept-Encoding", "gzip");
  20402. auto res = cli.Get("/", headers);
  20403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20404. EXPECT_EQ(StatusCode::OK_200, res->status);
  20405. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20406. }
  20407. #endif
  20408. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20409. // Transfer-Encoding is not its body.
  20410. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20411. Server svr;
  20412. svr.set_payload_max_length(8);
  20413. svr.Post("/test", [](const Request &, Response &res) {
  20414. res.set_content("ok", "text/plain");
  20415. });
  20416. auto port = svr.bind_to_any_port(HOST);
  20417. ASSERT_GT(port, 0);
  20418. thread t = thread([&] { svr.listen_after_bind(); });
  20419. auto se = detail::scope_exit([&] {
  20420. svr.stop();
  20421. t.join();
  20422. ASSERT_FALSE(svr.is_running());
  20423. });
  20424. svr.wait_until_ready();
  20425. std::string resp;
  20426. ASSERT_TRUE(send_request(1,
  20427. "POST /test HTTP/1.1\r\n"
  20428. "Host: localhost\r\n"
  20429. "Connection: close\r\n"
  20430. "\r\n" +
  20431. std::string(16, 'X'),
  20432. &resp, port));
  20433. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20434. }
  20435. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20436. Server svr;
  20437. svr.Post("/post", [&](const Request &req, Response &res) {
  20438. res.set_content(req.body, "text/plain");
  20439. });
  20440. svr.Put("/put", [&](const Request &req, Response &res) {
  20441. res.set_content(req.body, "text/plain");
  20442. });
  20443. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20444. res.set_content(req.body, "text/plain");
  20445. });
  20446. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20447. res.set_content(req.body, "text/plain");
  20448. });
  20449. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20450. auto se = detail::scope_exit([&] {
  20451. svr.stop();
  20452. t.join();
  20453. ASSERT_FALSE(svr.is_running());
  20454. });
  20455. svr.wait_until_ready();
  20456. std::string resp;
  20457. // POST without Content-Length
  20458. ASSERT_TRUE(send_request(5,
  20459. "POST /post HTTP/1.1\r\n"
  20460. "Host: localhost\r\n"
  20461. "Connection: close\r\n"
  20462. "\r\n",
  20463. &resp));
  20464. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20465. // PUT without Content-Length
  20466. resp.clear();
  20467. ASSERT_TRUE(send_request(5,
  20468. "PUT /put HTTP/1.1\r\n"
  20469. "Host: localhost\r\n"
  20470. "Connection: close\r\n"
  20471. "\r\n",
  20472. &resp));
  20473. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20474. // PATCH without Content-Length
  20475. resp.clear();
  20476. ASSERT_TRUE(send_request(5,
  20477. "PATCH /patch HTTP/1.1\r\n"
  20478. "Host: localhost\r\n"
  20479. "Connection: close\r\n"
  20480. "\r\n",
  20481. &resp));
  20482. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20483. // DELETE without Content-Length
  20484. resp.clear();
  20485. ASSERT_TRUE(send_request(5,
  20486. "DELETE /delete HTTP/1.1\r\n"
  20487. "Host: localhost\r\n"
  20488. "Connection: close\r\n"
  20489. "\r\n",
  20490. &resp));
  20491. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20492. }
  20493. //==============================================================================
  20494. // open_stream() Tests
  20495. //==============================================================================
  20496. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20497. std::string result;
  20498. char buf[8192];
  20499. ssize_t n;
  20500. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20501. result.append(buf, static_cast<size_t>(n));
  20502. }
  20503. return result;
  20504. }
  20505. // Mock stream for unit tests
  20506. class MockStream : public Stream {
  20507. public:
  20508. std::string data;
  20509. size_t pos = 0;
  20510. ssize_t error_after = -1; // -1 = no error
  20511. explicit MockStream(const std::string &d, ssize_t err = -1)
  20512. : data(d), error_after(err) {}
  20513. bool is_readable() const override { return true; }
  20514. bool wait_readable() const override { return true; }
  20515. bool wait_writable() const override { return true; }
  20516. ssize_t read(char *ptr, size_t size) override {
  20517. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20518. if (pos >= data.size()) return 0;
  20519. size_t limit =
  20520. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20521. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20522. std::memcpy(ptr, data.data() + pos, to_read);
  20523. pos += to_read;
  20524. return static_cast<ssize_t>(to_read);
  20525. }
  20526. ssize_t write(const char *, size_t) override { return -1; }
  20527. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20528. ip = "127.0.0.1";
  20529. port = 0;
  20530. }
  20531. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20532. ip = "127.0.0.1";
  20533. port = 0;
  20534. }
  20535. socket_t socket() const override { return INVALID_SOCKET; }
  20536. time_t duration() const override { return 0; }
  20537. };
  20538. TEST(StreamHandleTest, Basic) {
  20539. ClientImpl::StreamHandle handle;
  20540. EXPECT_FALSE(handle.is_valid());
  20541. handle.response = detail::make_unique<Response>();
  20542. handle.error = Error::Connection;
  20543. EXPECT_FALSE(handle.is_valid());
  20544. handle.error = Error::Success;
  20545. EXPECT_TRUE(handle.is_valid());
  20546. }
  20547. TEST(BodyReaderTest, Basic) {
  20548. MockStream stream("Hello, World!");
  20549. detail::BodyReader reader;
  20550. reader.stream = &stream;
  20551. reader.content_length = 13;
  20552. char buf[32];
  20553. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20554. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20555. EXPECT_TRUE(reader.eof);
  20556. }
  20557. TEST(BodyReaderTest, NoStream) {
  20558. detail::BodyReader reader;
  20559. char buf[32];
  20560. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20561. EXPECT_EQ(Error::Connection, reader.last_error);
  20562. }
  20563. TEST(BodyReaderTest, Error) {
  20564. MockStream stream("Hello, World!", 5);
  20565. detail::BodyReader reader;
  20566. reader.stream = &stream;
  20567. reader.content_length = 13;
  20568. char buf[32];
  20569. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20570. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20571. EXPECT_EQ(Error::Read, reader.last_error);
  20572. }
  20573. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20574. // Mock-based StreamHandle tests relying on private internals are removed.
  20575. class OpenStreamTest : public ::testing::Test {
  20576. protected:
  20577. void SetUp() override {
  20578. svr_.Get("/hello", [](const Request &, Response &res) {
  20579. res.set_content("Hello World!", "text/plain");
  20580. });
  20581. svr_.Get("/large", [](const Request &, Response &res) {
  20582. res.set_content(std::string(10000, 'X'), "text/plain");
  20583. });
  20584. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20585. res.set_content("Hello World!", "image/jpeg");
  20586. res.set_header("Content-Encoding", "UTF-8");
  20587. });
  20588. svr_.Get("/chunked", [](const Request &, Response &res) {
  20589. res.set_chunked_content_provider("text/plain",
  20590. [](size_t offset, DataSink &sink) {
  20591. if (offset < 15) {
  20592. sink.write("chunk", 5);
  20593. return true;
  20594. }
  20595. sink.done();
  20596. return true;
  20597. });
  20598. });
  20599. svr_.Get("/compressible", [](const Request &, Response &res) {
  20600. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20601. DataSink &sink) {
  20602. if (offset < 100 * 1024) {
  20603. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20604. sink.write(chunk.data(), chunk.size());
  20605. return true;
  20606. }
  20607. sink.done();
  20608. return true;
  20609. });
  20610. });
  20611. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20612. [](const Request & /*req*/, Response &res) {
  20613. auto i = new int(0);
  20614. res.set_header("Trailer", "Content-Length, X-Allowed");
  20615. res.set_chunked_content_provider(
  20616. "text/plain",
  20617. [i](size_t /*offset*/, DataSink &sink) {
  20618. switch (*i) {
  20619. case 0: sink.os << "123"; break;
  20620. case 1: sink.os << "456"; break;
  20621. case 2: sink.os << "789"; break;
  20622. case 3: {
  20623. sink.done_with_trailer(
  20624. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20625. } break;
  20626. }
  20627. (*i)++;
  20628. return true;
  20629. },
  20630. [i](bool success) {
  20631. EXPECT_TRUE(success);
  20632. delete i;
  20633. });
  20634. });
  20635. // Echo headers endpoint for header-related tests
  20636. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20637. std::string body;
  20638. for (const auto &h : req.headers) {
  20639. body.append(h.first);
  20640. body.push_back(':');
  20641. body.append(h.second);
  20642. body.push_back('\n');
  20643. }
  20644. res.set_content(body, "text/plain");
  20645. });
  20646. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20647. std::string body;
  20648. for (const auto &h : req.headers) {
  20649. body.append(h.first);
  20650. body.push_back(':');
  20651. body.append(h.second);
  20652. body.push_back('\n');
  20653. }
  20654. res.set_content(body, "text/plain");
  20655. });
  20656. port_ = svr_.bind_to_any_port("127.0.0.1");
  20657. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20658. svr_.wait_until_ready();
  20659. }
  20660. void TearDown() override {
  20661. svr_.stop();
  20662. if (thread_.joinable()) thread_.join();
  20663. }
  20664. Server svr_;
  20665. std::thread thread_;
  20666. int port_ = 0;
  20667. };
  20668. TEST_F(OpenStreamTest, Basic) {
  20669. Client cli("127.0.0.1", port_);
  20670. auto handle = cli.open_stream("GET", "/hello");
  20671. EXPECT_TRUE(handle.is_valid());
  20672. EXPECT_EQ("Hello World!", read_all(handle));
  20673. }
  20674. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20675. Client cli("127.0.0.1", port_);
  20676. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20677. ASSERT_TRUE(handle.is_valid());
  20678. EXPECT_EQ("Hello World!", read_all(handle));
  20679. }
  20680. TEST_F(OpenStreamTest, SmallBuffer) {
  20681. Client cli("127.0.0.1", port_);
  20682. auto handle = cli.open_stream("GET", "/hello");
  20683. std::string result;
  20684. char buf[4];
  20685. ssize_t n;
  20686. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20687. result.append(buf, static_cast<size_t>(n));
  20688. EXPECT_EQ("Hello World!", result);
  20689. }
  20690. TEST_F(OpenStreamTest, DefaultHeaders) {
  20691. Client cli("127.0.0.1", port_);
  20692. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20693. {
  20694. auto handle = cli.open_stream("GET", "/echo-headers");
  20695. ASSERT_TRUE(handle.is_valid());
  20696. auto body = read_all(handle);
  20697. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20698. std::string::npos);
  20699. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20700. std::string::npos);
  20701. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20702. }
  20703. // open_stream POST with body and no explicit content_type should NOT add
  20704. // text/plain Content-Type (behavior differs from non-streaming path), but
  20705. // should include Content-Length
  20706. {
  20707. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20708. ASSERT_TRUE(handle.is_valid());
  20709. auto body = read_all(handle);
  20710. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20711. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20712. }
  20713. // open_stream POST with explicit Content-Type should preserve it
  20714. {
  20715. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20716. {{"Content-Type", "application/custom"}},
  20717. "{}", "application/custom");
  20718. ASSERT_TRUE(handle.is_valid());
  20719. auto body = read_all(handle);
  20720. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20721. }
  20722. // User-specified User-Agent must not be overwritten for stream API
  20723. {
  20724. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20725. {{"User-Agent", "MyAgent/1.2"}});
  20726. ASSERT_TRUE(handle.is_valid());
  20727. auto body = read_all(handle);
  20728. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20729. }
  20730. }
  20731. TEST_F(OpenStreamTest, Large) {
  20732. Client cli("127.0.0.1", port_);
  20733. auto handle = cli.open_stream("GET", "/large");
  20734. EXPECT_EQ(10000u, read_all(handle).size());
  20735. }
  20736. TEST_F(OpenStreamTest, ConnectionError) {
  20737. Client cli("127.0.0.1", 9999);
  20738. auto handle = cli.open_stream("GET", "/hello");
  20739. EXPECT_FALSE(handle.is_valid());
  20740. }
  20741. TEST_F(OpenStreamTest, Chunked) {
  20742. Client cli("127.0.0.1", port_);
  20743. auto handle = cli.open_stream("GET", "/chunked");
  20744. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20745. "Transfer-Encoding") == "chunked");
  20746. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20747. }
  20748. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20749. Client cli("127.0.0.1", port_);
  20750. auto handle =
  20751. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20752. ASSERT_TRUE(handle.is_valid());
  20753. // Consume body to allow trailers to be received/parsed
  20754. auto body = read_all(handle);
  20755. // Explicitly parse trailers (ensure trailers are available for assertion)
  20756. handle.parse_trailers_if_needed();
  20757. EXPECT_EQ(std::string("123456789"), body);
  20758. // The response should include a Trailer header declaring both names
  20759. ASSERT_TRUE(handle.response);
  20760. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20761. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20762. handle.response->get_header_value("Trailer"));
  20763. // Prohibited trailer must not be present
  20764. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20765. // Allowed trailer should be present
  20766. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20767. EXPECT_EQ(std::string("yes"),
  20768. handle.response->get_trailer_value("X-Allowed"));
  20769. // Verify trailers are NOT present as regular headers
  20770. EXPECT_EQ(std::string(""),
  20771. handle.response->get_header_value("Content-Length"));
  20772. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20773. }
  20774. // Accepts one connection on an OS-assigned port, which it hands over through
  20775. // port_promise, reads the request head and sends back response. after_send,
  20776. // if given, runs on the connection before it is closed.
  20777. static std::thread
  20778. serve_single_response(std::promise<int> &port_promise,
  20779. const std::string &response,
  20780. std::function<void(socket_t)> after_send = nullptr) {
  20781. return std::thread([&port_promise, response, after_send] {
  20782. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20783. default_socket_options(srv);
  20784. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20785. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20786. sockaddr_in addr{};
  20787. addr.sin_family = AF_INET;
  20788. addr.sin_port = htons(0); // Let OS assign a free port
  20789. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20790. int opt = 1;
  20791. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20792. #ifdef _WIN32
  20793. reinterpret_cast<const char *>(&opt),
  20794. #else
  20795. &opt,
  20796. #endif
  20797. sizeof(opt));
  20798. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20799. ::listen(srv, 1) != 0) {
  20800. port_promise.set_value(-1);
  20801. detail::close_socket(srv);
  20802. return;
  20803. }
  20804. socklen_t addr_len = sizeof(addr);
  20805. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20806. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20807. sockaddr_in cli_addr{};
  20808. socklen_t cli_len = sizeof(cli_addr);
  20809. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20810. if (cli != INVALID_SOCKET) {
  20811. // Read the complete HTTP request (until the blank line that terminates
  20812. // headers) before sending the response. If the server closes the socket
  20813. // while the client's request data is still unread in the kernel receive
  20814. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20815. // connection on both sides: it discards the client's receive buffer
  20816. // (which already holds our response) and causes any in-progress write on
  20817. // the client to fail with ECONNRESET. Reading all request data first
  20818. // ensures close() emits a graceful FIN.
  20819. {
  20820. char rbuf[256];
  20821. std::string req;
  20822. while (req.find("\r\n\r\n") == std::string::npos) {
  20823. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20824. if (n <= 0) { break; }
  20825. req.append(rbuf, static_cast<size_t>(n));
  20826. }
  20827. }
  20828. ::send(cli,
  20829. #ifdef _WIN32
  20830. static_cast<const char *>(response.c_str()),
  20831. static_cast<int>(response.size()),
  20832. #else
  20833. response.c_str(), response.size(),
  20834. #endif
  20835. 0);
  20836. if (after_send) { after_send(cli); }
  20837. detail::close_socket(cli);
  20838. }
  20839. detail::close_socket(srv);
  20840. });
  20841. }
  20842. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20843. #ifndef _WIN32
  20844. signal(SIGPIPE, SIG_IGN);
  20845. #endif
  20846. std::promise<int> port_promise;
  20847. auto port_future = port_promise.get_future();
  20848. auto server_thread =
  20849. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20850. "Content-Type: text/plain\r\n"
  20851. "Content-Length: not-a-number\r\n"
  20852. "Connection: close\r\n"
  20853. "\r\n"
  20854. "hello");
  20855. auto port = port_future.get();
  20856. ASSERT_GT(port, 0);
  20857. Client cli("127.0.0.1", port);
  20858. auto handle = cli.open_stream("GET", "/");
  20859. EXPECT_FALSE(handle.is_valid());
  20860. server_thread.join();
  20861. }
  20862. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20863. #ifndef _WIN32
  20864. signal(SIGPIPE, SIG_IGN);
  20865. #endif
  20866. std::promise<int> port_promise;
  20867. auto port_future = port_promise.get_future();
  20868. auto server_thread = serve_single_response(
  20869. port_promise, "HTTP/1.1 200 OK\r\n"
  20870. "Content-Type: text/plain\r\n"
  20871. "Content-Length: 99999999999999999999999999\r\n"
  20872. "Connection: close\r\n"
  20873. "\r\n"
  20874. "hello");
  20875. auto port = port_future.get();
  20876. ASSERT_GT(port, 0);
  20877. // Historically std::stoull would throw std::out_of_range here and crash
  20878. // the process, then parsing silently clamped to a bogus framing length and
  20879. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20880. // so the stream fails to open, matching the not-a-number case above. The
  20881. // process still must NOT terminate.
  20882. Client cli("127.0.0.1", port);
  20883. auto handle = cli.open_stream("GET", "/");
  20884. EXPECT_FALSE(handle.is_valid());
  20885. server_thread.join();
  20886. }
  20887. #ifndef _WIN32
  20888. // As above for the body of a streamed request: a send() cut short by the write
  20889. // timeout must not leave the rest of the body unsent.
  20890. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20891. signal(SIGPIPE, SIG_IGN);
  20892. Server svr;
  20893. svr.set_socket_options([](socket_t sock) {
  20894. int size = 8192;
  20895. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20896. reinterpret_cast<const char *>(&size), sizeof(size));
  20897. });
  20898. svr.Post("/size", [](const Request &, Response &res,
  20899. const ContentReader &content_reader) {
  20900. // Outlast the client's write timeout before reading the body.
  20901. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20902. size_t received = 0;
  20903. content_reader([&](const char *, size_t len) {
  20904. received += len;
  20905. return true;
  20906. });
  20907. res.set_content(std::to_string(received), "text/plain");
  20908. });
  20909. auto port = svr.bind_to_any_port(HOST);
  20910. std::thread t([&]() { svr.listen_after_bind(); });
  20911. auto se = detail::scope_exit([&] {
  20912. svr.stop();
  20913. t.join();
  20914. });
  20915. svr.wait_until_ready();
  20916. Client cli(HOST, port);
  20917. cli.set_write_timeout(0, 500000);
  20918. cli.set_socket_options([](socket_t sock) {
  20919. int size = 8192;
  20920. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20921. reinterpret_cast<const char *>(&size), sizeof(size));
  20922. });
  20923. const std::string body(4 * 1024 * 1024, 'A');
  20924. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20925. "application/octet-stream");
  20926. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20927. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20928. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20929. }
  20930. #endif
  20931. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  20932. std::promise<void> slow_started;
  20933. auto slow_started_future = slow_started.get_future();
  20934. Server svr;
  20935. svr.Get("/slow", [&](const Request &, Response &res) {
  20936. slow_started.set_value();
  20937. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20938. res.set_content("slow", "text/plain");
  20939. });
  20940. svr.Get("/fast", [](const Request &, Response &res) {
  20941. res.set_content("fast", "text/plain");
  20942. });
  20943. auto port = svr.bind_to_any_port(HOST);
  20944. std::thread t([&]() { svr.listen_after_bind(); });
  20945. auto se = detail::scope_exit([&] {
  20946. svr.stop();
  20947. t.join();
  20948. });
  20949. svr.wait_until_ready();
  20950. Client cli(HOST, port);
  20951. std::string slow_body;
  20952. std::thread slow_thread([&] {
  20953. auto res = cli.Get("/slow");
  20954. if (res) { slow_body = res->body; }
  20955. });
  20956. slow_started_future.wait();
  20957. auto result = stream::Get(cli, "/fast");
  20958. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  20959. slow_thread.join();
  20960. EXPECT_EQ("slow", slow_body);
  20961. EXPECT_EQ("fast", fast_body);
  20962. }
  20963. // Serves `response` to the single request `fn` makes with a fresh client.
  20964. template <typename Fn>
  20965. static void with_single_response(const std::string &response, Fn fn) {
  20966. #ifndef _WIN32
  20967. signal(SIGPIPE, SIG_IGN);
  20968. #endif
  20969. std::promise<int> port_promise;
  20970. auto port_future = port_promise.get_future();
  20971. auto server_thread = serve_single_response(port_promise, response);
  20972. auto se = detail::scope_exit([&] { server_thread.join(); });
  20973. auto port = port_future.get();
  20974. ASSERT_GT(port, 0);
  20975. Client cli("127.0.0.1", port);
  20976. fn(cli);
  20977. }
  20978. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20979. // too, also in a build without the decoder for the advertised coding.
  20980. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20981. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20982. const auto response = "HTTP/1.1 200 OK\r\n"
  20983. "Content-Encoding: gzip\r\n"
  20984. "Content-Length: " +
  20985. std::to_string(gzipped.size()) +
  20986. "\r\n"
  20987. "Connection: close\r\n\r\n" +
  20988. gzipped;
  20989. with_single_response(response, [&](Client &cli) {
  20990. cli.set_decompress(false);
  20991. auto handle = cli.open_stream("GET", "/");
  20992. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20993. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20994. EXPECT_EQ(gzipped, read_all(handle));
  20995. EXPECT_FALSE(handle.has_read_error());
  20996. });
  20997. with_single_response(response, [&](Client &cli) {
  20998. cli.set_decompress(false);
  20999. auto res = stream::Get(cli, "/", 7);
  21000. ASSERT_TRUE(res) << to_string(res.error());
  21001. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21002. EXPECT_EQ(gzipped, res.read_all());
  21003. EXPECT_FALSE(res.has_read_error());
  21004. });
  21005. }
  21006. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21007. // Neither Content-Length nor chunked: the body ends at the close
  21008. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21009. "Connection: close\r\n"
  21010. "\r\n"
  21011. "hello";
  21012. with_single_response(close_delimited, [](Client &cli) {
  21013. auto handle = cli.open_stream("GET", "/");
  21014. ASSERT_TRUE(handle.is_valid());
  21015. EXPECT_EQ("hello", read_all(handle));
  21016. EXPECT_FALSE(handle.has_read_error());
  21017. });
  21018. // A close before the end of the Content-Length is still an error
  21019. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21020. "Content-Length: 10\r\n"
  21021. "\r\n"
  21022. "hello";
  21023. with_single_response(short_content_length, [](Client &cli) {
  21024. auto handle = cli.open_stream("GET", "/");
  21025. ASSERT_TRUE(handle.is_valid());
  21026. read_all(handle);
  21027. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21028. });
  21029. // So is a close before the last chunk
  21030. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21031. "Transfer-Encoding: chunked\r\n"
  21032. "\r\n"
  21033. "5\r\nhello\r\n";
  21034. with_single_response(short_chunked, [](Client &cli) {
  21035. auto handle = cli.open_stream("GET", "/");
  21036. ASSERT_TRUE(handle.is_valid());
  21037. read_all(handle);
  21038. EXPECT_TRUE(handle.has_read_error());
  21039. });
  21040. }
  21041. #ifdef CPPHTTPLIB_SSL_ENABLED
  21042. // Serves `response` to one request, then closes with or without a close_notify
  21043. template <typename Fn>
  21044. static void with_single_tls_response(const std::string &response,
  21045. bool close_notify, Fn fn) {
  21046. #ifndef _WIN32
  21047. signal(SIGPIPE, SIG_IGN);
  21048. #endif
  21049. std::promise<int> port_promise;
  21050. auto port_future = port_promise.get_future();
  21051. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21052. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21053. default_socket_options(srv);
  21054. sockaddr_in addr{};
  21055. addr.sin_family = AF_INET;
  21056. addr.sin_port = htons(0);
  21057. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21058. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21059. ::listen(srv, 1) != 0) {
  21060. port_promise.set_value(-1);
  21061. detail::close_socket(srv);
  21062. return;
  21063. }
  21064. socklen_t addr_len = sizeof(addr);
  21065. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21066. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21067. auto cli = ::accept(srv, nullptr, nullptr);
  21068. if (cli != INVALID_SOCKET) {
  21069. auto ctx = tls::create_server_context();
  21070. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21071. nullptr);
  21072. auto session = tls::create_session(ctx, cli);
  21073. tls::TlsError err;
  21074. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  21075. // The request head first, so that closing the socket sends a FIN
  21076. // rather than an RST for the unread bytes.
  21077. std::string req;
  21078. char buf[256];
  21079. while (req.find("\r\n\r\n") == std::string::npos) {
  21080. auto n = tls::read(session, buf, sizeof(buf), err);
  21081. if (n <= 0) { break; }
  21082. req.append(buf, static_cast<size_t>(n));
  21083. }
  21084. size_t sent = 0;
  21085. while (sent < response.size()) {
  21086. auto n = tls::write(session, response.data() + sent,
  21087. response.size() - sent, err);
  21088. if (n <= 0) { break; }
  21089. sent += static_cast<size_t>(n);
  21090. }
  21091. if (close_notify) { tls::shutdown(session, true); }
  21092. }
  21093. tls::free_session(session);
  21094. detail::close_socket(cli);
  21095. tls::free_context(ctx);
  21096. }
  21097. detail::close_socket(srv);
  21098. });
  21099. auto se = detail::scope_exit([&] { server_thread.join(); });
  21100. auto port = port_future.get();
  21101. ASSERT_GT(port, 0);
  21102. SSLClient cli("127.0.0.1", port);
  21103. cli.enable_server_certificate_verification(false);
  21104. fn(cli);
  21105. }
  21106. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21107. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21108. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21109. "Connection: close\r\n"
  21110. "\r\n"
  21111. "hello";
  21112. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21113. auto res = cli.Get("/");
  21114. ASSERT_TRUE(res) << to_string(res.error());
  21115. EXPECT_EQ("hello", res->body);
  21116. });
  21117. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21118. auto res = cli.Get("/");
  21119. ASSERT_FALSE(res);
  21120. EXPECT_EQ(Error::Read, res.error());
  21121. });
  21122. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21123. auto handle = cli.open_stream("GET", "/");
  21124. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21125. read_all(handle);
  21126. EXPECT_TRUE(handle.has_read_error());
  21127. });
  21128. // A framed body ends where its framing says, with or without the alert
  21129. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21130. "Content-Length: 5\r\n"
  21131. "Connection: close\r\n"
  21132. "\r\n"
  21133. "hello";
  21134. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21135. auto res = cli.Get("/");
  21136. ASSERT_TRUE(res) << to_string(res.error());
  21137. EXPECT_EQ("hello", res->body);
  21138. });
  21139. }
  21140. #endif
  21141. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21142. const char *responses[] = {
  21143. "HTTP/1.1 103 Early Hints\r\n"
  21144. "Link: </style.css>; rel=preload\r\n"
  21145. "\r\n"
  21146. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21147. "HTTP/1.1 100 Continue\r\n"
  21148. "X-Note: interim\r\n"
  21149. "\r\n"
  21150. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21151. };
  21152. for (auto response : responses) {
  21153. with_single_response(response, [](Client &cli) {
  21154. auto res = cli.Get("/");
  21155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21156. EXPECT_EQ(StatusCode::OK_200, res->status);
  21157. EXPECT_EQ("ok", res->body);
  21158. });
  21159. }
  21160. }
  21161. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21162. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21163. const std::string final_response =
  21164. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21165. std::string interims;
  21166. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21167. interims += interim;
  21168. }
  21169. with_single_response(interims + final_response, [](Client &cli) {
  21170. auto res = cli.Get("/");
  21171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21172. EXPECT_EQ("ok", res->body);
  21173. });
  21174. with_single_response(interims + interim + final_response, [](Client &cli) {
  21175. auto res = cli.Get("/");
  21176. ASSERT_FALSE(res);
  21177. EXPECT_EQ(Error::Read, res.error());
  21178. });
  21179. }
  21180. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21181. #ifndef _WIN32
  21182. signal(SIGPIPE, SIG_IGN);
  21183. #endif
  21184. // The server answers the head without asking for the body. Bytes it then
  21185. // reads on the connection would be taken for the body the request declared.
  21186. auto closed_by_client = false;
  21187. std::promise<int> port_promise;
  21188. auto server_thread = serve_single_response(
  21189. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21190. [&](socket_t sock) {
  21191. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21192. char buf[256];
  21193. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21194. });
  21195. Client cli("127.0.0.1", port_promise.get_future().get());
  21196. cli.set_keep_alive(true);
  21197. cli.set_read_timeout(1, 0);
  21198. // Long enough for the client to send Expect: 100-continue.
  21199. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21201. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21202. cli.Get("/second");
  21203. server_thread.join();
  21204. EXPECT_TRUE(closed_by_client);
  21205. }
  21206. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21207. // Long enough for the client to send Expect: 100-continue
  21208. with_single_response(
  21209. "HTTP/1.1 103 Early Hints\r\n"
  21210. "Link: </style.css>; rel=preload\r\n"
  21211. "\r\n"
  21212. "HTTP/1.1 401 Unauthorized\r\n"
  21213. "Content-Length: 0\r\n\r\n",
  21214. [](Client &cli) {
  21215. cli.set_read_timeout(2, 0);
  21216. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21218. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21219. });
  21220. }
  21221. #ifdef CPPHTTPLIB_SSL_ENABLED
  21222. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21223. #ifndef _WIN32
  21224. signal(SIGPIPE, SIG_IGN);
  21225. #endif
  21226. auto reused = false;
  21227. std::promise<int> port_promise;
  21228. auto server_thread = serve_single_response(
  21229. port_promise,
  21230. "HTTP/1.1 401 Unauthorized\r\n"
  21231. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21232. "Content-Length: 0\r\n\r\n",
  21233. [&](socket_t sock) {
  21234. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21235. char buf[256];
  21236. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21237. });
  21238. Client cli("127.0.0.1", port_promise.get_future().get());
  21239. cli.set_keep_alive(true);
  21240. cli.set_digest_auth("user", "pass");
  21241. cli.set_read_timeout(1, 0);
  21242. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21243. server_thread.join();
  21244. EXPECT_FALSE(reused);
  21245. }
  21246. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21247. // Any other answer to CONNECT would read as the origin's response.
  21248. struct {
  21249. const char *response;
  21250. bool passed_on;
  21251. } cases[] = {
  21252. {"HTTP/1.1 201 Created\r\n"
  21253. "Set-Cookie: session=from-proxy\r\n"
  21254. "Content-Length: 0\r\n\r\n",
  21255. false},
  21256. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21257. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21258. "Content-Length: 0\r\n\r\n",
  21259. true},
  21260. };
  21261. for (const auto &c : cases) {
  21262. std::promise<int> port_promise;
  21263. auto server_thread = serve_single_response(port_promise, c.response);
  21264. SSLClient cli("example.com", 443);
  21265. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21266. auto res = cli.Get("/");
  21267. server_thread.join();
  21268. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21269. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21270. if (res) {
  21271. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21272. }
  21273. }
  21274. }
  21275. #endif
  21276. // Records the client's error logger calls as "error METHOD path", or
  21277. // "error null" for a call without a request
  21278. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21279. return [&log](const Error &err, const Request *req) {
  21280. log.push_back(to_string(err) + " " +
  21281. (req ? req->method + " " + req->path : "null"));
  21282. };
  21283. }
  21284. // A failed request is reported once, with the request the caller made
  21285. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21286. Server svr;
  21287. svr.Get("/big", [](const Request &, Response &res) {
  21288. res.set_content(std::string(100000, 'b'), "text/plain");
  21289. });
  21290. auto port = svr.bind_to_any_port(HOST);
  21291. std::thread t([&]() { svr.listen_after_bind(); });
  21292. auto se = detail::scope_exit([&] {
  21293. svr.stop();
  21294. t.join();
  21295. });
  21296. svr.wait_until_ready();
  21297. Client cli(HOST, port);
  21298. std::vector<std::string> log;
  21299. cli.set_error_logger(record_errors(log));
  21300. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21301. cli.Get("/big", [](const char *, size_t) { return false; });
  21302. EXPECT_EQ(expected, log);
  21303. log.clear();
  21304. cli.Get("/big", [](size_t, size_t) { return false; });
  21305. EXPECT_EQ(expected, log);
  21306. }
  21307. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21308. // Fails while the body is read
  21309. auto broken = [](const Request &, Response &res) {
  21310. res.set_content_provider(10, "text/plain",
  21311. [](size_t, size_t, DataSink &) { return false; });
  21312. };
  21313. Server other;
  21314. other.Get("/broken", broken);
  21315. auto other_port = other.bind_to_any_port(HOST);
  21316. std::thread other_t([&]() { other.listen_after_bind(); });
  21317. auto other_se = detail::scope_exit([&] {
  21318. other.stop();
  21319. other_t.join();
  21320. });
  21321. other.wait_until_ready();
  21322. Server svr;
  21323. svr.Get("/broken", broken);
  21324. svr.Get("/same-origin",
  21325. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21326. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21327. res.set_redirect("http://" + std::string(HOST) + ":" +
  21328. std::to_string(other_port) + "/broken");
  21329. });
  21330. auto port = svr.bind_to_any_port(HOST);
  21331. std::thread t([&]() { svr.listen_after_bind(); });
  21332. auto se = detail::scope_exit([&] {
  21333. svr.stop();
  21334. t.join();
  21335. });
  21336. svr.wait_until_ready();
  21337. Client cli(HOST, port);
  21338. cli.set_follow_location(true);
  21339. std::vector<std::string> log;
  21340. cli.set_error_logger(record_errors(log));
  21341. for (auto path : {"/same-origin", "/cross-origin"}) {
  21342. log.clear();
  21343. auto res = cli.Get(path);
  21344. ASSERT_FALSE(res);
  21345. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21346. log);
  21347. }
  21348. }
  21349. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21350. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21351. std::vector<std::string> log;
  21352. cli.set_error_logger(record_errors(log));
  21353. auto handle = cli.open_stream("GET", "/x");
  21354. EXPECT_FALSE(handle.is_valid());
  21355. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21356. log);
  21357. });
  21358. }
  21359. #ifdef CPPHTTPLIB_SSL_ENABLED
  21360. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21361. // Not a TLS server, so the handshake fails. It waits for a request line in
  21362. // the handshake bytes, so a short read timeout lets it close quickly.
  21363. Server svr;
  21364. svr.set_read_timeout(0, 100000);
  21365. svr.Get("/x", [](const Request &, Response &res) {
  21366. res.set_content("x", "text/plain");
  21367. });
  21368. auto port = svr.bind_to_any_port(HOST);
  21369. std::thread t([&]() { svr.listen_after_bind(); });
  21370. auto se = detail::scope_exit([&] {
  21371. svr.stop();
  21372. t.join();
  21373. });
  21374. svr.wait_until_ready();
  21375. std::vector<std::string> log;
  21376. SSLClient cli(HOST, port);
  21377. cli.enable_server_certificate_verification(false);
  21378. cli.set_error_logger(record_errors(log));
  21379. auto res = cli.Get("/x");
  21380. ASSERT_FALSE(res);
  21381. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21382. log.clear();
  21383. auto handle = cli.open_stream("GET", "/x");
  21384. EXPECT_FALSE(handle.is_valid());
  21385. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21386. log.clear();
  21387. SSLClient no_ca(HOST, port);
  21388. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21389. no_ca.set_error_logger(record_errors(log));
  21390. res = no_ca.Get("/x");
  21391. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21392. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21393. }
  21394. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21395. #ifndef _WIN32
  21396. signal(SIGPIPE, SIG_IGN);
  21397. #endif
  21398. // Refused, answered with a challenge, or closed without an answer
  21399. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21400. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21401. "Content-Length: 0\r\n\r\n",
  21402. ""}) {
  21403. std::promise<int> port_promise;
  21404. auto server_thread = serve_single_response(port_promise, response);
  21405. SSLClient cli("example.com", 443);
  21406. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21407. std::vector<std::string> log;
  21408. cli.set_error_logger(record_errors(log));
  21409. auto res = cli.Get("/");
  21410. server_thread.join();
  21411. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21412. << response;
  21413. }
  21414. }
  21415. #endif
  21416. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21417. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21418. // the chunked coding and drop Content-Length, so a front-end that trusts
  21419. // Content-Length would disagree about where the body ends (response
  21420. // smuggling). The client must reject such a response.
  21421. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21422. for (const char *te : {"chunked", "gzip, chunked"}) {
  21423. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21424. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21425. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21426. "5\r\nhello\r\n0\r\n\r\n";
  21427. with_single_response(response, [&](Client &cli) {
  21428. auto res = cli.Get("/");
  21429. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21430. EXPECT_EQ(Error::Read, res.error()) << te;
  21431. });
  21432. with_single_response(response, [&](Client &cli) {
  21433. auto handle = cli.open_stream("GET", "/");
  21434. EXPECT_FALSE(handle.is_valid()) << te;
  21435. EXPECT_EQ(Error::Read, handle.error) << te;
  21436. });
  21437. }
  21438. }
  21439. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21440. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21441. // closing the connection (unlike a request, which must be rejected).
  21442. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21443. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21444. "Transfer-Encoding: chunked\r\n"
  21445. "Connection: close\r\n"
  21446. "\r\n"
  21447. "5\r\nhello\r\n0\r\n\r\n",
  21448. "HTTP/1.1 200 OK\r\n"
  21449. "Transfer-Encoding: gzip\r\n"
  21450. "Connection: close\r\n"
  21451. "\r\n"
  21452. "hello"}) {
  21453. with_single_response(response, [&](Client &cli) {
  21454. auto res = cli.Get("/");
  21455. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21456. EXPECT_EQ("hello", res->body);
  21457. });
  21458. with_single_response(response, [&](Client &cli) {
  21459. auto handle = cli.open_stream("GET", "/");
  21460. ASSERT_TRUE(handle.is_valid()) << response;
  21461. EXPECT_EQ("hello", read_all(handle));
  21462. });
  21463. }
  21464. }
  21465. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21466. // framing headers describe nothing to read and must not be rejected.
  21467. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21468. const std::string framing = "Content-Length: 5\r\n"
  21469. "Transfer-Encoding: chunked\r\n"
  21470. "Connection: close\r\n"
  21471. "\r\n";
  21472. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21473. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21474. });
  21475. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21476. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21477. });
  21478. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21479. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21480. with_single_response(response, [&](Client &cli) {
  21481. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21482. });
  21483. with_single_response(response, [&](Client &cli) {
  21484. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21485. });
  21486. }
  21487. }
  21488. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21489. // header section, so a stream opened on one has nothing to read, whatever
  21490. // framing or coding headers it carries.
  21491. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21492. struct Case {
  21493. const char *method;
  21494. const char *status;
  21495. };
  21496. // A reader of the declared body reports an early close when nothing
  21497. // follows, and hands back what does.
  21498. struct Framing {
  21499. const char *headers;
  21500. const char *after;
  21501. };
  21502. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21503. Case{"GET", "304 Not Modified"}}) {
  21504. for (const auto &f :
  21505. {Framing{"Content-Length: 5\r\n", ""},
  21506. Framing{"Content-Length: 5\r\n", "hello"},
  21507. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21508. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21509. // Not decoded, so a build without Brotli opens it too
  21510. Framing{"Content-Encoding: br\r\n", ""}}) {
  21511. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21512. "Connection: close\r\n"
  21513. "\r\n" +
  21514. f.after;
  21515. with_single_response(response, [&](Client &cli) {
  21516. auto handle = cli.open_stream(c.method, "/");
  21517. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21518. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21519. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21520. });
  21521. }
  21522. }
  21523. }
  21524. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21525. // response, is faulty framing, so the connection is not reused after it.
  21526. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21527. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21528. "Content-Length: 0\r\n"
  21529. "Transfer-Encoding: chunked\r\n"
  21530. "\r\n"
  21531. "5\r\nhello\r\n0\r\n\r\n",
  21532. "HTTP/1.0 200 Connection established\r\n"
  21533. "Connection: keep-alive\r\n"
  21534. "Transfer-Encoding: chunked\r\n"
  21535. "\r\n"
  21536. "5\r\nhello\r\n0\r\n\r\n"}) {
  21537. with_single_response(response, [&](Client &cli) {
  21538. cli.set_keep_alive(true);
  21539. auto res = cli.Get("/");
  21540. ASSERT_TRUE(res) << response;
  21541. EXPECT_EQ("hello", res->body);
  21542. EXPECT_FALSE(cli.is_socket_open()) << response;
  21543. });
  21544. }
  21545. }
  21546. // A payload max length of 0 means no limit, however the body is framed.
  21547. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21548. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21549. "Transfer-Encoding: chunked\r\n"
  21550. "\r\n"
  21551. "5\r\nhello\r\n0\r\n\r\n",
  21552. "HTTP/1.1 200 OK\r\n"
  21553. "Connection: close\r\n"
  21554. "\r\n"
  21555. "hello"}) {
  21556. with_single_response(response, [&](Client &cli) {
  21557. cli.set_payload_max_length(0);
  21558. auto res = cli.Get("/");
  21559. ASSERT_TRUE(res) << response;
  21560. EXPECT_EQ("hello", res->body) << response;
  21561. });
  21562. }
  21563. }
  21564. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21565. Server svr;
  21566. svr.set_payload_max_length(0);
  21567. svr.Post("/echo", [](const Request &req, Response &res) {
  21568. res.set_content(req.body, "text/plain");
  21569. });
  21570. auto port = svr.bind_to_any_port(HOST);
  21571. thread t = thread([&] { svr.listen_after_bind(); });
  21572. auto se = detail::scope_exit([&] {
  21573. svr.stop();
  21574. t.join();
  21575. ASSERT_FALSE(svr.is_running());
  21576. });
  21577. svr.wait_until_ready();
  21578. Client cli(HOST, port);
  21579. auto res = cli.Post(
  21580. "/echo",
  21581. [](size_t /*offset*/, DataSink &sink) {
  21582. sink.write("hello", 5);
  21583. sink.done();
  21584. return true;
  21585. },
  21586. "text/plain");
  21587. ASSERT_TRUE(res);
  21588. EXPECT_EQ(StatusCode::OK_200, res->status);
  21589. EXPECT_EQ("hello", res->body);
  21590. }
  21591. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21592. TEST_F(OpenStreamTest, Gzip) {
  21593. Client cli("127.0.0.1", port_);
  21594. auto handle = cli.open_stream("GET", "/compressible", {},
  21595. {{"Accept-Encoding", "gzip"}});
  21596. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21597. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21598. }
  21599. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21600. Client cli("127.0.0.1", port_);
  21601. auto handle =
  21602. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21603. {{"Accept-Encoding", "gzip"}});
  21604. ASSERT_TRUE(handle.is_valid());
  21605. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21606. EXPECT_EQ("123456789", read_all(handle));
  21607. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21608. }
  21609. #endif
  21610. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21611. TEST_F(OpenStreamTest, Brotli) {
  21612. Client cli("127.0.0.1", port_);
  21613. auto handle =
  21614. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21615. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21616. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21617. }
  21618. #endif
  21619. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21620. TEST_F(OpenStreamTest, Zstd) {
  21621. Client cli("127.0.0.1", port_);
  21622. auto handle = cli.open_stream("GET", "/compressible", {},
  21623. {{"Accept-Encoding", "zstd"}});
  21624. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21625. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21626. }
  21627. #endif
  21628. #ifdef CPPHTTPLIB_SSL_ENABLED
  21629. class SSLOpenStreamTest : public ::testing::Test {
  21630. protected:
  21631. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21632. void SetUp() override {
  21633. svr_.Get("/hello", [](const Request &, Response &res) {
  21634. res.set_content("Hello SSL World!", "text/plain");
  21635. });
  21636. svr_.Get("/chunked", [](const Request &, Response &res) {
  21637. res.set_chunked_content_provider("text/plain",
  21638. [](size_t offset, DataSink &sink) {
  21639. if (offset < 15) {
  21640. sink.write("chunk", 5);
  21641. return true;
  21642. }
  21643. sink.done();
  21644. return true;
  21645. });
  21646. });
  21647. svr_.Post("/echo", [](const Request &req, Response &res) {
  21648. res.set_content(req.body, req.get_header_value("Content-Type"));
  21649. });
  21650. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21651. std::string body = req.body;
  21652. res.set_chunked_content_provider(
  21653. "text/plain", [body](size_t offset, DataSink &sink) {
  21654. if (offset < body.size()) {
  21655. sink.write(body.data() + offset, body.size() - offset);
  21656. }
  21657. sink.done();
  21658. return true;
  21659. });
  21660. });
  21661. port_ = svr_.bind_to_any_port("127.0.0.1");
  21662. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21663. svr_.wait_until_ready();
  21664. }
  21665. void TearDown() override {
  21666. svr_.stop();
  21667. if (thread_.joinable()) thread_.join();
  21668. }
  21669. SSLServer svr_;
  21670. std::thread thread_;
  21671. int port_ = 0;
  21672. };
  21673. TEST_F(SSLOpenStreamTest, Basic) {
  21674. SSLClient cli("127.0.0.1", port_);
  21675. cli.enable_server_certificate_verification(false);
  21676. auto handle = cli.open_stream("GET", "/hello");
  21677. ASSERT_TRUE(handle.is_valid());
  21678. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21679. }
  21680. TEST_F(SSLOpenStreamTest, Chunked) {
  21681. SSLClient cli("127.0.0.1", port_);
  21682. cli.enable_server_certificate_verification(false);
  21683. auto handle = cli.open_stream("GET", "/chunked");
  21684. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21685. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21686. "Transfer-Encoding") == "chunked");
  21687. auto body = read_all(handle);
  21688. EXPECT_EQ("chunkchunkchunk", body);
  21689. }
  21690. TEST_F(SSLOpenStreamTest, Post) {
  21691. SSLClient cli("127.0.0.1", port_);
  21692. cli.enable_server_certificate_verification(false);
  21693. auto handle =
  21694. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21695. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21696. EXPECT_EQ(200, handle.response->status);
  21697. auto body = read_all(handle);
  21698. EXPECT_EQ("Hello SSL POST", body);
  21699. }
  21700. TEST_F(SSLOpenStreamTest, PostChunked) {
  21701. SSLClient cli("127.0.0.1", port_);
  21702. cli.enable_server_certificate_verification(false);
  21703. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21704. "Chunked SSL Data", "text/plain");
  21705. ASSERT_TRUE(handle.is_valid());
  21706. EXPECT_EQ(200, handle.response->status);
  21707. auto body = read_all(handle);
  21708. EXPECT_EQ("Chunked SSL Data", body);
  21709. }
  21710. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21711. // Content-Length is terminated by the server closing the connection. When the
  21712. // SSL peer sends a close_notify after the body, the client must treat it as a
  21713. // clean EOF and return a successful response rather than an error.
  21714. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21716. ASSERT_TRUE(svr.is_valid());
  21717. svr.set_keep_alive_max_count(1);
  21718. const std::string expected_body = "Hello from connection-close response!";
  21719. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21720. res.set_content_provider("text/plain",
  21721. [&](size_t offset, DataSink &sink) -> bool {
  21722. if (offset < expected_body.size()) {
  21723. sink.write(expected_body.data() + offset,
  21724. expected_body.size() - offset);
  21725. }
  21726. sink.done();
  21727. return true;
  21728. });
  21729. });
  21730. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21731. auto se = detail::scope_exit([&] {
  21732. svr.stop();
  21733. listen_thread.join();
  21734. ASSERT_FALSE(svr.is_running());
  21735. });
  21736. svr.wait_until_ready();
  21737. SSLClient cli(HOST, PORT);
  21738. cli.enable_server_certificate_verification(false);
  21739. auto res = cli.Get("/no-content-length");
  21740. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21741. EXPECT_EQ(StatusCode::OK_200, res->status);
  21742. EXPECT_EQ(expected_body, res->body);
  21743. }
  21744. // Without Content-Length, the full buffer size reaches tls::read().
  21745. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21746. if (sizeof(size_t) <= sizeof(int)) {
  21747. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21748. }
  21749. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21750. ASSERT_TRUE(svr.is_valid());
  21751. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21752. res.set_content_provider("text/plain",
  21753. [&](size_t offset, DataSink &sink) -> bool {
  21754. if (offset == 0) { sink.write("Hello", 5); }
  21755. sink.done();
  21756. return true;
  21757. });
  21758. });
  21759. auto port = svr.bind_to_any_port(HOST);
  21760. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21761. auto se = detail::scope_exit([&] {
  21762. svr.stop();
  21763. listen_thread.join();
  21764. });
  21765. svr.wait_until_ready();
  21766. SSLClient cli(HOST, port);
  21767. cli.enable_server_certificate_verification(false);
  21768. auto handle = cli.open_stream("GET", "/no-content-length");
  21769. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21770. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21771. std::unique_ptr<char[]> buf(new char[len]);
  21772. std::string body;
  21773. ssize_t n;
  21774. while ((n = handle.read(buf.get(), len)) > 0) {
  21775. body.append(buf.get(), static_cast<size_t>(n));
  21776. }
  21777. EXPECT_EQ(0, n);
  21778. EXPECT_EQ("Hello", body);
  21779. }
  21780. #endif // CPPHTTPLIB_SSL_ENABLED
  21781. //==============================================================================
  21782. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21783. // results for various scenarios.
  21784. //==============================================================================
  21785. TEST(ParityTest, GetVsOpenStream) {
  21786. Server svr;
  21787. const std::string path = "/parity";
  21788. const std::string content = "Parity test content: hello world";
  21789. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21790. res.set_content(content, "text/plain");
  21791. });
  21792. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21793. auto se = detail::scope_exit([&] {
  21794. svr.stop();
  21795. t.join();
  21796. ASSERT_FALSE(svr.is_running());
  21797. });
  21798. svr.wait_until_ready();
  21799. Client cli(HOST, PORT);
  21800. // Non-stream path
  21801. auto r1 = cli.Get(path);
  21802. ASSERT_TRUE(r1);
  21803. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21804. // Stream path
  21805. auto h = cli.open_stream("GET", path);
  21806. ASSERT_TRUE(h.is_valid());
  21807. EXPECT_EQ(r1->body, read_all(h));
  21808. }
  21809. // Helper to compress data with provided compressor type T
  21810. template <typename Compressor>
  21811. static std::string compress_payload_for_parity(const std::string &in) {
  21812. std::string out;
  21813. Compressor compressor;
  21814. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21815. [&](const char *data, size_t n) {
  21816. out.append(data, n);
  21817. return true;
  21818. });
  21819. EXPECT_TRUE(ok);
  21820. return out;
  21821. }
  21822. // Helper function for compression parity tests
  21823. template <typename Compressor>
  21824. static void test_compression_parity(const std::string &original,
  21825. const std::string &path,
  21826. const std::string &encoding) {
  21827. const std::string compressed =
  21828. compress_payload_for_parity<Compressor>(original);
  21829. Server svr;
  21830. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21831. res.set_content(compressed, "application/octet-stream");
  21832. res.set_header("Content-Encoding", encoding);
  21833. });
  21834. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21835. auto se = detail::scope_exit([&] {
  21836. svr.stop();
  21837. t.join();
  21838. ASSERT_FALSE(svr.is_running());
  21839. });
  21840. svr.wait_until_ready();
  21841. Client cli(HOST, PORT);
  21842. // Non-streaming
  21843. {
  21844. auto res = cli.Get(path);
  21845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21846. EXPECT_EQ(StatusCode::OK_200, res->status);
  21847. EXPECT_EQ(original, res->body);
  21848. }
  21849. // Streaming
  21850. {
  21851. auto h = cli.open_stream("GET", path);
  21852. ASSERT_TRUE(h.is_valid());
  21853. EXPECT_EQ(original, read_all(h));
  21854. }
  21855. }
  21856. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21857. TEST(ParityTest, Gzip) {
  21858. test_compression_parity<detail::gzip_compressor>(
  21859. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  21860. }
  21861. #endif
  21862. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21863. TEST(ParityTest, Brotli) {
  21864. test_compression_parity<detail::brotli_compressor>(
  21865. "Hello, brotli parity test payload", "/parity-br", "br");
  21866. }
  21867. #endif
  21868. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21869. TEST(ParityTest, Zstd) {
  21870. test_compression_parity<detail::zstd_compressor>(
  21871. "Zstandard parity test payload", "/parity-zstd", "zstd");
  21872. }
  21873. #endif
  21874. //==============================================================================
  21875. // New Stream API Tests
  21876. //==============================================================================
  21877. inline std::string read_body(httplib::stream::Result &result) {
  21878. std::string body;
  21879. while (result.next()) {
  21880. body.append(result.data(), result.size());
  21881. }
  21882. return body;
  21883. }
  21884. TEST(ClientConnectionTest, Basic) {
  21885. httplib::ClientConnection conn;
  21886. EXPECT_FALSE(conn.is_open());
  21887. conn.sock = 1;
  21888. EXPECT_TRUE(conn.is_open());
  21889. httplib::ClientConnection conn2(std::move(conn));
  21890. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  21891. conn2.sock = INVALID_SOCKET;
  21892. }
  21893. // Unified test server for all stream::* tests
  21894. class StreamApiTest : public ::testing::Test {
  21895. protected:
  21896. void SetUp() override {
  21897. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21898. res.set_content("Hello World!", "text/plain");
  21899. });
  21900. svr_.Get("/echo-params",
  21901. [](const httplib::Request &req, httplib::Response &res) {
  21902. std::string r;
  21903. for (const auto &p : req.params) {
  21904. if (!r.empty()) r += "&";
  21905. r += p.first + "=" + p.second;
  21906. }
  21907. res.set_content(r, "text/plain");
  21908. });
  21909. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21910. res.set_content(req.body, req.get_header_value("Content-Type"));
  21911. });
  21912. svr_.Post("/echo-headers",
  21913. [](const httplib::Request &req, httplib::Response &res) {
  21914. std::string r;
  21915. for (const auto &h : req.headers)
  21916. r += h.first + ": " + h.second + "\n";
  21917. res.set_content(r, "text/plain");
  21918. });
  21919. svr_.Post("/echo-params",
  21920. [](const httplib::Request &req, httplib::Response &res) {
  21921. std::string r = "params:";
  21922. for (const auto &p : req.params)
  21923. r += p.first + "=" + p.second + ";";
  21924. res.set_content(r + " body:" + req.body, "text/plain");
  21925. });
  21926. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  21927. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  21928. });
  21929. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21930. res.set_content("PUT:" + req.body, "text/plain");
  21931. });
  21932. svr_.Patch("/echo",
  21933. [](const httplib::Request &req, httplib::Response &res) {
  21934. res.set_content("PATCH:" + req.body, "text/plain");
  21935. });
  21936. svr_.Delete(
  21937. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21938. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21939. "text/plain");
  21940. });
  21941. svr_.Get("/head-test",
  21942. [](const httplib::Request &, httplib::Response &res) {
  21943. res.set_content("body for HEAD", "text/plain");
  21944. });
  21945. svr_.Options("/options",
  21946. [](const httplib::Request &, httplib::Response &res) {
  21947. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21948. });
  21949. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21950. svr_.wait_until_ready();
  21951. }
  21952. void TearDown() override {
  21953. svr_.stop();
  21954. if (thread_.joinable()) thread_.join();
  21955. }
  21956. httplib::Server svr_;
  21957. std::thread thread_;
  21958. };
  21959. // stream::Get tests
  21960. TEST_F(StreamApiTest, GetBasic) {
  21961. httplib::Client cli(HOST, PORT);
  21962. auto result = httplib::stream::Get(cli, "/hello");
  21963. ASSERT_TRUE(result.is_valid());
  21964. EXPECT_EQ(200, result.status());
  21965. EXPECT_EQ("Hello World!", read_body(result));
  21966. }
  21967. TEST_F(StreamApiTest, GetWithParams) {
  21968. httplib::Client cli(HOST, PORT);
  21969. httplib::Params params{{"foo", "bar"}};
  21970. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21971. ASSERT_TRUE(result.is_valid());
  21972. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21973. }
  21974. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21975. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21976. httplib::Client cli(HOST, PORT);
  21977. cli.set_payload_max_length(0);
  21978. auto result = httplib::stream::Get(cli, "/hello");
  21979. ASSERT_TRUE(result.is_valid());
  21980. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21981. EXPECT_EQ("Hello World!", read_body(result));
  21982. }
  21983. #endif
  21984. TEST_F(StreamApiTest, GetConnectionError) {
  21985. httplib::Client cli(HOST, 9999);
  21986. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21987. }
  21988. TEST_F(StreamApiTest, Get404) {
  21989. httplib::Client cli(HOST, PORT);
  21990. auto result = httplib::stream::Get(cli, "/nonexistent");
  21991. EXPECT_TRUE(result.is_valid());
  21992. EXPECT_EQ(404, result.status());
  21993. }
  21994. // stream::Post tests
  21995. TEST_F(StreamApiTest, PostBasic) {
  21996. httplib::Client cli(HOST, PORT);
  21997. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21998. "application/json");
  21999. ASSERT_TRUE(result.is_valid());
  22000. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22001. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22002. }
  22003. TEST_F(StreamApiTest, PostWithHeaders) {
  22004. httplib::Client cli(HOST, PORT);
  22005. httplib::Headers headers{{"X-Custom", "value"}};
  22006. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22007. "text/plain");
  22008. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22009. }
  22010. TEST_F(StreamApiTest, PostWithParams) {
  22011. httplib::Client cli(HOST, PORT);
  22012. httplib::Params params{{"k", "v"}};
  22013. auto result =
  22014. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22015. auto body = read_body(result);
  22016. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22017. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22018. }
  22019. TEST_F(StreamApiTest, PostLarge) {
  22020. httplib::Client cli(HOST, PORT);
  22021. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22022. size_t total = 0;
  22023. while (result.next()) {
  22024. total += result.size();
  22025. }
  22026. EXPECT_EQ(100u * 1024u, total);
  22027. }
  22028. // stream::Put/Patch tests
  22029. TEST_F(StreamApiTest, PutAndPatch) {
  22030. httplib::Client cli(HOST, PORT);
  22031. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22032. EXPECT_EQ("PUT:test", read_body(put));
  22033. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22034. EXPECT_EQ("PATCH:test", read_body(patch));
  22035. }
  22036. // stream::Delete tests
  22037. TEST_F(StreamApiTest, Delete) {
  22038. httplib::Client cli(HOST, PORT);
  22039. auto del1 = httplib::stream::Delete(cli, "/resource");
  22040. EXPECT_EQ("Deleted", read_body(del1));
  22041. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22042. EXPECT_EQ("Deleted:data", read_body(del2));
  22043. }
  22044. // stream::Head/Options tests
  22045. TEST_F(StreamApiTest, HeadAndOptions) {
  22046. httplib::Client cli(HOST, PORT);
  22047. auto head = httplib::stream::Head(cli, "/head-test");
  22048. EXPECT_TRUE(head.is_valid());
  22049. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22050. auto opts = httplib::stream::Options(cli, "/options");
  22051. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22052. }
  22053. // SSL stream::* tests
  22054. #ifdef CPPHTTPLIB_SSL_ENABLED
  22055. class SSLStreamApiTest : public ::testing::Test {
  22056. protected:
  22057. void SetUp() override {
  22058. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22059. res.set_content("Hello SSL!", "text/plain");
  22060. });
  22061. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22062. res.set_content(req.body, "text/plain");
  22063. });
  22064. port_ = svr_.bind_to_any_port("127.0.0.1");
  22065. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22066. svr_.wait_until_ready();
  22067. }
  22068. void TearDown() override {
  22069. svr_.stop();
  22070. if (thread_.joinable()) thread_.join();
  22071. }
  22072. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22073. std::thread thread_;
  22074. int port_ = 0;
  22075. };
  22076. TEST_F(SSLStreamApiTest, GetAndPost) {
  22077. httplib::SSLClient cli("127.0.0.1", port_);
  22078. cli.enable_server_certificate_verification(false);
  22079. auto get = httplib::stream::Get(cli, "/hello");
  22080. EXPECT_EQ("Hello SSL!", read_body(get));
  22081. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22082. EXPECT_EQ("test", read_body(post));
  22083. }
  22084. #endif
  22085. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22086. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22087. // BodyReader
  22088. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22089. // Test that read timeout during streaming is detected
  22090. // Use a large content-length response where server delays mid-stream
  22091. Server svr;
  22092. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22093. // Send a large response with delay in the middle
  22094. res.set_content_provider(
  22095. 1000, // content_length
  22096. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22097. if (offset < 100) {
  22098. // Send first 100 bytes immediately
  22099. std::string data(100, 'A');
  22100. sink.write(data.c_str(), data.size());
  22101. return true;
  22102. }
  22103. // Then delay longer than client timeout
  22104. std::this_thread::sleep_for(std::chrono::seconds(3));
  22105. std::string data(900, 'B');
  22106. sink.write(data.c_str(), data.size());
  22107. return true;
  22108. });
  22109. });
  22110. auto port = 8091;
  22111. std::thread t([&]() { svr.listen("localhost", port); });
  22112. svr.wait_until_ready();
  22113. Client cli("localhost", port);
  22114. cli.set_read_timeout(1, 0); // 1 second timeout
  22115. auto handle = cli.open_stream("GET", "/slow-stream");
  22116. ASSERT_TRUE(handle.is_valid());
  22117. char buf[256];
  22118. ssize_t total = 0;
  22119. ssize_t n;
  22120. bool got_error = false;
  22121. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22122. total += n;
  22123. }
  22124. if (n < 0) {
  22125. got_error = true;
  22126. // Should be timeout or read error
  22127. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22128. handle.get_read_error() == Error::Read)
  22129. << "Actual error: " << to_string(handle.get_read_error());
  22130. }
  22131. // Either we got an error, or we got less data than expected
  22132. EXPECT_TRUE(got_error || total < 1000)
  22133. << "Expected timeout but got all " << total << " bytes";
  22134. svr.stop();
  22135. t.join();
  22136. }
  22137. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22138. // Test connection closed detection via BodyReader
  22139. Server svr;
  22140. std::atomic<bool> close_now{false};
  22141. svr.Get("/will-close", [&](const Request &, Response &res) {
  22142. res.set_content_provider(
  22143. 10000, // Large content_length that we won't fully send
  22144. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22145. if (offset < 100) {
  22146. std::string data(100, 'X');
  22147. sink.write(data.c_str(), data.size());
  22148. return true;
  22149. }
  22150. // Wait for signal then abort
  22151. while (!close_now) {
  22152. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22153. }
  22154. return false; // Abort - server will close connection
  22155. });
  22156. });
  22157. auto port = 8092;
  22158. std::thread t([&]() { svr.listen("localhost", port); });
  22159. svr.wait_until_ready();
  22160. Client cli("localhost", port);
  22161. auto handle = cli.open_stream("GET", "/will-close");
  22162. ASSERT_TRUE(handle.is_valid());
  22163. char buf[256];
  22164. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22165. EXPECT_GT(n, 0) << "First read should succeed";
  22166. // Signal server to close
  22167. close_now = true;
  22168. // Keep reading until error or EOF
  22169. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22170. // Keep reading
  22171. }
  22172. // Should get an error since content_length wasn't satisfied
  22173. if (n < 0) {
  22174. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22175. handle.get_read_error() == Error::Read)
  22176. << "Actual error: " << to_string(handle.get_read_error());
  22177. }
  22178. svr.stop();
  22179. t.join();
  22180. }
  22181. #ifdef CPPHTTPLIB_SSL_ENABLED
  22182. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22183. // Test that read timeout during SSL streaming is detected
  22184. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22185. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22186. res.set_content_provider(
  22187. 1000, "text/plain",
  22188. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22189. if (offset < 100) {
  22190. std::string data(100, 'A');
  22191. sink.write(data.c_str(), data.size());
  22192. return true;
  22193. }
  22194. std::this_thread::sleep_for(std::chrono::seconds(3));
  22195. std::string data(900, 'B');
  22196. sink.write(data.c_str(), data.size());
  22197. return true;
  22198. });
  22199. });
  22200. auto port = 8093;
  22201. std::thread t([&]() { svr.listen("localhost", port); });
  22202. svr.wait_until_ready();
  22203. SSLClient cli("localhost", port);
  22204. cli.enable_server_certificate_verification(false);
  22205. cli.set_read_timeout(1, 0); // 1 second timeout
  22206. auto handle = cli.open_stream("GET", "/slow-stream");
  22207. ASSERT_TRUE(handle.is_valid());
  22208. char buf[256];
  22209. ssize_t total = 0;
  22210. ssize_t n;
  22211. bool got_error = false;
  22212. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22213. total += n;
  22214. }
  22215. if (n < 0) {
  22216. got_error = true;
  22217. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22218. handle.get_read_error() == Error::Read)
  22219. << "Actual error: " << to_string(handle.get_read_error());
  22220. }
  22221. EXPECT_TRUE(got_error || total < 1000)
  22222. << "Expected timeout but got all " << total << " bytes";
  22223. svr.stop();
  22224. t.join();
  22225. }
  22226. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22227. // Test SSL connection closed detection
  22228. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22229. std::atomic<bool> close_now{false};
  22230. svr.Get("/will-close", [&](const Request &, Response &res) {
  22231. res.set_content_provider(
  22232. 10000, "text/plain",
  22233. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22234. if (offset < 100) {
  22235. std::string data(100, 'X');
  22236. sink.write(data.c_str(), data.size());
  22237. return true;
  22238. }
  22239. while (!close_now) {
  22240. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22241. }
  22242. return false;
  22243. });
  22244. });
  22245. auto port = 8094;
  22246. std::thread t([&]() { svr.listen("localhost", port); });
  22247. svr.wait_until_ready();
  22248. SSLClient cli("localhost", port);
  22249. cli.enable_server_certificate_verification(false);
  22250. auto handle = cli.open_stream("GET", "/will-close");
  22251. ASSERT_TRUE(handle.is_valid());
  22252. char buf[256];
  22253. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22254. EXPECT_GT(n, 0);
  22255. // Signal server to close
  22256. close_now = true;
  22257. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22258. // Keep reading
  22259. }
  22260. if (n < 0) {
  22261. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22262. handle.get_read_error() == Error::Read)
  22263. << "Actual error: " << to_string(handle.get_read_error());
  22264. }
  22265. svr.stop();
  22266. t.join();
  22267. }
  22268. #endif
  22269. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22270. using namespace httplib;
  22271. // Create a test file
  22272. const char *fname = "etag_testfile.txt";
  22273. const char *content = "etag-content";
  22274. {
  22275. std::ofstream ofs(fname);
  22276. ofs << content;
  22277. ASSERT_TRUE(ofs.good());
  22278. }
  22279. Server svr;
  22280. svr.set_mount_point("/static", ".");
  22281. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22282. svr.wait_until_ready();
  22283. Client cli(HOST, PORT);
  22284. // First request: should get 200 with ETag header
  22285. auto res1 = cli.Get("/static/etag_testfile.txt");
  22286. ASSERT_TRUE(res1);
  22287. ASSERT_EQ(200, res1->status);
  22288. ASSERT_TRUE(res1->has_header("ETag"));
  22289. std::string etag = res1->get_header_value("ETag");
  22290. EXPECT_FALSE(etag.empty());
  22291. // Verify ETag format: W/"hex-hex"
  22292. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22293. EXPECT_EQ('W', etag[0]);
  22294. EXPECT_EQ('/', etag[1]);
  22295. EXPECT_EQ('"', etag[2]);
  22296. EXPECT_EQ('"', etag.back());
  22297. // Exact match: expect 304 Not Modified
  22298. Headers h2 = {{"If-None-Match", etag}};
  22299. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22300. ASSERT_TRUE(res2);
  22301. EXPECT_EQ(304, res2->status);
  22302. // Wildcard match: expect 304 Not Modified
  22303. Headers h3 = {{"If-None-Match", "*"}};
  22304. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22305. ASSERT_TRUE(res3);
  22306. EXPECT_EQ(304, res3->status);
  22307. // Non-matching ETag: expect 200
  22308. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22309. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22310. ASSERT_TRUE(res4);
  22311. EXPECT_EQ(200, res4->status);
  22312. // Multiple ETags with one matching: expect 304
  22313. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22314. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22315. ASSERT_TRUE(res5);
  22316. EXPECT_EQ(304, res5->status);
  22317. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22318. // that equivalent to the single comma-separated list above, so the match on
  22319. // the second line must still be found.
  22320. Headers h6;
  22321. h6.emplace("If-None-Match", "W/\"other\"");
  22322. h6.emplace("If-None-Match", etag);
  22323. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22324. ASSERT_TRUE(res6);
  22325. EXPECT_EQ(304, res6->status);
  22326. svr.stop();
  22327. t.join();
  22328. std::remove(fname);
  22329. }
  22330. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22331. using namespace httplib;
  22332. Server svr;
  22333. svr.set_mount_point("/static", ".");
  22334. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22335. svr.wait_until_ready();
  22336. Client cli(HOST, PORT);
  22337. // Send If-None-Match: * to a non-existent file
  22338. Headers h = {{"If-None-Match", "*"}};
  22339. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22341. EXPECT_EQ(404, res->status);
  22342. svr.stop();
  22343. t.join();
  22344. }
  22345. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22346. using namespace httplib;
  22347. // Create a test file
  22348. const char *fname = "etag_boundary_testfile.txt";
  22349. const char *content = "boundary-test";
  22350. {
  22351. std::ofstream ofs(fname);
  22352. ofs << content;
  22353. ASSERT_TRUE(ofs.good());
  22354. }
  22355. Server svr;
  22356. svr.set_mount_point("/static", ".");
  22357. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22358. svr.wait_until_ready();
  22359. Client cli(HOST, PORT);
  22360. // Get the actual ETag
  22361. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22362. ASSERT_TRUE(res1);
  22363. ASSERT_EQ(200, res1->status);
  22364. ASSERT_TRUE(res1->has_header("ETag"));
  22365. std::string etag = res1->get_header_value("ETag");
  22366. // Test 1: Very long ETag value (longer than actual ETag)
  22367. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22368. Headers h1 = {{"If-None-Match", "W/"
  22369. "\"very-long-etag-value-that-is-much-longer-"
  22370. "than-the-actual-etag-value\""}};
  22371. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22372. ASSERT_TRUE(res2);
  22373. EXPECT_EQ(200, res2->status); // Should not match
  22374. // Test 2: Long string followed by wildcard
  22375. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22376. // string)
  22377. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22378. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22379. ASSERT_TRUE(res3);
  22380. EXPECT_EQ(304, res3->status); // Should match on "*"
  22381. // Test 3: Wildcard followed by long string
  22382. // Should match on "*" immediately and return 304
  22383. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22384. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22385. ASSERT_TRUE(res4);
  22386. EXPECT_EQ(304, res4->status); // Should match on "*"
  22387. // Test 4: Multiple long non-matching values
  22388. // Should NOT match and return 200 (test that all comparisons are safe)
  22389. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22390. "W/\"second-long-non-matching-value\", "
  22391. "W/\"third-long-non-matching-value\""}};
  22392. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22393. ASSERT_TRUE(res5);
  22394. EXPECT_EQ(200, res5->status); // Should not match
  22395. // Test 5: Single character that is not "*" (edge case)
  22396. Headers h5 = {{"If-None-Match", "X"}};
  22397. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22398. ASSERT_TRUE(res6);
  22399. EXPECT_EQ(200, res6->status); // Should not match
  22400. svr.stop();
  22401. t.join();
  22402. std::remove(fname);
  22403. }
  22404. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22405. using namespace httplib;
  22406. // Create a test file
  22407. const char *fname = "ims_testfile.txt";
  22408. const char *content = "if-modified-since-test";
  22409. {
  22410. std::ofstream ofs(fname);
  22411. ofs << content;
  22412. ASSERT_TRUE(ofs.good());
  22413. }
  22414. Server svr;
  22415. svr.set_mount_point("/static", ".");
  22416. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22417. svr.wait_until_ready();
  22418. Client cli(HOST, PORT);
  22419. // First request: should get 200 with Last-Modified header
  22420. auto res1 = cli.Get("/static/ims_testfile.txt");
  22421. ASSERT_TRUE(res1);
  22422. ASSERT_EQ(200, res1->status);
  22423. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22424. std::string last_modified = res1->get_header_value("Last-Modified");
  22425. EXPECT_FALSE(last_modified.empty());
  22426. // If-Modified-Since with same time: expect 304
  22427. Headers h2 = {{"If-Modified-Since", last_modified}};
  22428. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22429. ASSERT_TRUE(res2);
  22430. EXPECT_EQ(304, res2->status);
  22431. // If-Modified-Since with future time: expect 304
  22432. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22433. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22434. ASSERT_TRUE(res3);
  22435. EXPECT_EQ(304, res3->status);
  22436. // If-Modified-Since with past time: expect 200
  22437. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22438. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22439. ASSERT_TRUE(res4);
  22440. EXPECT_EQ(200, res4->status);
  22441. // If-None-Match takes precedence over If-Modified-Since
  22442. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22443. ASSERT_TRUE(res1->has_header("ETag"));
  22444. std::string etag = res1->get_header_value("ETag");
  22445. Headers h5 = {{"If-None-Match", etag},
  22446. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22447. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22448. ASSERT_TRUE(res5);
  22449. EXPECT_EQ(304, res5->status);
  22450. svr.stop();
  22451. t.join();
  22452. std::remove(fname);
  22453. }
  22454. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22455. using namespace httplib;
  22456. Server svr;
  22457. // Endpoint that returns compressible content
  22458. svr.Get("/compressible", [](const Request &, Response &res) {
  22459. // Return a large enough body to trigger compression
  22460. std::string body(1000, 'a');
  22461. res.set_content(body, "text/plain");
  22462. });
  22463. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22464. svr.wait_until_ready();
  22465. Client cli(HOST, PORT);
  22466. // Request with gzip support: should get Vary header when compressed
  22467. cli.set_compress(true);
  22468. auto res1 = cli.Get("/compressible");
  22469. ASSERT_TRUE(res1);
  22470. EXPECT_EQ(200, res1->status);
  22471. // If Content-Encoding is set, Vary should also be set
  22472. if (res1->has_header("Content-Encoding")) {
  22473. EXPECT_TRUE(res1->has_header("Vary"));
  22474. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22475. }
  22476. // Request without Accept-Encoding header: should not have compression
  22477. Headers h_no_compress;
  22478. auto res2 = cli.Get("/compressible", h_no_compress);
  22479. ASSERT_TRUE(res2);
  22480. EXPECT_EQ(200, res2->status);
  22481. // Verify Vary header is present when compression is applied
  22482. // (the exact behavior depends on server configuration)
  22483. svr.stop();
  22484. t.join();
  22485. }
  22486. TEST(ETagTest, IfRangeWithETag) {
  22487. using namespace httplib;
  22488. // Create a test file with known content
  22489. const char *fname = "if_range_testfile.txt";
  22490. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22491. {
  22492. std::ofstream ofs(fname);
  22493. ofs << content;
  22494. ASSERT_TRUE(ofs.good());
  22495. }
  22496. Server svr;
  22497. svr.set_mount_point("/static", ".");
  22498. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22499. svr.wait_until_ready();
  22500. Client cli(HOST, PORT);
  22501. // First request: get ETag
  22502. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22503. ASSERT_TRUE(res1);
  22504. ASSERT_EQ(200, res1->status);
  22505. ASSERT_TRUE(res1->has_header("ETag"));
  22506. std::string etag = res1->get_header_value("ETag");
  22507. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22508. // Since our server generates weak ETags (W/"..."), If-Range with our
  22509. // ETag should NOT result in partial content - it should return full content.
  22510. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22511. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22512. ASSERT_TRUE(res2);
  22513. // Weak ETag in If-Range -> full content (200), not partial (206)
  22514. EXPECT_EQ(200, res2->status);
  22515. EXPECT_EQ(content, res2->body);
  22516. EXPECT_FALSE(res2->has_header("Content-Range"));
  22517. // Range request with non-matching If-Range (ETag): should get 200 (full
  22518. // content)
  22519. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22520. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22521. ASSERT_TRUE(res3);
  22522. EXPECT_EQ(200, res3->status);
  22523. EXPECT_EQ(content, res3->body);
  22524. EXPECT_FALSE(res3->has_header("Content-Range"));
  22525. // Range request with strong ETag (hypothetical - our server doesn't generate
  22526. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22527. // should return full content)
  22528. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22529. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22530. ASSERT_TRUE(res4);
  22531. EXPECT_EQ(200, res4->status);
  22532. EXPECT_EQ(content, res4->body);
  22533. EXPECT_FALSE(res4->has_header("Content-Range"));
  22534. svr.stop();
  22535. t.join();
  22536. std::remove(fname);
  22537. }
  22538. TEST(ETagTest, IfRangeWithDate) {
  22539. using namespace httplib;
  22540. // Create a test file
  22541. const char *fname = "if_range_date_testfile.txt";
  22542. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22543. {
  22544. std::ofstream ofs(fname);
  22545. ofs << content;
  22546. ASSERT_TRUE(ofs.good());
  22547. }
  22548. Server svr;
  22549. svr.set_mount_point("/static", ".");
  22550. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22551. svr.wait_until_ready();
  22552. Client cli(HOST, PORT);
  22553. // First request: get Last-Modified
  22554. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22555. ASSERT_TRUE(res1);
  22556. ASSERT_EQ(200, res1->status);
  22557. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22558. std::string last_modified = res1->get_header_value("Last-Modified");
  22559. // Range request with matching If-Range (date): should get 206
  22560. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22561. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22562. ASSERT_TRUE(res2);
  22563. EXPECT_EQ(206, res2->status);
  22564. EXPECT_EQ("FGHIJ", res2->body);
  22565. // Range request with old If-Range date: should get 200 (full content)
  22566. Headers h3 = {{"Range", "bytes=5-9"},
  22567. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22568. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22569. ASSERT_TRUE(res3);
  22570. EXPECT_EQ(200, res3->status);
  22571. EXPECT_EQ(content, res3->body);
  22572. // Range request with future If-Range date: should get 206
  22573. Headers h4 = {{"Range", "bytes=0-4"},
  22574. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22575. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22576. ASSERT_TRUE(res4);
  22577. EXPECT_EQ(206, res4->status);
  22578. EXPECT_EQ("ABCDE", res4->body);
  22579. svr.stop();
  22580. t.join();
  22581. std::remove(fname);
  22582. }
  22583. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22584. using namespace httplib;
  22585. const char *fname = "etag_malformed.txt";
  22586. const char *content = "malformed-etag";
  22587. {
  22588. std::ofstream ofs(fname);
  22589. ofs << content;
  22590. ASSERT_TRUE(ofs.good());
  22591. }
  22592. Server svr;
  22593. svr.set_mount_point("/static", ".");
  22594. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22595. svr.wait_until_ready();
  22596. Client cli(HOST, PORT);
  22597. // baseline: should get 200 and an ETag
  22598. auto res1 = cli.Get("/static/etag_malformed.txt");
  22599. ASSERT_TRUE(res1);
  22600. ASSERT_EQ(200, res1->status);
  22601. ASSERT_TRUE(res1->has_header("ETag"));
  22602. // Malformed ETag value (missing quotes) should be treated as non-matching
  22603. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22604. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22605. ASSERT_TRUE(res_bad);
  22606. EXPECT_EQ(200, res_bad->status);
  22607. // Whitespace-only header value should be considered invalid / non-matching
  22608. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22609. "Host: localhost\r\n"
  22610. "If-None-Match: \r\n"
  22611. "Connection: close\r\n"
  22612. "\r\n";
  22613. std::string out;
  22614. ASSERT_TRUE(send_request(5, raw_req, &out));
  22615. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22616. svr.stop();
  22617. t.join();
  22618. std::remove(fname);
  22619. }
  22620. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22621. using namespace httplib;
  22622. const char *fname = "ims_invalid_format.txt";
  22623. const char *content = "ims-bad-format";
  22624. {
  22625. std::ofstream ofs(fname);
  22626. ofs << content;
  22627. ASSERT_TRUE(ofs.good());
  22628. }
  22629. Server svr;
  22630. svr.set_mount_point("/static", ".");
  22631. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22632. svr.wait_until_ready();
  22633. Client cli(HOST, PORT);
  22634. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22635. ASSERT_TRUE(res1);
  22636. ASSERT_EQ(200, res1->status);
  22637. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22638. // If-Modified-Since with invalid format should not result in 304
  22639. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22640. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22641. ASSERT_TRUE(res_bad);
  22642. EXPECT_EQ(200, res_bad->status);
  22643. // If-Range with invalid date format should be treated as mismatch -> full
  22644. // content (200)
  22645. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22646. {"If-Range", "invalid-date"}};
  22647. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22648. ASSERT_TRUE(res_ifrange);
  22649. EXPECT_EQ(200, res_ifrange->status);
  22650. svr.stop();
  22651. t.join();
  22652. std::remove(fname);
  22653. }
  22654. TEST(ETagTest, IfRangeWithMalformedETag) {
  22655. using namespace httplib;
  22656. const char *fname = "ifrange_malformed.txt";
  22657. const std::string content = "0123456789";
  22658. {
  22659. std::ofstream ofs(fname);
  22660. ofs << content;
  22661. ASSERT_TRUE(ofs.good());
  22662. }
  22663. Server svr;
  22664. svr.set_mount_point("/static", ".");
  22665. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22666. svr.wait_until_ready();
  22667. Client cli(HOST, PORT);
  22668. // First request: get ETag
  22669. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22670. ASSERT_TRUE(res1);
  22671. ASSERT_EQ(200, res1->status);
  22672. ASSERT_TRUE(res1->has_header("ETag"));
  22673. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22674. // full content (200)
  22675. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22676. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22677. ASSERT_TRUE(res2);
  22678. EXPECT_EQ(200, res2->status);
  22679. EXPECT_EQ(content, res2->body);
  22680. svr.stop();
  22681. t.join();
  22682. std::remove(fname);
  22683. }
  22684. TEST(ETagTest, ExtremeLargeDateValues) {
  22685. using namespace httplib;
  22686. const char *fname = "ims_extreme_date.txt";
  22687. const char *content = "ims-extreme-date";
  22688. {
  22689. std::ofstream ofs(fname);
  22690. ofs << content;
  22691. ASSERT_TRUE(ofs.good());
  22692. }
  22693. Server svr;
  22694. svr.set_mount_point("/static", ".");
  22695. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22696. svr.wait_until_ready();
  22697. Client cli(HOST, PORT);
  22698. auto res1 = cli.Get(std::string("/static/") + fname);
  22699. ASSERT_TRUE(res1);
  22700. ASSERT_EQ(200, res1->status);
  22701. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22702. // Extremely large year that may overflow date parsing routines.
  22703. Headers h_large_date = {
  22704. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22705. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22706. ASSERT_TRUE(res_bad);
  22707. // Expect server to treat this as invalid/mismatch and return full content
  22708. EXPECT_EQ(200, res_bad->status);
  22709. // If-Range with extremely large date should be treated as mismatch -> full
  22710. // content (200)
  22711. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22712. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22713. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22714. ASSERT_TRUE(res_ifrange);
  22715. EXPECT_EQ(200, res_ifrange->status);
  22716. svr.stop();
  22717. t.join();
  22718. std::remove(fname);
  22719. }
  22720. TEST(ETagTest, NegativeFileModificationTime) {
  22721. using namespace httplib;
  22722. const char *fname = "ims_negative_mtime.txt";
  22723. const std::string content = "negative-mtime";
  22724. {
  22725. std::ofstream ofs(fname);
  22726. ofs << content;
  22727. ASSERT_TRUE(ofs.good());
  22728. }
  22729. // Try to set file mtime to a negative value. This may fail on some
  22730. // platforms/filesystems; if it fails, the test will still verify server
  22731. // behaves safely by performing a regular conditional request.
  22732. #if defined(__APPLE__) || defined(__linux__)
  22733. bool set_negative = false;
  22734. do {
  22735. struct timeval times[2];
  22736. // access time: now
  22737. times[0].tv_sec = time(nullptr);
  22738. times[0].tv_usec = 0;
  22739. // modification time: negative (e.g., -1)
  22740. times[1].tv_sec = -1;
  22741. times[1].tv_usec = 0;
  22742. if (utimes(fname, times) == 0) { set_negative = true; }
  22743. } while (0);
  22744. #else
  22745. bool set_negative = false;
  22746. #endif
  22747. Server svr;
  22748. svr.set_mount_point("/static", ".");
  22749. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22750. svr.wait_until_ready();
  22751. Client cli(HOST, PORT);
  22752. auto res1 = cli.Get(std::string("/static/") + fname);
  22753. ASSERT_TRUE(res1);
  22754. ASSERT_EQ(200, res1->status);
  22755. bool has_last_modified = res1->has_header("Last-Modified");
  22756. std::string last_modified;
  22757. if (has_last_modified) {
  22758. last_modified = res1->get_header_value("Last-Modified");
  22759. }
  22760. if (set_negative) {
  22761. // If we successfully set a negative mtime, ensure server returns a
  22762. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22763. // with an old date and ensure server handles it without crash.
  22764. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22765. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22766. ASSERT_TRUE(res2);
  22767. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22768. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22769. } else {
  22770. // Could not set negative mtime on this platform; fall back to verifying
  22771. // that normal invalid/malformed dates are treated safely (non-304).
  22772. Headers h_bad_date = {
  22773. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22774. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22775. ASSERT_TRUE(res_bad);
  22776. EXPECT_EQ(200, res_bad->status);
  22777. }
  22778. svr.stop();
  22779. t.join();
  22780. std::remove(fname);
  22781. }
  22782. //==============================================================================
  22783. // Integration Tests with Server
  22784. //==============================================================================
  22785. class SSEIntegrationTest : public ::testing::Test {
  22786. protected:
  22787. void SetUp() override {
  22788. stop_server_.store(false);
  22789. events_.clear();
  22790. server_ = httplib::detail::make_unique<Server>();
  22791. setup_server();
  22792. start_server();
  22793. }
  22794. void TearDown() override {
  22795. stop_server_.store(true);
  22796. event_cv_.notify_all();
  22797. server_->stop();
  22798. if (server_thread_.joinable()) { server_thread_.join(); }
  22799. }
  22800. void setup_server() {
  22801. // Simple SSE endpoint
  22802. server_->Get("/events", [this](const Request &req, Response &res) {
  22803. auto last_id = req.get_header_value("Last-Event-ID");
  22804. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22805. res.set_chunked_content_provider(
  22806. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22807. std::unique_lock<std::mutex> lock(event_mutex_);
  22808. if (event_cv_.wait_for(
  22809. lock, std::chrono::milliseconds(200), [this] {
  22810. return !events_.empty() || stop_server_.load();
  22811. })) {
  22812. if (stop_server_.load()) { return false; }
  22813. if (!events_.empty()) {
  22814. std::string event = events_.front();
  22815. events_.erase(events_.begin());
  22816. sink.write(event.data(), event.size());
  22817. return true;
  22818. }
  22819. }
  22820. return !stop_server_.load();
  22821. });
  22822. });
  22823. // Endpoint that returns error
  22824. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22825. res.status = 500;
  22826. res.set_content("Internal Server Error", "text/plain");
  22827. });
  22828. // Endpoint for custom event types
  22829. server_->Get("/custom-events", [](const Request &, Response &res) {
  22830. res.set_chunked_content_provider(
  22831. "text/event-stream", [](size_t offset, DataSink &sink) {
  22832. if (offset == 0) {
  22833. std::string event = "event: update\ndata: updated\n\n"
  22834. "event: delete\ndata: deleted\n\n";
  22835. sink.write(event.data(), event.size());
  22836. }
  22837. return false; // End stream after sending
  22838. });
  22839. });
  22840. }
  22841. void start_server() {
  22842. port_ = server_->bind_to_any_port(HOST);
  22843. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22844. // Wait for server to start
  22845. while (!server_->is_running()) {
  22846. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22847. }
  22848. }
  22849. int get_port() const { return port_; }
  22850. void send_event(const std::string &event) {
  22851. std::lock_guard<std::mutex> lock(event_mutex_);
  22852. events_.push_back(event);
  22853. event_cv_.notify_all();
  22854. }
  22855. std::unique_ptr<Server> server_;
  22856. std::thread server_thread_;
  22857. std::mutex event_mutex_;
  22858. std::condition_variable event_cv_;
  22859. std::vector<std::string> events_;
  22860. std::atomic<bool> stop_server_{false};
  22861. std::string last_received_event_id_;
  22862. int port_ = 0;
  22863. };
  22864. //==============================================================================
  22865. // SSE Parser Tests
  22866. //==============================================================================
  22867. struct SSEParseResult {
  22868. std::vector<sse::SSEMessage> events;
  22869. std::vector<std::string> ids;
  22870. std::vector<int> retries;
  22871. bool ok = true;
  22872. std::string trace; // Every handler call in order
  22873. };
  22874. static SSEParseResult
  22875. sse_parse(const std::vector<std::string> &chunks,
  22876. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  22877. SSEParseResult r;
  22878. detail::SSEParser parser(
  22879. [&](const sse::SSEMessage &msg) {
  22880. r.events.push_back(msg);
  22881. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  22882. },
  22883. [&](const std::string &id) {
  22884. r.ids.push_back(id);
  22885. r.trace += "id[" + id + "]";
  22886. },
  22887. [&](int retry_ms) {
  22888. r.retries.push_back(retry_ms);
  22889. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  22890. },
  22891. max_event_length);
  22892. for (const auto &chunk : chunks) {
  22893. if (!parser.parse(chunk.data(), chunk.size())) {
  22894. r.ok = false;
  22895. break;
  22896. }
  22897. }
  22898. return r;
  22899. }
  22900. static SSEParseResult sse_parse(const std::string &stream) {
  22901. return sse_parse(std::vector<std::string>{stream});
  22902. }
  22903. TEST(SSEParserTest, SingleLineData) {
  22904. auto r = sse_parse("data: hello\n\n");
  22905. ASSERT_EQ(r.events.size(), 1u);
  22906. EXPECT_EQ(r.events[0].data, "hello");
  22907. EXPECT_EQ(r.events[0].event, "message");
  22908. }
  22909. TEST(SSEParserTest, MultiLineData) {
  22910. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  22911. ASSERT_EQ(r.events.size(), 1u);
  22912. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  22913. }
  22914. TEST(SSEParserTest, CustomEventType) {
  22915. auto r = sse_parse("event: update\ndata: payload\n\n");
  22916. ASSERT_EQ(r.events.size(), 1u);
  22917. EXPECT_EQ(r.events[0].event, "update");
  22918. EXPECT_EQ(r.events[0].data, "payload");
  22919. }
  22920. TEST(SSEParserTest, EventIdHandling) {
  22921. auto r = sse_parse("id: 12345\ndata: test\n\n");
  22922. ASSERT_EQ(r.events.size(), 1u);
  22923. EXPECT_EQ(r.events[0].id, "12345");
  22924. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  22925. }
  22926. TEST(SSEParserTest, EmptyEventId) {
  22927. auto r = sse_parse("id:\ndata: test\n\n");
  22928. ASSERT_EQ(r.events.size(), 1u);
  22929. EXPECT_EQ(r.events[0].id, "");
  22930. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  22931. }
  22932. TEST(SSEParserTest, CommentsIgnored) {
  22933. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  22934. ASSERT_EQ(r.events.size(), 1u);
  22935. EXPECT_EQ(r.events[0].data, "hello");
  22936. EXPECT_EQ(r.events[0].event, "message");
  22937. }
  22938. TEST(SSEParserTest, ColonInValue) {
  22939. auto r = sse_parse("data: hello:world:test\n\n");
  22940. ASSERT_EQ(r.events.size(), 1u);
  22941. EXPECT_EQ(r.events[0].data, "hello:world:test");
  22942. }
  22943. TEST(SSEParserTest, FieldNameOnly) {
  22944. // A line without a colon is a field name with an empty value
  22945. auto r = sse_parse("data\n\n");
  22946. ASSERT_EQ(r.events.size(), 1u);
  22947. EXPECT_EQ(r.events[0].data, "");
  22948. }
  22949. TEST(SSEParserTest, TrailingCarriageReturn) {
  22950. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  22951. ASSERT_EQ(r.events.size(), 1u);
  22952. EXPECT_EQ(r.events[0].event, "update");
  22953. EXPECT_EQ(r.events[0].data, "hello");
  22954. }
  22955. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  22956. auto r = sse_parse("data\r\n\r\n");
  22957. ASSERT_EQ(r.events.size(), 1u);
  22958. EXPECT_EQ(r.events[0].data, "");
  22959. }
  22960. TEST(SSEParserTest, CarriageReturnLineEnding) {
  22961. auto r = sse_parse("event: update\rdata: hello\r\r");
  22962. ASSERT_EQ(r.events.size(), 1u);
  22963. EXPECT_EQ(r.events[0].event, "update");
  22964. EXPECT_EQ(r.events[0].data, "hello");
  22965. }
  22966. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  22967. // Chunk boundaries fall inside every \r\n and right before the first one
  22968. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  22969. "\ndata: hello\r", "\n\r", "\n"});
  22970. ASSERT_EQ(r.events.size(), 1u);
  22971. EXPECT_EQ(r.events[0].event, "update");
  22972. EXPECT_EQ(r.events[0].data, "hello");
  22973. }
  22974. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  22975. // Only a BOM at the start of the stream is ignored
  22976. auto r = sse_parse("\xEF\xBB\xBF"
  22977. "data: first\n\n"
  22978. "\xEF\xBB\xBF"
  22979. "data: second\n\n");
  22980. ASSERT_EQ(r.events.size(), 1u);
  22981. EXPECT_EQ(r.events[0].data, "first");
  22982. }
  22983. TEST(SSEParserTest, UnknownFieldsIgnored) {
  22984. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  22985. ASSERT_EQ(r.events.size(), 1u);
  22986. EXPECT_EQ(r.events[0].data, "hello");
  22987. EXPECT_EQ(r.events[0].event, "message");
  22988. }
  22989. TEST(SSEParserTest, SpaceAfterColonOptional) {
  22990. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  22991. ASSERT_EQ(r.events.size(), 2u);
  22992. EXPECT_EQ(r.events[0].data, "hello");
  22993. EXPECT_EQ(r.events[1].data, "hello");
  22994. }
  22995. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  22996. // An event without data is not dispatched, and its type must not leak
  22997. // into the next event
  22998. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  22999. ASSERT_EQ(r.events.size(), 1u);
  23000. EXPECT_EQ(r.events[0].event, "message");
  23001. EXPECT_EQ(r.events[0].data, "hello");
  23002. }
  23003. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23004. // Also when the empty field replaces an earlier type
  23005. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23006. ASSERT_EQ(r.events.size(), 2u);
  23007. EXPECT_EQ(r.events[0].event, "message");
  23008. EXPECT_EQ(r.events[1].event, "message");
  23009. }
  23010. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23011. auto r = sse_parse("id: 42\n\n");
  23012. EXPECT_TRUE(r.events.empty());
  23013. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23014. }
  23015. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23016. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23017. ASSERT_EQ(r.events.size(), 2u);
  23018. EXPECT_EQ(r.events[0].id, "1");
  23019. EXPECT_EQ(r.events[1].id, "");
  23020. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23021. }
  23022. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23023. // Ids that cannot be carried in a Last-Event-ID header
  23024. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23025. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23026. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23027. }
  23028. TEST(SSEParserTest, RetryDigitsOnly) {
  23029. auto r = sse_parse("retry: 1000\n");
  23030. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23031. // A value that is not all ASCII digits, or does not fit, is ignored
  23032. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23033. EXPECT_TRUE(r.retries.empty());
  23034. }
  23035. TEST(SSEParserTest, CompleteEventParsing) {
  23036. auto r = sse_parse("event: notification\nid: evt-42\n"
  23037. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23038. ASSERT_EQ(r.events.size(), 1u);
  23039. EXPECT_EQ(r.events[0].event, "notification");
  23040. EXPECT_EQ(r.events[0].id, "evt-42");
  23041. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23042. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23043. }
  23044. TEST(SSEParserTest, IncompleteEventNotReported) {
  23045. // An event still waiting for its blank line when the stream ends is
  23046. // discarded per the SSE spec
  23047. auto r = sse_parse("id: 1\ndata: x\n");
  23048. EXPECT_TRUE(r.events.empty());
  23049. EXPECT_TRUE(r.ids.empty());
  23050. }
  23051. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23052. const std::vector<std::string> streams = {
  23053. "\xEF\xBB\xBF"
  23054. "data: bom\r\n\r\n",
  23055. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23056. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23057. };
  23058. for (const auto &stream : streams) {
  23059. auto expected = sse_parse(stream).trace;
  23060. ASSERT_FALSE(expected.empty());
  23061. for (size_t i = 0; i <= stream.size(); i++) {
  23062. auto r = sse_parse(
  23063. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23064. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23065. }
  23066. std::vector<std::string> bytes;
  23067. for (auto c : stream) {
  23068. bytes.emplace_back(1, c);
  23069. }
  23070. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23071. }
  23072. }
  23073. TEST(SSEParserTest, MaxEventLength) {
  23074. // A line still waiting for its end
  23075. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23076. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23077. // Data accumulated over the lines of one event
  23078. EXPECT_TRUE(
  23079. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23080. EXPECT_FALSE(
  23081. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23082. // 0 means no limit
  23083. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23084. // Events completed in the same chunk are still reported
  23085. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23086. EXPECT_FALSE(r.ok);
  23087. ASSERT_EQ(r.events.size(), 1u);
  23088. EXPECT_EQ(r.events[0].data, "a");
  23089. }
  23090. TEST(SSEMessageTest, Clear) {
  23091. sse::SSEMessage msg;
  23092. msg.event = "custom";
  23093. msg.data = "some data";
  23094. msg.id = "123";
  23095. msg.clear();
  23096. EXPECT_EQ(msg.event, "message");
  23097. EXPECT_EQ(msg.data, "");
  23098. EXPECT_EQ(msg.id, "");
  23099. }
  23100. //==============================================================================
  23101. // SSE Integration Tests
  23102. //==============================================================================
  23103. // Test: Successful connection and on_open callback
  23104. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23105. // Add a simple endpoint that sends one event and closes
  23106. server_->Get("/simple-event", [](const Request &, Response &res) {
  23107. res.set_chunked_content_provider(
  23108. "text/event-stream", [](size_t offset, DataSink &sink) {
  23109. if (offset == 0) {
  23110. std::string event = "data: hello\n\n";
  23111. sink.write(event.data(), event.size());
  23112. }
  23113. return false; // Close stream after sending
  23114. });
  23115. });
  23116. Client client("localhost", get_port());
  23117. sse::SSEClient sse(client, "/simple-event");
  23118. std::atomic<bool> open_called{false};
  23119. std::atomic<bool> message_received{false};
  23120. sse.on_open([&open_called]() { open_called.store(true); });
  23121. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23122. if (msg.data == "hello") { message_received.store(true); }
  23123. });
  23124. sse.set_reconnect_interval(100);
  23125. sse.set_max_reconnect_attempts(1);
  23126. // Start async
  23127. sse.start_async();
  23128. // Wait for message to be processed
  23129. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23130. sse.stop();
  23131. EXPECT_TRUE(open_called.load());
  23132. EXPECT_TRUE(message_received.load());
  23133. }
  23134. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23135. // A data line that never ends.
  23136. server_->Get("/endless-line", [](const Request &, Response &res) {
  23137. res.set_chunked_content_provider(
  23138. "text/event-stream", [](size_t offset, DataSink &sink) {
  23139. if (offset == 0) { sink.write("data: ", 6); }
  23140. std::string chunk(64 * 1024, 'A');
  23141. return sink.write(chunk.data(), chunk.size());
  23142. });
  23143. });
  23144. Client client("localhost", get_port());
  23145. sse::SSEClient sse(client, "/endless-line");
  23146. std::atomic<bool> too_long{false};
  23147. sse.on_error([&](Error err) {
  23148. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23149. });
  23150. sse.set_max_reconnect_attempts(1);
  23151. sse.start_async();
  23152. for (int i = 0; i < 500 && !too_long; i++) {
  23153. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23154. }
  23155. sse.stop();
  23156. EXPECT_TRUE(too_long);
  23157. }
  23158. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23159. // Far more in all than the client's payload limit below.
  23160. server_->Get("/many-events", [](const Request &, Response &res) {
  23161. res.set_chunked_content_provider(
  23162. "text/event-stream", [](size_t offset, DataSink &sink) {
  23163. if (offset == 0) {
  23164. std::string events;
  23165. for (int i = 0; i < 1000; i++) {
  23166. events += "data: message\n\n";
  23167. }
  23168. sink.write(events.data(), events.size());
  23169. }
  23170. return false;
  23171. });
  23172. });
  23173. Client client("localhost", get_port());
  23174. client.set_payload_max_length(1024);
  23175. sse::SSEClient sse(client, "/many-events");
  23176. std::atomic<int> messages{0};
  23177. std::atomic<bool> too_large{false};
  23178. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23179. sse.on_error([&](Error err) {
  23180. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23181. });
  23182. sse.set_max_reconnect_attempts(1);
  23183. sse.start_async();
  23184. for (int i = 0; i < 500 && messages < 1000; i++) {
  23185. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23186. }
  23187. sse.stop();
  23188. EXPECT_GE(messages.load(), 1000);
  23189. EXPECT_FALSE(too_large);
  23190. }
  23191. // Test: on_message callback
  23192. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23193. // Endpoint that sends multiple events then closes
  23194. server_->Get("/multi-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 events = "data: message1\n\ndata: message2\n\n";
  23199. sink.write(events.data(), events.size());
  23200. }
  23201. return false;
  23202. });
  23203. });
  23204. Client client("localhost", get_port());
  23205. sse::SSEClient sse(client, "/multi-event");
  23206. std::vector<std::string> received_messages;
  23207. std::mutex messages_mutex;
  23208. sse.on_message([&](const sse::SSEMessage &msg) {
  23209. std::lock_guard<std::mutex> lock(messages_mutex);
  23210. received_messages.push_back(msg.data);
  23211. });
  23212. sse.set_reconnect_interval(100);
  23213. sse.set_max_reconnect_attempts(1);
  23214. sse.start_async();
  23215. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23216. sse.stop();
  23217. std::lock_guard<std::mutex> lock(messages_mutex);
  23218. EXPECT_GE(received_messages.size(), 2u);
  23219. if (received_messages.size() >= 2) {
  23220. EXPECT_EQ(received_messages[0], "message1");
  23221. EXPECT_EQ(received_messages[1], "message2");
  23222. }
  23223. }
  23224. // Test: on_event for specific types
  23225. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23226. Client client("localhost", get_port());
  23227. sse::SSEClient sse(client, "/custom-events");
  23228. std::atomic<bool> update_received{false};
  23229. std::atomic<bool> delete_received{false};
  23230. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23231. if (msg.data == "updated") { update_received.store(true); }
  23232. });
  23233. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23234. if (msg.data == "deleted") { delete_received.store(true); }
  23235. });
  23236. sse.set_max_reconnect_attempts(1);
  23237. sse.start_async();
  23238. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23239. sse.stop();
  23240. EXPECT_TRUE(update_received.load());
  23241. EXPECT_TRUE(delete_received.load());
  23242. }
  23243. // Test: on_error callback on connection failure
  23244. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23245. // Connect to a non-existent port
  23246. Client client("localhost", 59999);
  23247. sse::SSEClient sse(client, "/events");
  23248. std::atomic<bool> error_called{false};
  23249. Error received_error = Error::Success;
  23250. sse.on_error([&](Error err) {
  23251. error_called.store(true);
  23252. received_error = err;
  23253. });
  23254. sse.set_reconnect_interval(50);
  23255. sse.set_max_reconnect_attempts(1);
  23256. sse.start_async();
  23257. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23258. sse.stop();
  23259. EXPECT_TRUE(error_called.load());
  23260. EXPECT_NE(received_error, Error::Success);
  23261. }
  23262. // Test: Last-Event-ID header sent on reconnect
  23263. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23264. // Endpoint that sends event with ID
  23265. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23266. res.set_chunked_content_provider(
  23267. "text/event-stream", [](size_t offset, DataSink &sink) {
  23268. if (offset == 0) {
  23269. std::string event = "id: evt-123\ndata: test\n\n";
  23270. sink.write(event.data(), event.size());
  23271. }
  23272. return false;
  23273. });
  23274. });
  23275. Client client("localhost", get_port());
  23276. sse::SSEClient sse(client, "/event-with-id");
  23277. std::atomic<bool> id_received{false};
  23278. sse.on_message([&](const sse::SSEMessage &msg) {
  23279. if (!msg.id.empty()) { id_received.store(true); }
  23280. });
  23281. sse.set_reconnect_interval(100);
  23282. sse.set_max_reconnect_attempts(1);
  23283. sse.start_async();
  23284. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23285. sse.stop();
  23286. EXPECT_TRUE(id_received.load());
  23287. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23288. }
  23289. // Test: last_event_id() read from another thread while start_async() runs
  23290. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23291. // Ids of every length up to 200, so the stored id keeps changing size
  23292. server_->Get("/many-ids", [](const Request &, Response &res) {
  23293. res.set_chunked_content_provider(
  23294. "text/event-stream", [](size_t offset, DataSink &sink) {
  23295. if (offset == 0) {
  23296. std::string events;
  23297. for (size_t i = 0; i < 2000; i++) {
  23298. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23299. events += "data: x\n\n";
  23300. }
  23301. events += "id: end\ndata: x\n\n";
  23302. sink.write(events.data(), events.size());
  23303. }
  23304. return false;
  23305. });
  23306. });
  23307. Client client("localhost", get_port());
  23308. sse::SSEClient sse(client, "/many-ids");
  23309. // Wait out the rest of the test rather than replay the stream
  23310. sse.set_reconnect_interval(10000);
  23311. sse.set_max_reconnect_attempts(1);
  23312. sse.start_async();
  23313. auto well_formed = true;
  23314. std::string id;
  23315. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23316. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23317. id = sse.last_event_id();
  23318. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23319. well_formed = false;
  23320. }
  23321. }
  23322. sse.stop();
  23323. EXPECT_TRUE(well_formed);
  23324. EXPECT_EQ(sse.last_event_id(), "end");
  23325. }
  23326. // Test: Manual stop
  23327. TEST_F(SSEIntegrationTest, ManualStop) {
  23328. // Endpoint that sends one event and stays open briefly. The server outlives
  23329. // this test body, so the provider uses the fixture's flag, not a local.
  23330. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23331. res.set_chunked_content_provider(
  23332. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23333. if (offset == 0) {
  23334. std::string event = "data: connected\n\n";
  23335. sink.write(event.data(), event.size());
  23336. }
  23337. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23338. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23339. }
  23340. return false;
  23341. });
  23342. });
  23343. Client client("localhost", get_port());
  23344. sse::SSEClient sse(client, "/stay-open");
  23345. std::atomic<bool> connected{false};
  23346. sse.on_open([&connected]() { connected.store(true); });
  23347. sse.set_reconnect_interval(100);
  23348. sse.set_max_reconnect_attempts(1);
  23349. sse.start_async();
  23350. // Wait for connection to establish
  23351. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23352. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23353. }
  23354. EXPECT_TRUE(connected.load());
  23355. EXPECT_TRUE(sse.is_connected());
  23356. // Signal handler to stop
  23357. stop_server_.store(true);
  23358. // Stop SSE client
  23359. sse.stop();
  23360. EXPECT_FALSE(sse.is_connected());
  23361. }
  23362. // Sends one event, then nothing until stop is set
  23363. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23364. return [&stop](const Request &, Response &res) {
  23365. res.set_chunked_content_provider(
  23366. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23367. if (offset == 0) {
  23368. std::string event = "data: hello\n\n";
  23369. sink.write(event.data(), event.size());
  23370. }
  23371. while (!stop.load()) {
  23372. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23373. }
  23374. return false;
  23375. });
  23376. };
  23377. }
  23378. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23379. static void check_stop_interrupts_blocked_read(Client &client) {
  23380. client.set_read_timeout(30, 0);
  23381. for (auto by_destructor : {false, true}) {
  23382. std::atomic<bool> received{false};
  23383. std::chrono::steady_clock::time_point start;
  23384. {
  23385. sse::SSEClient sse(client, "/idle-stream");
  23386. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23387. sse.start_async();
  23388. for (int i = 0; i < 500 && !received.load(); ++i) {
  23389. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23390. }
  23391. ASSERT_TRUE(received.load());
  23392. // Let the client block in the next read
  23393. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23394. start = std::chrono::steady_clock::now();
  23395. if (!by_destructor) { sse.stop(); }
  23396. }
  23397. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23398. std::chrono::seconds(2));
  23399. }
  23400. }
  23401. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23402. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23403. Client client("localhost", get_port());
  23404. check_stop_interrupts_blocked_read(client);
  23405. }
  23406. #ifdef CPPHTTPLIB_SSL_ENABLED
  23407. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23409. std::atomic<bool> done{false};
  23410. svr.Get("/idle-stream", idle_event_stream(done));
  23411. auto port = svr.bind_to_any_port(HOST);
  23412. std::thread t([&] { svr.listen_after_bind(); });
  23413. auto se = detail::scope_exit([&] {
  23414. done.store(true);
  23415. svr.stop();
  23416. t.join();
  23417. });
  23418. svr.wait_until_ready();
  23419. Client client("https://localhost:" + std::to_string(port));
  23420. client.enable_server_certificate_verification(false);
  23421. check_stop_interrupts_blocked_read(client);
  23422. }
  23423. #endif
  23424. // Test: SSEClient with custom headers
  23425. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23426. // Setup a server endpoint that checks for custom header
  23427. std::atomic<bool> header_received{false};
  23428. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23429. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23430. header_received.store(true);
  23431. }
  23432. res.set_chunked_content_provider("text/event-stream",
  23433. [](size_t, DataSink &) { return false; });
  23434. });
  23435. Client client("localhost", get_port());
  23436. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23437. sse::SSEClient sse(client, "/header-check", headers);
  23438. sse.set_max_reconnect_attempts(1);
  23439. sse.start_async();
  23440. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23441. sse.stop();
  23442. EXPECT_TRUE(header_received.load());
  23443. }
  23444. // Test: Reconnect interval configuration
  23445. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23446. Client client("localhost", get_port());
  23447. sse::SSEClient sse(client, "/events");
  23448. auto &result = sse.set_reconnect_interval(500);
  23449. // Builder pattern should return reference to self
  23450. EXPECT_EQ(&result, &sse);
  23451. }
  23452. // Test: Max reconnect attempts
  23453. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23454. // Connect to non-existent port to force reconnects
  23455. Client client("localhost", 59998);
  23456. sse::SSEClient sse(client, "/events");
  23457. std::atomic<int> error_count{0};
  23458. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23459. sse.set_reconnect_interval(50);
  23460. sse.set_max_reconnect_attempts(2);
  23461. auto start = std::chrono::steady_clock::now();
  23462. sse.start(); // Blocking call
  23463. auto end = std::chrono::steady_clock::now();
  23464. // Should have stopped after 2 failed attempts
  23465. EXPECT_GE(error_count.load(), 2);
  23466. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23467. auto duration =
  23468. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23469. #ifdef _WIN32
  23470. // Windows is much slower for socket connection failures
  23471. EXPECT_LT(duration.count(), 7000);
  23472. #else
  23473. EXPECT_LT(duration.count(), 1000);
  23474. #endif
  23475. }
  23476. // Test: Multi-line data in integration
  23477. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23478. // Endpoint with multi-line data
  23479. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23480. res.set_chunked_content_provider(
  23481. "text/event-stream", [](size_t offset, DataSink &sink) {
  23482. if (offset == 0) {
  23483. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23484. sink.write(event.data(), event.size());
  23485. }
  23486. return false;
  23487. });
  23488. });
  23489. Client client("localhost", get_port());
  23490. sse::SSEClient sse(client, "/multiline-data");
  23491. std::string received_data;
  23492. std::mutex data_mutex;
  23493. sse.on_message([&](const sse::SSEMessage &msg) {
  23494. std::lock_guard<std::mutex> lock(data_mutex);
  23495. received_data = msg.data;
  23496. });
  23497. sse.set_reconnect_interval(100);
  23498. sse.set_max_reconnect_attempts(1);
  23499. sse.start_async();
  23500. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23501. sse.stop();
  23502. std::lock_guard<std::mutex> lock(data_mutex);
  23503. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23504. }
  23505. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23506. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23507. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23508. DataSink &sink) {
  23509. if (offset == 0) {
  23510. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23511. sink.write(events.data(), events.size());
  23512. }
  23513. return false;
  23514. });
  23515. });
  23516. Client client("localhost", get_port());
  23517. sse::SSEClient sse(client, "/empty-data-lines");
  23518. std::mutex mutex;
  23519. std::condition_variable cv;
  23520. std::vector<std::string> received;
  23521. sse.on_message([&](const sse::SSEMessage &msg) {
  23522. std::lock_guard<std::mutex> lock(mutex);
  23523. received.push_back(msg.data);
  23524. cv.notify_all();
  23525. });
  23526. sse.set_max_reconnect_attempts(1);
  23527. sse.start_async();
  23528. {
  23529. std::unique_lock<std::mutex> lock(mutex);
  23530. cv.wait_for(lock, std::chrono::seconds(2),
  23531. [&] { return received.size() >= 3; });
  23532. }
  23533. sse.stop();
  23534. ASSERT_GE(received.size(), 3u);
  23535. EXPECT_EQ(received[0], "");
  23536. EXPECT_EQ(received[1], "\nhello");
  23537. EXPECT_EQ(received[2], "");
  23538. }
  23539. // Test: Auto-reconnect after server disconnection
  23540. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23541. std::atomic<int> connection_count{0};
  23542. std::atomic<int> message_count{0};
  23543. // Endpoint that sends one event and closes, forcing reconnect
  23544. server_->Get("/reconnect-test",
  23545. [&connection_count](const Request &, Response &res) {
  23546. connection_count.fetch_add(1);
  23547. res.set_chunked_content_provider(
  23548. "text/event-stream", [](size_t offset, DataSink &sink) {
  23549. if (offset == 0) {
  23550. std::string event = "data: hello\n\n";
  23551. sink.write(event.data(), event.size());
  23552. }
  23553. return false; // Close connection after sending
  23554. });
  23555. });
  23556. Client client("localhost", get_port());
  23557. sse::SSEClient sse(client, "/reconnect-test");
  23558. sse.on_message([&message_count](const sse::SSEMessage &) {
  23559. message_count.fetch_add(1);
  23560. });
  23561. sse.set_reconnect_interval(100);
  23562. sse.set_max_reconnect_attempts(3);
  23563. sse.start_async();
  23564. // Wait long enough for multiple reconnects
  23565. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23566. sse.stop();
  23567. // Should have connected multiple times (initial + reconnects)
  23568. EXPECT_GE(connection_count.load(), 2);
  23569. // Should have received messages from multiple connections
  23570. EXPECT_GE(message_count.load(), 2);
  23571. }
  23572. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23573. std::atomic<int> connection_count{0};
  23574. // Neither Content-Length nor chunked: the close ends the stream
  23575. server_->Get("/close-delimited",
  23576. [&connection_count](const Request &, Response &res) {
  23577. connection_count.fetch_add(1);
  23578. res.set_content_provider(
  23579. "text/event-stream", [](size_t offset, DataSink &sink) {
  23580. if (offset == 0) {
  23581. std::string event = "data: hello\n\n";
  23582. sink.write(event.data(), event.size());
  23583. } else {
  23584. sink.done();
  23585. }
  23586. return true;
  23587. });
  23588. });
  23589. Client client("localhost", get_port());
  23590. sse::SSEClient sse(client, "/close-delimited");
  23591. std::atomic<int> error_count{0};
  23592. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23593. sse.set_reconnect_interval(100);
  23594. sse.start_async();
  23595. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23596. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23597. }
  23598. sse.stop();
  23599. // Reconnects as after any end of the stream, but reports no error
  23600. EXPECT_GE(connection_count.load(), 2);
  23601. EXPECT_EQ(0, error_count.load());
  23602. }
  23603. // Test: A retry field of all ASCII digits sets the reconnection time
  23604. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23605. std::mutex mutex;
  23606. std::condition_variable cv;
  23607. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23608. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23609. {
  23610. std::lock_guard<std::mutex> lock(mutex);
  23611. connected_at.push_back(std::chrono::steady_clock::now());
  23612. cv.notify_all();
  23613. }
  23614. res.set_chunked_content_provider(
  23615. "text/event-stream", [](size_t offset, DataSink &sink) {
  23616. if (offset == 0) {
  23617. std::string event = "retry: 0\ndata: hello\n\n";
  23618. sink.write(event.data(), event.size());
  23619. }
  23620. return false;
  23621. });
  23622. });
  23623. Client client("localhost", get_port());
  23624. sse::SSEClient sse(client, "/zero-retry");
  23625. sse.set_reconnect_interval(10000);
  23626. sse.start_async();
  23627. {
  23628. std::unique_lock<std::mutex> lock(mutex);
  23629. cv.wait_for(lock, std::chrono::seconds(5),
  23630. [&] { return connected_at.size() >= 2; });
  23631. }
  23632. sse.stop();
  23633. // The server-supplied interval is applied, but never below 100ms, so
  23634. // "retry: 0" does not cause a busy reconnect loop
  23635. std::lock_guard<std::mutex> lock(mutex);
  23636. ASSERT_GE(connected_at.size(), 2u);
  23637. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23638. connected_at[1] - connected_at[0])
  23639. .count();
  23640. EXPECT_GE(interval_ms, 100);
  23641. }
  23642. // Test: Last-Event-ID sent on reconnect
  23643. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23644. std::atomic<int> connection_count{0};
  23645. std::vector<std::string> received_last_event_ids;
  23646. std::mutex id_mutex;
  23647. // Endpoint that checks Last-Event-ID header and sends event with ID
  23648. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23649. int conn = connection_count.fetch_add(1);
  23650. // Capture the Last-Event-ID header from each connection
  23651. {
  23652. std::lock_guard<std::mutex> lock(id_mutex);
  23653. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23654. }
  23655. res.set_chunked_content_provider(
  23656. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23657. if (offset == 0) {
  23658. std::string event =
  23659. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23660. sink.write(event.data(), event.size());
  23661. }
  23662. return false;
  23663. });
  23664. });
  23665. Client client("localhost", get_port());
  23666. sse::SSEClient sse(client, "/reconnect-with-id");
  23667. sse.set_reconnect_interval(100);
  23668. sse.set_max_reconnect_attempts(3);
  23669. sse.start_async();
  23670. // Wait for at least 2 connections
  23671. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23672. sse.stop();
  23673. // Verify behavior
  23674. std::lock_guard<std::mutex> lock(id_mutex);
  23675. EXPECT_GE(received_last_event_ids.size(), 2u);
  23676. // First connection should have no Last-Event-ID
  23677. if (!received_last_event_ids.empty()) {
  23678. EXPECT_EQ(received_last_event_ids[0], "");
  23679. }
  23680. // Second connection should have Last-Event-ID from first connection
  23681. if (received_last_event_ids.size() >= 2) {
  23682. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23683. }
  23684. }
  23685. // Test: set_headers updates headers used on reconnect
  23686. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23687. std::vector<std::string> received_tokens;
  23688. std::mutex token_mutex;
  23689. // Endpoint that captures Authorization header
  23690. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23691. {
  23692. std::lock_guard<std::mutex> lock(token_mutex);
  23693. received_tokens.push_back(req.get_header_value("Authorization"));
  23694. }
  23695. res.set_chunked_content_provider(
  23696. "text/event-stream", [](size_t offset, DataSink &sink) {
  23697. if (offset == 0) {
  23698. std::string event = "data: hello\n\n";
  23699. sink.write(event.data(), event.size());
  23700. }
  23701. return false; // Close connection to trigger reconnect
  23702. });
  23703. });
  23704. Client client("localhost", get_port());
  23705. Headers headers = {{"Authorization", "Bearer old-token"}};
  23706. sse::SSEClient sse(client, "/auth-check", headers);
  23707. // Update headers on each successful connection
  23708. sse.on_open(
  23709. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23710. sse.set_reconnect_interval(100);
  23711. sse.set_max_reconnect_attempts(3);
  23712. sse.start_async();
  23713. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23714. sse.stop();
  23715. std::lock_guard<std::mutex> lock(token_mutex);
  23716. ASSERT_GE(received_tokens.size(), 2u);
  23717. // First connection uses original header
  23718. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23719. // Second connection uses updated header from set_headers
  23720. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23721. }
  23722. // Test: 401 allows reconnection (so on_error can refresh headers)
  23723. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23724. std::atomic<int> connection_count{0};
  23725. // Endpoint: returns 401 on first attempt, 200 on second
  23726. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23727. int conn = connection_count.fetch_add(1);
  23728. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23729. res.status = StatusCode::Unauthorized_401;
  23730. res.set_content("Unauthorized", "text/plain");
  23731. return;
  23732. }
  23733. res.set_chunked_content_provider(
  23734. "text/event-stream", [](size_t offset, DataSink &sink) {
  23735. if (offset == 0) {
  23736. std::string event = "data: authenticated\n\n";
  23737. sink.write(event.data(), event.size());
  23738. }
  23739. return false;
  23740. });
  23741. });
  23742. Client client("localhost", get_port());
  23743. Headers headers = {{"Authorization", "Bearer expired"}};
  23744. sse::SSEClient sse(client, "/auth-retry", headers);
  23745. std::atomic<bool> message_received{false};
  23746. // Refresh token on error
  23747. sse.on_error(
  23748. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23749. sse.on_message([&](const sse::SSEMessage &msg) {
  23750. if (msg.data == "authenticated") { message_received.store(true); }
  23751. });
  23752. sse.set_reconnect_interval(100);
  23753. sse.set_max_reconnect_attempts(3);
  23754. sse.start_async();
  23755. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23756. sse.stop();
  23757. // Should have reconnected after 401 and succeeded with new token
  23758. EXPECT_GE(connection_count.load(), 2);
  23759. EXPECT_TRUE(message_received.load());
  23760. }
  23761. TEST(Issue2318Test, EmptyHostString) {
  23762. {
  23763. httplib::Client cli_empty("", PORT);
  23764. auto res = cli_empty.Get("/");
  23765. ASSERT_FALSE(res);
  23766. EXPECT_EQ(httplib::Error::Connection, res.error());
  23767. }
  23768. {
  23769. httplib::Client cli(" ", PORT);
  23770. auto res = cli.Get("/");
  23771. ASSERT_FALSE(res);
  23772. EXPECT_EQ(httplib::Error::Connection, res.error());
  23773. }
  23774. }
  23775. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23776. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23777. Server svr;
  23778. // Set a small payload limit (1KB)
  23779. svr.set_payload_max_length(1024);
  23780. svr.Post("/test", [&](const Request &req, Response &res) {
  23781. res.set_content("Body size: " + std::to_string(req.body.size()),
  23782. "text/plain");
  23783. });
  23784. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23785. auto se = detail::scope_exit([&] {
  23786. svr.stop();
  23787. listen_thread.join();
  23788. });
  23789. svr.wait_until_ready();
  23790. // Create data that compresses well but exceeds limit when decompressed
  23791. // 8KB of repeated null bytes compresses to a very small size
  23792. std::string original_data(8 * 1024, '\0');
  23793. // Compress the data using gzip
  23794. std::string compressed_data;
  23795. detail::gzip_compressor compressor;
  23796. compressor.compress(original_data.data(), original_data.size(), true,
  23797. [&](const char *data, size_t size) {
  23798. compressed_data.append(data, size);
  23799. return true;
  23800. });
  23801. // Verify compression worked (compressed should be much smaller)
  23802. ASSERT_LT(compressed_data.size(), original_data.size());
  23803. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23804. // Send compressed data with Content-Encoding: gzip
  23805. Client cli(HOST, PORT);
  23806. Headers headers = {{"Content-Encoding", "gzip"}};
  23807. auto res =
  23808. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23809. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23811. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23812. }
  23813. #endif
  23814. // ============================================================================
  23815. // OpenSSL-Specific Tests
  23816. // ============================================================================
  23817. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23818. X509 *readCertificate(const std::string &strFileName) {
  23819. std::ifstream inStream(strFileName);
  23820. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23821. std::istreambuf_iterator<char>());
  23822. if (strCertPEM.empty()) return (nullptr);
  23823. BIO *pbCert = BIO_new(BIO_s_mem());
  23824. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23825. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23826. BIO_free(pbCert);
  23827. return (pCert);
  23828. }
  23829. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23830. std::ifstream inStream(strFileName);
  23831. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23832. std::istreambuf_iterator<char>());
  23833. if (strPrivateKeyPEM.empty()) return (nullptr);
  23834. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23835. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23836. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23837. BIO_free(pbPrivKey);
  23838. return (pPrivateKey);
  23839. }
  23840. TEST(BindServerTest, UpdateCerts) {
  23841. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23842. int port = svr.bind_to_any_port("0.0.0.0");
  23843. ASSERT_TRUE(svr.is_valid());
  23844. ASSERT_TRUE(port > 0);
  23845. X509 *cert = readCertificate(SERVER_CERT_FILE);
  23846. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  23847. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  23848. ASSERT_TRUE(cert != nullptr);
  23849. ASSERT_TRUE(ca_cert != nullptr);
  23850. ASSERT_TRUE(key != nullptr);
  23851. X509_STORE *cert_store = X509_STORE_new();
  23852. X509_STORE_add_cert(cert_store, ca_cert);
  23853. // svr.update_certs(cert, key, cert_store); // deprecated
  23854. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  23855. CLIENT_CA_CERT_FILE);
  23856. ASSERT_TRUE(svr.is_valid());
  23857. svr.stop();
  23858. X509_STORE_free(cert_store);
  23859. X509_free(cert);
  23860. X509_free(ca_cert);
  23861. EVP_PKEY_free(key);
  23862. }
  23863. // Test that update_certs() updates client CA list correctly
  23864. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  23865. // Start with file-based constructor
  23866. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23867. ASSERT_TRUE(svr.is_valid());
  23868. // Initially no client CA list should be set
  23869. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23870. ASSERT_TRUE(ssl_ctx != nullptr);
  23871. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  23872. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  23873. // Now update with client CA (PEM string)
  23874. std::string cert_pem, key_pem, ca_pem;
  23875. read_file(SERVER_CERT_FILE, cert_pem);
  23876. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  23877. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  23878. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  23879. ASSERT_TRUE(svr.is_valid());
  23880. // Now client CA list should be set
  23881. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  23882. ASSERT_TRUE(ca_list_after != nullptr);
  23883. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  23884. }
  23885. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  23886. // Test that the file-path SSLServer constructor properly sets the client CA
  23887. // list that is sent to clients during the TLS handshake (CertificateRequest)
  23888. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23889. ASSERT_TRUE(svr.is_valid());
  23890. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  23891. ASSERT_TRUE(ssl_ctx != nullptr);
  23892. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  23893. ASSERT_TRUE(ca_list != nullptr);
  23894. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  23895. }
  23896. #endif
  23897. // ============================================================================
  23898. // MbedTLS-Specific Tests
  23899. // ============================================================================
  23900. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  23901. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  23902. using namespace httplib::tls;
  23903. // Track if callback was invoked
  23904. bool callback_invoked = false;
  23905. // The callback receives void* ctx which is actually MbedTlsContext*
  23906. // We can access the mbedtls_ssl_config via the context
  23907. auto setup_callback = [&callback_invoked](void *ctx) {
  23908. callback_invoked = true;
  23909. // Cast to MbedTlsContext* to access the ssl config
  23910. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23911. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23912. // Use static variables to hold certificate data (simplified for test)
  23913. static mbedtls_x509_crt own_cert;
  23914. static mbedtls_pk_context own_key;
  23915. static mbedtls_x509_crt ca_chain;
  23916. static bool initialized = false;
  23917. if (!initialized) {
  23918. mbedtls_x509_crt_init(&own_cert);
  23919. mbedtls_pk_init(&own_key);
  23920. mbedtls_x509_crt_init(&ca_chain);
  23921. // Load server certificate
  23922. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23923. return false;
  23924. }
  23925. // Load server private key.
  23926. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23927. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23928. #if MBEDTLS_VERSION_MAJOR == 3
  23929. ,
  23930. mbedtls_ctr_drbg_random, nullptr
  23931. #endif
  23932. ) != 0) {
  23933. return false;
  23934. }
  23935. // Load CA chain for client verification
  23936. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23937. return false;
  23938. }
  23939. initialized = true;
  23940. }
  23941. // Configure the SSL config
  23942. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23943. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23944. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23945. // Set minimum TLS version using mbedTLS native API
  23946. #if MBEDTLS_VERSION_MAJOR >= 3
  23947. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23948. #else
  23949. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23950. MBEDTLS_SSL_MINOR_VERSION_3);
  23951. #endif
  23952. return true;
  23953. };
  23954. SSLServer svr(setup_callback);
  23955. ASSERT_TRUE(svr.is_valid());
  23956. ASSERT_TRUE(callback_invoked);
  23957. svr.Get("/test", [&](const Request &req, Response &res) {
  23958. res.set_content("test", "text/plain");
  23959. auto cert = req.peer_cert();
  23960. ASSERT_TRUE(static_cast<bool>(cert));
  23961. auto common_name = cert.subject_cn();
  23962. EXPECT_EQ("Common Name", common_name);
  23963. });
  23964. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23965. auto se = detail::scope_exit([&] {
  23966. svr.stop();
  23967. t.join();
  23968. ASSERT_FALSE(svr.is_running());
  23969. });
  23970. svr.wait_until_ready();
  23971. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23972. cli.enable_server_certificate_verification(false);
  23973. cli.set_connection_timeout(30);
  23974. auto res = cli.Get("/test");
  23975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23976. ASSERT_EQ(StatusCode::OK_200, res->status);
  23977. }
  23978. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23979. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23980. // keep-alive SSL session, which reads through that config in
  23981. // mbedtls_ssl_close_notify.
  23982. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23983. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23984. ASSERT_TRUE(svr.is_valid());
  23985. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23986. res.set_content("test", "text/plain");
  23987. });
  23988. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23989. auto se = detail::scope_exit([&] {
  23990. svr.stop();
  23991. t.join();
  23992. ASSERT_FALSE(svr.is_running());
  23993. });
  23994. svr.wait_until_ready();
  23995. {
  23996. SSLClient cli(HOST, PORT);
  23997. cli.enable_server_certificate_verification(false);
  23998. cli.set_keep_alive(true);
  23999. auto res = cli.Get("/test");
  24000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24001. ASSERT_EQ(StatusCode::OK_200, res->status);
  24002. // cli is destructed here with the keep-alive SSL session still open.
  24003. }
  24004. }
  24005. #endif
  24006. // WebSocket Tests
  24007. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24008. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24009. // defining the meaning of these bits has been negotiated.
  24010. auto make_frame = [](uint8_t first_byte) {
  24011. std::string frame;
  24012. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24013. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24014. frame += "Hello";
  24015. return frame;
  24016. };
  24017. // RSV1 set (0x40)
  24018. {
  24019. detail::BufferStream strm;
  24020. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24021. ws::Opcode opcode;
  24022. std::string payload;
  24023. bool fin;
  24024. EXPECT_EQ(
  24025. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24026. ws::impl::FrameRead::Fail);
  24027. }
  24028. // RSV2 set (0x20)
  24029. {
  24030. detail::BufferStream strm;
  24031. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24032. ws::Opcode opcode;
  24033. std::string payload;
  24034. bool fin;
  24035. EXPECT_EQ(
  24036. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24037. ws::impl::FrameRead::Fail);
  24038. }
  24039. // RSV3 set (0x10)
  24040. {
  24041. detail::BufferStream strm;
  24042. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24043. ws::Opcode opcode;
  24044. std::string payload;
  24045. bool fin;
  24046. EXPECT_EQ(
  24047. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24048. ws::impl::FrameRead::Fail);
  24049. }
  24050. // No RSV bits set - should succeed
  24051. {
  24052. detail::BufferStream strm;
  24053. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24054. ws::Opcode opcode;
  24055. std::string payload;
  24056. bool fin;
  24057. EXPECT_EQ(
  24058. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24059. ws::impl::FrameRead::Ok);
  24060. EXPECT_EQ(ws::Opcode::Text, opcode);
  24061. EXPECT_EQ("Hello", payload);
  24062. EXPECT_TRUE(fin);
  24063. }
  24064. }
  24065. TEST(WebSocketTest, ControlFrameValidation) {
  24066. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24067. // payload length <= 125.
  24068. // Ping with FIN=0 - must be rejected
  24069. {
  24070. detail::BufferStream strm;
  24071. std::string frame;
  24072. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24073. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24074. strm.write(frame.data(), frame.size());
  24075. ws::Opcode opcode;
  24076. std::string payload;
  24077. bool fin;
  24078. EXPECT_EQ(
  24079. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24080. ws::impl::FrameRead::Fail);
  24081. }
  24082. // Close with FIN=0 - must be rejected
  24083. {
  24084. detail::BufferStream strm;
  24085. std::string frame;
  24086. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24087. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24088. strm.write(frame.data(), frame.size());
  24089. ws::Opcode opcode;
  24090. std::string payload;
  24091. bool fin;
  24092. EXPECT_EQ(
  24093. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24094. ws::impl::FrameRead::Fail);
  24095. }
  24096. // Ping with payload_len=126 (extended length) - must be rejected
  24097. {
  24098. detail::BufferStream strm;
  24099. std::string frame;
  24100. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24101. frame += static_cast<char>(126); // payload_len=126 (>125)
  24102. frame += static_cast<char>(0x00); // extended length high byte
  24103. frame += static_cast<char>(126); // extended length low byte
  24104. frame += std::string(126, 'x');
  24105. strm.write(frame.data(), frame.size());
  24106. ws::Opcode opcode;
  24107. std::string payload;
  24108. bool fin;
  24109. EXPECT_EQ(
  24110. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24111. ws::impl::FrameRead::Fail);
  24112. }
  24113. // Ping with FIN=1 and payload_len=125 - should succeed
  24114. {
  24115. detail::BufferStream strm;
  24116. std::string frame;
  24117. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24118. frame += static_cast<char>(125); // payload_len=125
  24119. frame += std::string(125, 'x');
  24120. strm.write(frame.data(), frame.size());
  24121. ws::Opcode opcode;
  24122. std::string payload;
  24123. bool fin;
  24124. EXPECT_EQ(
  24125. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24126. ws::impl::FrameRead::Ok);
  24127. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24128. EXPECT_EQ(125u, payload.size());
  24129. EXPECT_TRUE(fin);
  24130. }
  24131. }
  24132. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24133. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24134. // length MUST be 0.
  24135. // MSB set - must be rejected
  24136. {
  24137. detail::BufferStream strm;
  24138. std::string frame;
  24139. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24140. frame += static_cast<char>(127); // 64-bit extended length
  24141. frame += static_cast<char>(0x80); // MSB set (invalid)
  24142. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24143. strm.write(frame.data(), frame.size());
  24144. ws::Opcode opcode;
  24145. std::string payload;
  24146. bool fin;
  24147. EXPECT_EQ(
  24148. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24149. ws::impl::FrameRead::Fail);
  24150. }
  24151. // MSB clear - should pass length parsing (will be rejected by max_len,
  24152. // but that's a different check; use a small length to verify)
  24153. {
  24154. detail::BufferStream strm;
  24155. std::string frame;
  24156. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24157. frame += static_cast<char>(127); // 64-bit extended length
  24158. frame += std::string(7, '\0'); // high bytes = 0
  24159. frame += static_cast<char>(0x03); // length = 3
  24160. frame += "abc";
  24161. strm.write(frame.data(), frame.size());
  24162. ws::Opcode opcode;
  24163. std::string payload;
  24164. bool fin;
  24165. EXPECT_EQ(
  24166. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24167. ws::impl::FrameRead::Ok);
  24168. EXPECT_EQ(ws::Opcode::Text, opcode);
  24169. EXPECT_EQ("abc", payload);
  24170. }
  24171. }
  24172. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24173. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24174. // Valid UTF-8
  24175. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24176. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24177. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24178. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24179. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24180. // Invalid UTF-8
  24181. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24182. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24183. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24184. EXPECT_FALSE(
  24185. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24186. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24187. }
  24188. TEST(WebSocketTest, ConnectAndDisconnect) {
  24189. Server svr;
  24190. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24191. std::string msg;
  24192. while (ws.read(msg)) {}
  24193. });
  24194. auto port = svr.bind_to_any_port(HOST);
  24195. std::thread t([&]() { svr.listen_after_bind(); });
  24196. svr.wait_until_ready();
  24197. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24198. auto res = client.connect();
  24199. ASSERT_TRUE(res);
  24200. EXPECT_EQ(Error::Success, res.error());
  24201. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24202. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24203. EXPECT_TRUE(client.is_open());
  24204. client.close();
  24205. EXPECT_FALSE(client.is_open());
  24206. svr.stop();
  24207. t.join();
  24208. }
  24209. TEST(WebSocketTest, ValidURL) {
  24210. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24211. EXPECT_TRUE(ws1.is_valid());
  24212. ws::WebSocketClient ws2("ws://example.com/path");
  24213. EXPECT_TRUE(ws2.is_valid());
  24214. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24215. EXPECT_TRUE(ws3.is_valid());
  24216. #ifdef CPPHTTPLIB_SSL_ENABLED
  24217. ws::WebSocketClient wss1("wss://example.com/path");
  24218. EXPECT_TRUE(wss1.is_valid());
  24219. ws::WebSocketClient wss2("wss://example.com:443/path");
  24220. EXPECT_TRUE(wss2.is_valid());
  24221. #endif
  24222. }
  24223. TEST(WebSocketTest, InvalidURL) {
  24224. // No scheme
  24225. ws::WebSocketClient ws1("localhost:8080/path");
  24226. EXPECT_FALSE(ws1.is_valid());
  24227. // No path
  24228. ws::WebSocketClient ws2("ws://localhost:8080");
  24229. EXPECT_FALSE(ws2.is_valid());
  24230. // Empty string
  24231. ws::WebSocketClient ws3("");
  24232. EXPECT_FALSE(ws3.is_valid());
  24233. // Missing host
  24234. ws::WebSocketClient ws4("ws://:8080/path");
  24235. EXPECT_FALSE(ws4.is_valid());
  24236. // Port number overflow — should not crash
  24237. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24238. EXPECT_FALSE(ws5.is_valid());
  24239. // Port out of range
  24240. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24241. EXPECT_FALSE(ws6.is_valid());
  24242. }
  24243. TEST(WebSocketTest, UnsupportedScheme) {
  24244. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24245. ws::WebSocketClient ws1("http://localhost:8080/path");
  24246. EXPECT_FALSE(ws1.is_valid());
  24247. ws::WebSocketClient ws2("https://localhost:8080/path");
  24248. EXPECT_FALSE(ws2.is_valid());
  24249. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24250. EXPECT_FALSE(ws3.is_valid());
  24251. #else
  24252. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24253. std::invalid_argument);
  24254. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24255. std::invalid_argument);
  24256. #endif
  24257. }
  24258. TEST(WebSocketTest, ConnectWhenInvalid) {
  24259. ws::WebSocketClient ws("not a valid url");
  24260. EXPECT_FALSE(ws.is_valid());
  24261. auto res = ws.connect();
  24262. EXPECT_FALSE(res);
  24263. EXPECT_EQ(Error::Connection, res.error());
  24264. EXPECT_EQ(-1, res.status());
  24265. }
  24266. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24267. // Grab a port that is free, then close it again so nothing listens there
  24268. Server svr;
  24269. auto port = svr.bind_to_any_port(HOST);
  24270. svr.stop();
  24271. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24272. auto res = client.connect();
  24273. ASSERT_FALSE(res);
  24274. EXPECT_EQ(Error::Connection, res.error());
  24275. EXPECT_EQ(-1, res.status());
  24276. }
  24277. TEST(WebSocketTest, DefaultPort) {
  24278. ws::WebSocketClient ws1("ws://example.com/path");
  24279. EXPECT_TRUE(ws1.is_valid());
  24280. // ws:// defaults to port 80 (verified by successful parse)
  24281. #ifdef CPPHTTPLIB_SSL_ENABLED
  24282. ws::WebSocketClient ws2("wss://example.com/path");
  24283. EXPECT_TRUE(ws2.is_valid());
  24284. // wss:// defaults to port 443 (verified by successful parse)
  24285. #endif
  24286. }
  24287. TEST(WebSocketTest, IPv6LiteralAddress) {
  24288. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24289. EXPECT_TRUE(ws1.is_valid());
  24290. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24291. EXPECT_TRUE(ws2.is_valid());
  24292. }
  24293. TEST(WebSocketTest, ComplexPath) {
  24294. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24295. EXPECT_TRUE(ws1.is_valid());
  24296. ws::WebSocketClient ws2("ws://localhost:8080/");
  24297. EXPECT_TRUE(ws2.is_valid());
  24298. }
  24299. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24300. Server svr;
  24301. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24302. std::string msg;
  24303. while (ws.read(msg)) {}
  24304. });
  24305. auto port = svr.bind_to_any_port(HOST);
  24306. std::thread t([&]() { svr.listen_after_bind(); });
  24307. svr.wait_until_ready();
  24308. auto another_host = "example.com";
  24309. auto wrong_ip = "192.0.2.1";
  24310. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24311. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24312. ASSERT_TRUE(client.connect());
  24313. EXPECT_TRUE(client.is_open());
  24314. client.close();
  24315. svr.stop();
  24316. t.join();
  24317. }
  24318. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24319. Server svr;
  24320. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24321. std::string msg;
  24322. while (ws.read(msg)) {}
  24323. });
  24324. auto port = svr.bind_to_any_port(HOST);
  24325. std::thread t([&]() { svr.listen_after_bind(); });
  24326. svr.wait_until_ready();
  24327. auto wrong_ip = "192.0.2.1";
  24328. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24329. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24330. client.set_connection_timeout(1);
  24331. client.set_read_timeout(1);
  24332. client.set_write_timeout(1);
  24333. EXPECT_FALSE(client.connect());
  24334. EXPECT_FALSE(client.is_open());
  24335. svr.stop();
  24336. t.join();
  24337. }
  24338. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24339. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24340. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24341. // (RFC 6761) is only a map key and the Host header value.
  24342. auto host = "target.invalid";
  24343. Server svr;
  24344. std::string received_host;
  24345. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24346. received_host = req.get_header_value("Host");
  24347. std::string msg;
  24348. while (ws.read(msg)) {}
  24349. });
  24350. auto port = svr.bind_to_any_port(HOST);
  24351. std::thread t([&]() { svr.listen_after_bind(); });
  24352. // ASSERT_* below returns from the test body, which would leave t joinable
  24353. // and make ~thread call std::terminate.
  24354. auto se = detail::scope_exit([&] {
  24355. svr.stop();
  24356. if (t.joinable()) { t.join(); }
  24357. });
  24358. svr.wait_until_ready();
  24359. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24360. std::to_string(port) + "/ws");
  24361. client.set_direct_hostname_addr_map({{host, HOST}});
  24362. ASSERT_TRUE(client.connect());
  24363. EXPECT_TRUE(client.is_open());
  24364. client.close();
  24365. svr.stop();
  24366. t.join();
  24367. // The mapping only redirects the connection; the identity stays host_.
  24368. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24369. }
  24370. class WebSocketIntegrationTest : public ::testing::Test {
  24371. protected:
  24372. void SetUp() override {
  24373. server_ = httplib::detail::make_unique<Server>();
  24374. setup_server();
  24375. start_server();
  24376. }
  24377. void TearDown() override {
  24378. server_->stop();
  24379. if (server_thread_.joinable()) { server_thread_.join(); }
  24380. }
  24381. void setup_server() {
  24382. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24383. std::string msg;
  24384. ws::ReadResult ret;
  24385. while ((ret = ws.read(msg))) {
  24386. if (ret == ws::Binary) {
  24387. ws.send(msg.data(), msg.size());
  24388. } else {
  24389. ws.send(msg);
  24390. }
  24391. }
  24392. });
  24393. server_->WebSocket("/ws-echo-string",
  24394. [](const Request &, ws::WebSocket &ws) {
  24395. std::string msg;
  24396. while (ws.read(msg)) {
  24397. ws.send("echo: " + msg);
  24398. }
  24399. });
  24400. server_->WebSocket(
  24401. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24402. // Echo back request metadata
  24403. ws.send("path:" + req.path);
  24404. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24405. std::string msg;
  24406. while (ws.read(msg)) {}
  24407. });
  24408. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24409. std::string msg;
  24410. ws.read(msg); // wait for a message
  24411. ws.close();
  24412. });
  24413. server_->WebSocket("/ws-close-status",
  24414. [](const Request &, ws::WebSocket &ws) {
  24415. std::string msg;
  24416. ws.read(msg); // wait for a message
  24417. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24418. });
  24419. server_->WebSocket(
  24420. "/ws-subprotocol",
  24421. [](const Request &, ws::WebSocket &ws) {
  24422. std::string msg;
  24423. while (ws.read(msg)) {
  24424. ws.send(msg);
  24425. }
  24426. },
  24427. [](const std::vector<std::string> &protocols) -> std::string {
  24428. for (const auto &p : protocols) {
  24429. if (p == "graphql-ws") { return p; }
  24430. }
  24431. return "";
  24432. });
  24433. server_->WebSocket(
  24434. "/ws-subprotocol-unoffered",
  24435. [](const Request &, ws::WebSocket &ws) {
  24436. std::string msg;
  24437. while (ws.read(msg)) {
  24438. ws.send(msg);
  24439. }
  24440. },
  24441. [](const std::vector<std::string> &) -> std::string {
  24442. return "admin";
  24443. });
  24444. }
  24445. void start_server() {
  24446. port_ = server_->bind_to_any_port(HOST);
  24447. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24448. server_->wait_until_ready();
  24449. }
  24450. std::unique_ptr<Server> server_;
  24451. std::thread server_thread_;
  24452. int port_ = 0;
  24453. };
  24454. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24455. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24456. "/ws-echo");
  24457. ASSERT_TRUE(client.connect());
  24458. ASSERT_TRUE(client.is_open());
  24459. ASSERT_TRUE(client.send("Hello WebSocket"));
  24460. std::string msg;
  24461. EXPECT_EQ(ws::Text, client.read(msg));
  24462. EXPECT_EQ("Hello WebSocket", msg);
  24463. client.close();
  24464. }
  24465. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24466. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24467. "/ws-echo");
  24468. ASSERT_TRUE(client.connect());
  24469. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24470. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24471. std::string msg;
  24472. EXPECT_EQ(ws::Binary, client.read(msg));
  24473. EXPECT_EQ(binary_data, msg);
  24474. client.close();
  24475. }
  24476. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24477. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24478. "/ws-echo");
  24479. ASSERT_TRUE(client.connect());
  24480. for (int i = 0; i < 10; i++) {
  24481. auto text = "message " + std::to_string(i);
  24482. ASSERT_TRUE(client.send(text));
  24483. std::string msg;
  24484. ASSERT_TRUE(client.read(msg));
  24485. EXPECT_EQ(text, msg);
  24486. }
  24487. client.close();
  24488. }
  24489. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24490. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24491. "/ws-close");
  24492. ASSERT_TRUE(client.connect());
  24493. // Send a message to trigger the server to close
  24494. ASSERT_TRUE(client.send("trigger close"));
  24495. // The server will close, so read should return false
  24496. std::string msg;
  24497. EXPECT_FALSE(client.read(msg));
  24498. EXPECT_FALSE(client.is_open());
  24499. }
  24500. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24501. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24502. "/ws-echo");
  24503. ASSERT_TRUE(client.connect());
  24504. // 128KB message
  24505. std::string large_data(128 * 1024, 'X');
  24506. ASSERT_TRUE(client.send(large_data));
  24507. std::string msg;
  24508. ASSERT_TRUE(client.read(msg));
  24509. EXPECT_EQ(large_data, msg);
  24510. client.close();
  24511. }
  24512. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24513. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24514. "/ws-echo");
  24515. ASSERT_TRUE(client.connect());
  24516. const int num_threads = 4;
  24517. std::vector<std::thread> threads;
  24518. std::atomic<int> send_count{0};
  24519. for (int t = 0; t < num_threads; t++) {
  24520. threads.emplace_back([&client, &send_count, t]() {
  24521. for (int i = 0; i < 5; i++) {
  24522. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24523. if (client.send(text)) { send_count++; }
  24524. }
  24525. });
  24526. }
  24527. for (auto &th : threads) {
  24528. th.join();
  24529. }
  24530. int received = 0;
  24531. std::string msg;
  24532. while (received < send_count.load()) {
  24533. if (!client.read(msg)) { break; }
  24534. received++;
  24535. }
  24536. EXPECT_EQ(send_count.load(), received);
  24537. client.close();
  24538. }
  24539. TEST_F(WebSocketIntegrationTest, ReadString) {
  24540. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24541. "/ws-echo-string");
  24542. ASSERT_TRUE(client.connect());
  24543. ASSERT_TRUE(client.send("hello"));
  24544. std::string msg;
  24545. ASSERT_TRUE(client.read(msg));
  24546. EXPECT_EQ("echo: hello", msg);
  24547. ASSERT_TRUE(client.send("world"));
  24548. ASSERT_TRUE(client.read(msg));
  24549. EXPECT_EQ("echo: world", msg);
  24550. client.close();
  24551. }
  24552. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24553. Headers headers = {{"X-Test-Header", "test-value"}};
  24554. ws::WebSocketClient client(
  24555. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24556. ASSERT_TRUE(client.connect());
  24557. std::string msg;
  24558. ASSERT_TRUE(client.read(msg));
  24559. EXPECT_EQ("path:/ws-request-info", msg);
  24560. ASSERT_TRUE(client.read(msg));
  24561. EXPECT_EQ("header:test-value", msg);
  24562. client.close();
  24563. }
  24564. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24565. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24566. "/ws-echo");
  24567. client.set_read_timeout(1, 0); // 1 second
  24568. ASSERT_TRUE(client.connect());
  24569. // Don't send anything — server echo handler waits for a message, so read()
  24570. // should time out. The connection survives it: nothing was consumed.
  24571. std::string msg;
  24572. EXPECT_EQ(client.read(msg), ws::Timeout);
  24573. EXPECT_TRUE(client.is_open());
  24574. // And it is still usable afterwards.
  24575. EXPECT_TRUE(client.send("after timeout"));
  24576. EXPECT_EQ(client.read(msg), ws::Text);
  24577. EXPECT_EQ(msg, "after timeout");
  24578. }
  24579. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24580. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24581. "/ws-echo");
  24582. client.set_read_timeout(1, 0);
  24583. ASSERT_TRUE(client.connect());
  24584. ASSERT_TRUE(client.send("first"));
  24585. std::string msg;
  24586. ASSERT_EQ(client.read(msg), ws::Text);
  24587. ASSERT_EQ(msg, "first");
  24588. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24589. // not be used with a read timeout: it would reprocess the previous message.
  24590. EXPECT_EQ(client.read(msg), ws::Timeout);
  24591. EXPECT_EQ(msg, "first");
  24592. }
  24593. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24594. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24595. "/ws-echo");
  24596. ASSERT_TRUE(client.connect());
  24597. // Setting it once the connection is open reaches the live stream, not just
  24598. // the seed for the next connect().
  24599. client.set_read_timeout(1, 0);
  24600. std::string msg;
  24601. EXPECT_EQ(client.read(msg), ws::Timeout);
  24602. EXPECT_TRUE(client.is_open());
  24603. }
  24604. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24605. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24606. "/ws-echo");
  24607. client.set_read_timeout(5, 0);
  24608. ASSERT_TRUE(client.connect());
  24609. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24610. // The server should reject it and close the connection.
  24611. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24612. client.send(oversized);
  24613. // The server's read() should have failed due to payload limit,
  24614. // so our read() should return false (connection closed).
  24615. std::string msg;
  24616. EXPECT_FALSE(client.read(msg));
  24617. }
  24618. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24619. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24620. "/ws-echo");
  24621. client.set_read_timeout(10, 0);
  24622. ASSERT_TRUE(client.connect());
  24623. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24624. // This should succeed.
  24625. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24626. ASSERT_TRUE(client.send(at_limit));
  24627. std::string msg;
  24628. ASSERT_TRUE(client.read(msg));
  24629. EXPECT_EQ(at_limit.size(), msg.size());
  24630. client.close();
  24631. }
  24632. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24633. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24634. "/nonexistent");
  24635. auto res = client.connect();
  24636. EXPECT_FALSE(res);
  24637. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24638. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24639. EXPECT_FALSE(client.is_open());
  24640. }
  24641. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24642. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24643. "/ws-echo");
  24644. ASSERT_TRUE(client.connect());
  24645. ASSERT_TRUE(client.send(""));
  24646. std::string msg;
  24647. EXPECT_EQ(ws::Text, client.read(msg));
  24648. EXPECT_EQ("", msg);
  24649. client.close();
  24650. }
  24651. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24652. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24653. "/ws-echo");
  24654. // First connection
  24655. ASSERT_TRUE(client.connect());
  24656. ASSERT_TRUE(client.send("first"));
  24657. std::string msg;
  24658. ASSERT_TRUE(client.read(msg));
  24659. EXPECT_EQ("first", msg);
  24660. client.close();
  24661. EXPECT_FALSE(client.is_open());
  24662. // Reconnect using the same client object
  24663. ASSERT_TRUE(client.connect());
  24664. ASSERT_TRUE(client.is_open());
  24665. ASSERT_TRUE(client.send("second"));
  24666. ASSERT_TRUE(client.read(msg));
  24667. EXPECT_EQ("second", msg);
  24668. client.close();
  24669. }
  24670. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24671. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24672. "/ws-close-status");
  24673. ASSERT_TRUE(client.connect());
  24674. // Trigger the server to close with GoingAway status
  24675. ASSERT_TRUE(client.send("trigger"));
  24676. // read() should return false after receiving the close frame
  24677. std::string msg;
  24678. EXPECT_FALSE(client.read(msg));
  24679. EXPECT_FALSE(client.is_open());
  24680. }
  24681. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24682. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24683. "/ws-echo");
  24684. ASSERT_TRUE(client.connect());
  24685. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24686. EXPECT_FALSE(client.is_open());
  24687. }
  24688. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24689. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24690. ws::WebSocketClient client(
  24691. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24692. ASSERT_TRUE(client.connect());
  24693. // Server should have selected graphql-ws
  24694. EXPECT_EQ("graphql-ws", client.subprotocol());
  24695. client.close();
  24696. }
  24697. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24698. Headers headers;
  24699. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24700. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24701. ws::WebSocketClient client(
  24702. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24703. ASSERT_TRUE(client.connect());
  24704. // The offer on the second field line counts too, so graphql-ws is selected
  24705. EXPECT_EQ("graphql-ws", client.subprotocol());
  24706. client.close();
  24707. }
  24708. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24709. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24710. ws::WebSocketClient client(
  24711. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24712. ASSERT_TRUE(client.connect());
  24713. // Server should not have selected any subprotocol
  24714. EXPECT_TRUE(client.subprotocol().empty());
  24715. client.close();
  24716. }
  24717. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24718. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24719. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24720. "/ws-subprotocol-unoffered",
  24721. headers);
  24722. ASSERT_TRUE(client.connect());
  24723. EXPECT_TRUE(client.subprotocol().empty());
  24724. client.close();
  24725. }
  24726. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24727. // Connect without requesting any subprotocol
  24728. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24729. "/ws-subprotocol");
  24730. ASSERT_TRUE(client.connect());
  24731. EXPECT_TRUE(client.subprotocol().empty());
  24732. client.close();
  24733. }
  24734. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24735. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24736. "/ws-echo");
  24737. client.set_tcp_nodelay(true);
  24738. client.set_connection_timeout(3, 0);
  24739. bool socket_options_called = false;
  24740. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24741. ASSERT_TRUE(client.connect());
  24742. ASSERT_TRUE(client.is_open());
  24743. EXPECT_TRUE(socket_options_called);
  24744. ASSERT_TRUE(client.send("hello"));
  24745. std::string msg;
  24746. auto result = client.read(msg);
  24747. EXPECT_EQ(result, ws::ReadResult::Text);
  24748. EXPECT_EQ(msg, "hello");
  24749. client.close();
  24750. }
  24751. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24752. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24753. "/ws-echo");
  24754. client.set_connection_timeout(std::chrono::seconds(3));
  24755. client.set_write_timeout(std::chrono::seconds(3));
  24756. // A sub-second remainder exercises the seconds/microseconds split.
  24757. client.set_read_timeout(std::chrono::milliseconds(1500));
  24758. ASSERT_TRUE(client.connect());
  24759. auto start = std::chrono::steady_clock::now();
  24760. std::string msg;
  24761. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24762. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24763. std::chrono::steady_clock::now() - start)
  24764. .count();
  24765. // Above 1s so that dropping the microseconds half of the split fails here.
  24766. // Ignoring the setter altogether would not reach this line at all: a client
  24767. // waits forever by default.
  24768. EXPECT_GE(elapsed, 1400);
  24769. EXPECT_LT(elapsed, 30000);
  24770. }
  24771. #ifndef _WIN32
  24772. // A send() that times out after part of the data went out returns the count
  24773. // written so far. Every byte of the frame must still be sent, or the peer reads
  24774. // the next frame's header and payload as the rest of this one.
  24775. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24776. signal(SIGPIPE, SIG_IGN);
  24777. const std::string large(4 * 1024 * 1024, 'A');
  24778. std::atomic<bool> large_sent{false};
  24779. std::atomic<bool> small_sent{false};
  24780. Server svr;
  24781. svr.set_write_timeout(0, 500000);
  24782. svr.set_socket_options([](socket_t sock) {
  24783. int size = 8192;
  24784. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24785. reinterpret_cast<const char *>(&size), sizeof(size));
  24786. });
  24787. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24788. large_sent = ws.send(large.data(), large.size());
  24789. small_sent = ws.send("after");
  24790. std::string msg;
  24791. while (ws.read(msg)) {}
  24792. });
  24793. auto port = svr.bind_to_any_port(HOST);
  24794. std::thread t([&]() { svr.listen_after_bind(); });
  24795. auto se = detail::scope_exit([&] {
  24796. svr.stop();
  24797. t.join();
  24798. });
  24799. svr.wait_until_ready();
  24800. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24801. std::to_string(port) + "/ws");
  24802. client.set_read_timeout(5);
  24803. client.set_socket_options([](socket_t sock) {
  24804. int size = 8192;
  24805. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24806. reinterpret_cast<const char *>(&size), sizeof(size));
  24807. });
  24808. ASSERT_TRUE(client.connect());
  24809. // Outlast the server's write timeout, then drain.
  24810. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24811. std::string msg;
  24812. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24813. EXPECT_TRUE(msg == large);
  24814. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24815. EXPECT_EQ("after", msg);
  24816. EXPECT_TRUE(large_sent);
  24817. EXPECT_TRUE(small_sent);
  24818. client.close();
  24819. }
  24820. #endif
  24821. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  24822. Server svr;
  24823. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24824. if (!req.has_header("Authorization")) {
  24825. res.status = StatusCode::Unauthorized_401;
  24826. res.set_content("Unauthorized", "text/plain");
  24827. return Server::HandlerResponse::Handled;
  24828. }
  24829. return Server::HandlerResponse::Unhandled;
  24830. });
  24831. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24832. std::string msg;
  24833. while (ws.read(msg)) {
  24834. ws.send(msg);
  24835. }
  24836. });
  24837. auto port = svr.bind_to_any_port("localhost");
  24838. std::thread t([&]() { svr.listen_after_bind(); });
  24839. svr.wait_until_ready();
  24840. // Without Authorization header - should be rejected before upgrade
  24841. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  24842. EXPECT_FALSE(client1.connect());
  24843. // The rejection is framed like any other HTTP response
  24844. {
  24845. Client cli("localhost", port);
  24846. Headers headers = {{"Upgrade", "websocket"},
  24847. {"Connection", "Upgrade"},
  24848. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24849. {"Sec-WebSocket-Version", "13"}};
  24850. auto res = cli.Get("/ws", headers);
  24851. ASSERT_TRUE(res);
  24852. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24853. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24854. EXPECT_EQ("Unauthorized", res->body);
  24855. }
  24856. // With Authorization header - should succeed
  24857. Headers headers = {{"Authorization", "Bearer token123"}};
  24858. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  24859. headers);
  24860. ASSERT_TRUE(client2.connect());
  24861. ASSERT_TRUE(client2.send("hello"));
  24862. std::string msg;
  24863. ASSERT_TRUE(client2.read(msg));
  24864. EXPECT_EQ("hello", msg);
  24865. client2.close();
  24866. svr.stop();
  24867. t.join();
  24868. }
  24869. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  24870. Server svr;
  24871. std::atomic<int> pre_routing_calls{0};
  24872. std::atomic<int> pre_request_calls{0};
  24873. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  24874. pre_routing_calls++;
  24875. if (req.path == "/handled") {
  24876. res.set_content("handled", "text/plain");
  24877. return Server::HandlerResponse::Handled;
  24878. }
  24879. return Server::HandlerResponse::Unhandled;
  24880. });
  24881. svr.set_pre_request_handler([&](const Request &, Response &) {
  24882. pre_request_calls++;
  24883. return Server::HandlerResponse::Unhandled;
  24884. });
  24885. svr.Get("/http", [](const Request &, Response &res) {
  24886. res.set_content("http", "text/plain");
  24887. });
  24888. svr.WebSocket("/ws",
  24889. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24890. auto port = svr.bind_to_any_port("localhost");
  24891. std::thread t([&]() { svr.listen_after_bind(); });
  24892. auto se = detail::scope_exit([&] {
  24893. svr.stop();
  24894. t.join();
  24895. });
  24896. svr.wait_until_ready();
  24897. Headers upgrade = {{"Upgrade", "websocket"},
  24898. {"Connection", "Upgrade"},
  24899. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24900. {"Sec-WebSocket-Version", "13"}};
  24901. auto get = [&](const char *path) {
  24902. pre_routing_calls = 0;
  24903. return Client("localhost", port).Get(path, upgrade);
  24904. };
  24905. // No WebSocket route, but an HTTP one
  24906. auto res = get("/http");
  24907. ASSERT_TRUE(res);
  24908. EXPECT_EQ(StatusCode::OK_200, res->status);
  24909. EXPECT_EQ("http", res->body);
  24910. EXPECT_EQ(1, pre_routing_calls);
  24911. EXPECT_EQ(1, pre_request_calls);
  24912. // No route at all
  24913. res = get("/none");
  24914. ASSERT_TRUE(res);
  24915. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24916. EXPECT_EQ(1, pre_routing_calls);
  24917. // Answered by the pre-routing handler
  24918. res = get("/handled");
  24919. ASSERT_TRUE(res);
  24920. EXPECT_EQ(StatusCode::OK_200, res->status);
  24921. EXPECT_EQ("handled", res->body);
  24922. EXPECT_EQ(1, pre_routing_calls);
  24923. // A WebSocket route
  24924. pre_routing_calls = 0;
  24925. pre_request_calls = 0;
  24926. {
  24927. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24928. "/ws");
  24929. ASSERT_TRUE(client.connect());
  24930. std::string msg;
  24931. ASSERT_TRUE(client.read(msg));
  24932. EXPECT_EQ("ws", msg);
  24933. client.close();
  24934. }
  24935. EXPECT_EQ(1, pre_routing_calls);
  24936. EXPECT_EQ(1, pre_request_calls);
  24937. }
  24938. // An upgrade request answered by a hook leaves its body unread, so that body
  24939. // must not be served as the next request on the connection.
  24940. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24941. Server svr;
  24942. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24943. if (req.path == "/pre-routing") {
  24944. res.set_content("pre-routing", "text/plain");
  24945. return Server::HandlerResponse::Handled;
  24946. }
  24947. return Server::HandlerResponse::Unhandled;
  24948. });
  24949. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24950. if (req.matched_route == "/pre-request") {
  24951. res.set_content("pre-request", "text/plain");
  24952. return Server::HandlerResponse::Handled;
  24953. }
  24954. return Server::HandlerResponse::Unhandled;
  24955. });
  24956. svr.Get("/smuggled", [](const Request &, Response &res) {
  24957. res.set_content("smuggled", "text/plain");
  24958. });
  24959. svr.WebSocket("/pre-request",
  24960. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24961. auto port = svr.bind_to_any_port(HOST);
  24962. std::thread t([&]() { svr.listen_after_bind(); });
  24963. auto se = detail::scope_exit([&] {
  24964. svr.stop();
  24965. t.join();
  24966. });
  24967. svr.wait_until_ready();
  24968. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24969. for (auto path : {"/pre-routing", "/pre-request"}) {
  24970. std::string req = std::string("GET ") + path +
  24971. " HTTP/1.1\r\n"
  24972. "Host: localhost\r\n"
  24973. "Upgrade: websocket\r\n"
  24974. "Connection: Upgrade\r\n"
  24975. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24976. "Sec-WebSocket-Version: 13\r\n"
  24977. "Content-Length: " +
  24978. std::to_string(body.size()) + "\r\n\r\n" + body;
  24979. std::string res;
  24980. ASSERT_TRUE(send_request(5, req, &res, port));
  24981. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24982. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24983. // Only one response, and the body was not served as a request
  24984. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24985. }
  24986. }
  24987. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24988. Server svr;
  24989. std::atomic<int> pre_request_calls{0};
  24990. std::atomic<bool> route_matched{false};
  24991. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24992. pre_request_calls++;
  24993. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24994. if (req.get_header_value("Authorization") != "Bearer token123") {
  24995. res.status = StatusCode::Unauthorized_401;
  24996. res.set_content("Unauthorized", "text/plain");
  24997. return Server::HandlerResponse::Handled;
  24998. }
  24999. return Server::HandlerResponse::Unhandled;
  25000. });
  25001. std::atomic<bool> handler_called{false};
  25002. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25003. handler_called = true;
  25004. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25005. });
  25006. auto port = svr.bind_to_any_port("localhost");
  25007. std::thread t([&]() { svr.listen_after_bind(); });
  25008. svr.wait_until_ready();
  25009. // Without Authorization header - should be rejected before upgrade
  25010. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25011. "/ws/1");
  25012. EXPECT_FALSE(client1.connect());
  25013. EXPECT_FALSE(handler_called);
  25014. EXPECT_EQ(1, pre_request_calls);
  25015. EXPECT_TRUE(route_matched);
  25016. // The rejection is an ordinary HTTP response, not a protocol switch
  25017. {
  25018. Client cli("localhost", port);
  25019. Headers headers = {{"Upgrade", "websocket"},
  25020. {"Connection", "Upgrade"},
  25021. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25022. {"Sec-WebSocket-Version", "13"}};
  25023. auto res = cli.Get("/ws/1", headers);
  25024. ASSERT_TRUE(res);
  25025. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25026. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25027. EXPECT_EQ("Unauthorized", res->body);
  25028. }
  25029. EXPECT_FALSE(handler_called);
  25030. // With Authorization header - should succeed
  25031. Headers headers = {{"Authorization", "Bearer token123"}};
  25032. ws::WebSocketClient client2(
  25033. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25034. ASSERT_TRUE(client2.connect());
  25035. std::string msg;
  25036. ASSERT_TRUE(client2.read(msg));
  25037. EXPECT_EQ("/ws/:id 2", msg);
  25038. EXPECT_TRUE(handler_called);
  25039. client2.close();
  25040. svr.stop();
  25041. t.join();
  25042. }
  25043. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25044. static Headers websocket_upgrade_headers() {
  25045. return {{"Upgrade", "websocket"},
  25046. {"Connection", "Upgrade"},
  25047. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25048. {"Sec-WebSocket-Version", "13"},
  25049. {"Sec-WebSocket-Protocol", "chat"}};
  25050. }
  25051. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25052. Server svr;
  25053. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25054. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25055. return Server::HandlerResponse::Unhandled;
  25056. });
  25057. svr.set_pre_request_handler([](const Request &req, Response &) {
  25058. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25059. return Server::HandlerResponse::Unhandled;
  25060. });
  25061. svr.set_exception_handler(
  25062. [](const Request &, Response &res, std::exception_ptr ep) {
  25063. try {
  25064. std::rethrow_exception(ep);
  25065. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25066. });
  25067. auto handler = [](const Request &, ws::WebSocket &) {};
  25068. svr.WebSocket("/pre-routing", handler);
  25069. svr.WebSocket("/pre-request", handler);
  25070. svr.WebSocket("/sub-protocol", handler,
  25071. [](const std::vector<std::string> &) -> std::string {
  25072. throw std::runtime_error("/sub-protocol");
  25073. });
  25074. auto port = svr.bind_to_any_port(HOST);
  25075. ASSERT_GT(port, 0);
  25076. thread t = thread([&] { svr.listen_after_bind(); });
  25077. auto se = detail::scope_exit([&] {
  25078. svr.stop();
  25079. t.join();
  25080. ASSERT_FALSE(svr.is_running());
  25081. });
  25082. svr.wait_until_ready();
  25083. Client cli(HOST, port);
  25084. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25085. auto res = cli.Get(path, websocket_upgrade_headers());
  25086. if (!res) {
  25087. ADD_FAILURE() << path << ": " << to_string(res.error());
  25088. continue;
  25089. }
  25090. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25091. EXPECT_EQ(path, res->body);
  25092. }
  25093. }
  25094. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25095. Server svr;
  25096. svr.set_pre_routing_handler(
  25097. [](const Request &, Response &) -> Server::HandlerResponse {
  25098. throw std::runtime_error("pre-routing");
  25099. });
  25100. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25101. auto port = svr.bind_to_any_port(HOST);
  25102. ASSERT_GT(port, 0);
  25103. thread t = thread([&] { svr.listen_after_bind(); });
  25104. auto se = detail::scope_exit([&] {
  25105. svr.stop();
  25106. t.join();
  25107. ASSERT_FALSE(svr.is_running());
  25108. });
  25109. svr.wait_until_ready();
  25110. Client cli(HOST, port);
  25111. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25112. ASSERT_TRUE(res) << to_string(res.error());
  25113. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25114. }
  25115. #endif
  25116. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25117. Server svr;
  25118. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25119. // A read timeout is how a handler gets control back. Without it, a handler
  25120. // parked in read() can never write on the connection it is reading.
  25121. ws.set_read_timeout(std::chrono::milliseconds(100));
  25122. std::string msg;
  25123. while (ws.is_open()) {
  25124. auto r = ws.read(msg);
  25125. if (r == httplib::ws::Timeout) {
  25126. ws.send("tick");
  25127. continue;
  25128. }
  25129. if (r == httplib::ws::Fail) { break; }
  25130. ws.send(msg);
  25131. }
  25132. });
  25133. auto port = svr.bind_to_any_port("localhost");
  25134. std::thread t([&]() { svr.listen_after_bind(); });
  25135. svr.wait_until_ready();
  25136. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25137. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25138. ASSERT_TRUE(client.connect());
  25139. // The client sends nothing, so anything it receives came out of the
  25140. // handler's timeout path.
  25141. std::string msg;
  25142. ASSERT_EQ(client.read(msg), ws::Text);
  25143. EXPECT_EQ("tick", msg);
  25144. client.close();
  25145. svr.stop();
  25146. t.join();
  25147. }
  25148. // Stream::read may return fewer bytes than asked for. This is that contract at
  25149. // its worst -- one byte per call -- which is what a frame header straddling a
  25150. // read buffer's boundary looks like to the frame parser.
  25151. class WsByteAtATimeStream : public Stream {
  25152. public:
  25153. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25154. bool is_readable() const override { return true; }
  25155. bool wait_readable() const override { return true; }
  25156. bool wait_writable() const override { return true; }
  25157. ssize_t read(char *ptr, size_t size) override {
  25158. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25159. *ptr = data_[pos_++];
  25160. return 1;
  25161. }
  25162. ssize_t write(const char *, size_t size) override {
  25163. return static_cast<ssize_t>(size);
  25164. }
  25165. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25166. ip = "127.0.0.1";
  25167. port = 0;
  25168. }
  25169. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25170. ip = "127.0.0.1";
  25171. port = 0;
  25172. }
  25173. socket_t socket() const override { return INVALID_SOCKET; }
  25174. time_t duration() const override { return 0; }
  25175. private:
  25176. std::string data_;
  25177. size_t pos_ = 0;
  25178. };
  25179. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25180. // The payload uses the 16-bit extended length, so the header, the length
  25181. // and the mask key are all multi-byte fields here. Each used to be read
  25182. // with a single read() call, which fails as soon as one is split. The
  25183. // payload is also a little over one read chunk, so it is read in two.
  25184. std::string body;
  25185. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25186. body += static_cast<char>(i % 251);
  25187. }
  25188. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25189. std::string frame;
  25190. frame += static_cast<char>(0x81); // FIN + Text
  25191. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25192. frame += static_cast<char>(body.size() >> 8);
  25193. frame += static_cast<char>(body.size() & 0xff);
  25194. for (size_t i = 0; i < 4; i++) {
  25195. frame += static_cast<char>(mask[i]);
  25196. }
  25197. for (size_t i = 0; i < body.size(); i++) {
  25198. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25199. }
  25200. WsByteAtATimeStream strm(frame);
  25201. ws::Opcode opcode;
  25202. std::string payload;
  25203. bool fin = false;
  25204. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25205. /*expect_masked=*/true, body.size()),
  25206. ws::impl::FrameRead::Ok);
  25207. EXPECT_TRUE(fin);
  25208. EXPECT_EQ(opcode, ws::Opcode::Text);
  25209. EXPECT_EQ(payload, body);
  25210. }
  25211. // Keeps what is written, counting the writes, and reads it back.
  25212. class WsWriteCountingStream : public Stream {
  25213. public:
  25214. bool is_readable() const override { return true; }
  25215. bool wait_readable() const override { return true; }
  25216. bool wait_writable() const override { return true; }
  25217. ssize_t read(char *ptr, size_t size) override {
  25218. auto n = (std::min)(size, data_.size() - pos_);
  25219. if (n == 0) { return 0; }
  25220. memcpy(ptr, data_.data() + pos_, n);
  25221. pos_ += n;
  25222. return static_cast<ssize_t>(n);
  25223. }
  25224. ssize_t write(const char *ptr, size_t size) override {
  25225. writes++;
  25226. data_.append(ptr, size);
  25227. return static_cast<ssize_t>(size);
  25228. }
  25229. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25230. ip = "127.0.0.1";
  25231. port = 0;
  25232. }
  25233. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25234. ip = "127.0.0.1";
  25235. port = 0;
  25236. }
  25237. socket_t socket() const override { return INVALID_SOCKET; }
  25238. time_t duration() const override { return 0; }
  25239. int writes = 0;
  25240. private:
  25241. std::string data_;
  25242. size_t pos_ = 0;
  25243. };
  25244. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25245. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25246. // masked and not, reads back as written; a payload over one chunk follows
  25247. // its first in more writes.
  25248. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25249. for (auto mask : {false, true}) {
  25250. std::string body(len, '\0');
  25251. for (size_t i = 0; i < len; i++) {
  25252. body[i] = static_cast<char>(i % 251);
  25253. }
  25254. WsWriteCountingStream strm;
  25255. ASSERT_TRUE(detail::write_websocket_frame(
  25256. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25257. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25258. ws::Opcode opcode;
  25259. std::string payload;
  25260. bool fin = false;
  25261. ASSERT_EQ(
  25262. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25263. ws::impl::FrameRead::Ok)
  25264. << len << " " << mask;
  25265. EXPECT_TRUE(fin);
  25266. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25267. EXPECT_EQ(body, payload) << len << " " << mask;
  25268. }
  25269. }
  25270. }
  25271. // Hands out its pieces one read at a time, timing out between each two.
  25272. class WsTimeoutBetweenPiecesStream : public Stream {
  25273. public:
  25274. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25275. : pieces_(std::move(pieces)) {}
  25276. bool is_readable() const override { return true; }
  25277. bool wait_readable() const override { return true; }
  25278. bool wait_writable() const override { return true; }
  25279. ssize_t read(char *ptr, size_t size) override {
  25280. if (time_out_) {
  25281. time_out_ = false;
  25282. error_ = Error::Timeout;
  25283. return -1;
  25284. }
  25285. if (i_ >= pieces_.size()) {
  25286. error_ = Error::ConnectionClosed;
  25287. return 0;
  25288. }
  25289. auto &piece = pieces_[i_];
  25290. auto n = (std::min)(size, piece.size() - at_);
  25291. memcpy(ptr, piece.data() + at_, n);
  25292. at_ += n;
  25293. if (at_ == piece.size()) {
  25294. i_++;
  25295. at_ = 0;
  25296. time_out_ = true;
  25297. }
  25298. return static_cast<ssize_t>(n);
  25299. }
  25300. ssize_t write(const char *, size_t size) override {
  25301. return static_cast<ssize_t>(size);
  25302. }
  25303. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25304. ip = "127.0.0.1";
  25305. port = 0;
  25306. }
  25307. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25308. ip = "127.0.0.1";
  25309. port = 0;
  25310. }
  25311. socket_t socket() const override { return INVALID_SOCKET; }
  25312. time_t duration() const override { return 0; }
  25313. private:
  25314. std::vector<std::string> pieces_;
  25315. size_t i_ = 0;
  25316. size_t at_ = 0;
  25317. bool time_out_ = false;
  25318. };
  25319. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25320. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25321. std::string frame = "\x81\x85";
  25322. frame.append(4, '\0');
  25323. frame += "Hello";
  25324. // The header's first byte, then its second with half the mask key, then
  25325. // the rest
  25326. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25327. frame.substr(4)};
  25328. WsTimeoutBetweenPiecesStream strm(pieces);
  25329. ws::impl::FrameReader reader;
  25330. ws::Opcode opcode;
  25331. std::string payload;
  25332. bool fin = false;
  25333. for (int i = 0; i < 2; i++) {
  25334. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25335. reader.read(strm, opcode, payload, fin, true, 0));
  25336. EXPECT_TRUE(reader.begun());
  25337. }
  25338. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25339. reader.read(strm, opcode, payload, fin, true, 0));
  25340. EXPECT_FALSE(reader.begun());
  25341. EXPECT_TRUE(fin);
  25342. EXPECT_EQ(ws::Opcode::Text, opcode);
  25343. EXPECT_EQ("Hello", payload);
  25344. // Read in one go, the frame cannot be gone on with after a timeout
  25345. WsTimeoutBetweenPiecesStream again(pieces);
  25346. EXPECT_EQ(
  25347. ws::impl::FrameRead::Fail,
  25348. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25349. }
  25350. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25351. std::string body(2000, 'x');
  25352. std::string frame;
  25353. frame += static_cast<char>(0x82); // FIN + Binary
  25354. frame += static_cast<char>(126); // 16-bit length follows
  25355. frame += static_cast<char>(body.size() >> 8);
  25356. frame += static_cast<char>(body.size() & 0xff);
  25357. frame += body;
  25358. detail::BufferStream strm;
  25359. strm.write(frame.data(), frame.size());
  25360. ws::Opcode opcode;
  25361. std::string payload;
  25362. bool fin;
  25363. EXPECT_EQ(
  25364. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25365. ws::impl::FrameRead::Ok);
  25366. EXPECT_EQ(body, payload);
  25367. }
  25368. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25369. // The header announces the largest payload allowed, and only 3 bytes of it
  25370. // ever arrive.
  25371. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25372. std::string frame;
  25373. frame += static_cast<char>(0x82); // FIN + Binary
  25374. frame += static_cast<char>(127); // 64-bit length follows
  25375. for (int shift = 56; shift >= 0; shift -= 8) {
  25376. frame += static_cast<char>((len >> shift) & 0xff);
  25377. }
  25378. frame += "abc";
  25379. detail::BufferStream strm;
  25380. strm.write(frame.data(), frame.size());
  25381. ws::Opcode opcode;
  25382. std::string payload;
  25383. bool fin;
  25384. EXPECT_EQ(
  25385. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25386. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25387. ws::impl::FrameRead::Fail);
  25388. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25389. }
  25390. TEST(WebSocketTest, QueryStringInHandshake) {
  25391. Server svr;
  25392. std::mutex mtx;
  25393. std::string received_target;
  25394. std::string received_token;
  25395. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25396. {
  25397. std::lock_guard<std::mutex> lock(mtx);
  25398. received_target = req.target;
  25399. if (req.has_param("token")) {
  25400. received_token = req.get_param_value("token");
  25401. }
  25402. }
  25403. std::string msg;
  25404. while (ws.read(msg)) {
  25405. ws.send(msg);
  25406. }
  25407. });
  25408. auto port = svr.bind_to_any_port("localhost");
  25409. std::thread t([&]() { svr.listen_after_bind(); });
  25410. svr.wait_until_ready();
  25411. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25412. "/ws?token=ABC&session=123");
  25413. ASSERT_TRUE(client.connect());
  25414. // Round-trip ensures the handler has run and captured the request.
  25415. ASSERT_TRUE(client.send("hello"));
  25416. std::string msg;
  25417. ASSERT_TRUE(client.read(msg));
  25418. EXPECT_EQ("hello", msg);
  25419. client.close();
  25420. {
  25421. std::lock_guard<std::mutex> lock(mtx);
  25422. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25423. EXPECT_EQ("ABC", received_token);
  25424. }
  25425. svr.stop();
  25426. t.join();
  25427. }
  25428. // Run a handshake against a throwaway server and hand the request the server
  25429. // received back to the caller, so tests can assert on the headers the client
  25430. // actually put on the wire.
  25431. static void capture_websocket_handshake_request(
  25432. const Headers &client_headers,
  25433. std::function<void(const Request &, int port)> verify) {
  25434. Server svr;
  25435. std::mutex mtx;
  25436. Request received;
  25437. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25438. {
  25439. std::lock_guard<std::mutex> lock(mtx);
  25440. received = req;
  25441. }
  25442. std::string msg;
  25443. while (ws.read(msg)) {
  25444. ws.send(msg);
  25445. }
  25446. });
  25447. auto port = svr.bind_to_any_port("localhost");
  25448. std::thread t([&]() { svr.listen_after_bind(); });
  25449. auto se = detail::scope_exit([&] {
  25450. svr.stop();
  25451. t.join();
  25452. });
  25453. svr.wait_until_ready();
  25454. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25455. client_headers);
  25456. ASSERT_TRUE(client.connect());
  25457. ASSERT_TRUE(client.send("hello"));
  25458. std::string msg;
  25459. ASSERT_TRUE(client.read(msg));
  25460. client.close();
  25461. {
  25462. std::lock_guard<std::mutex> lock(mtx);
  25463. verify(received, port);
  25464. }
  25465. }
  25466. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25467. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25468. // Non-default port must be present in the Host header. Default ports
  25469. // (80/443) are omitted; that logic is covered by
  25470. // MakeHostAndPortStringTest.
  25471. EXPECT_EQ("localhost:" + std::to_string(port),
  25472. req.get_header_value("Host"));
  25473. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25474. req.get_header_value("User-Agent"));
  25475. EXPECT_FALSE(req.has_header("Accept"));
  25476. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25477. EXPECT_FALSE(req.has_header("Content-Length"));
  25478. });
  25479. }
  25480. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25481. capture_websocket_handshake_request(
  25482. {{"Host", "example.com"},
  25483. {"User-Agent", "custom-agent"},
  25484. {"X-Custom", "value"}},
  25485. [](const Request &req, int) {
  25486. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25487. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25488. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25489. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25490. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25491. });
  25492. }
  25493. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25494. capture_websocket_handshake_request(
  25495. {{"Upgrade", "bogus"},
  25496. {"Connection", "close"},
  25497. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25498. {"Sec-WebSocket-Version", "8"}},
  25499. [](const Request &req, int) {
  25500. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25501. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25502. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25503. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25504. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25505. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25506. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25507. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25508. req.get_header_value("Sec-WebSocket-Key"));
  25509. });
  25510. }
  25511. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25512. // A header the client refuses to send must abort the handshake before any
  25513. // part of it reaches the wire; a lone request line would otherwise sit in
  25514. // the peer's buffer as a truncated request.
  25515. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25516. ASSERT_NE(INVALID_SOCKET, srv);
  25517. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25518. sockaddr_in addr{};
  25519. addr.sin_family = AF_INET;
  25520. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25521. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25522. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25523. ASSERT_EQ(0, ::listen(srv, 1));
  25524. sockaddr_in bound{};
  25525. socklen_t bound_len = sizeof(bound);
  25526. ASSERT_EQ(
  25527. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25528. auto port = ntohs(bound.sin_port);
  25529. ssize_t received = -1;
  25530. std::thread t([&] {
  25531. // Bound every blocking call so a regression fails the test with a bad
  25532. // value instead of hanging the suite.
  25533. fd_set rfds;
  25534. FD_ZERO(&rfds);
  25535. FD_SET(srv, &rfds);
  25536. timeval tv{5, 0};
  25537. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25538. 0) {
  25539. return;
  25540. }
  25541. sockaddr_in cli_addr{};
  25542. socklen_t cli_len = sizeof(cli_addr);
  25543. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25544. if (cli == INVALID_SOCKET) { return; }
  25545. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25546. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25547. char buf[4096];
  25548. received = ::recv(cli, buf, sizeof(buf), 0);
  25549. });
  25550. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25551. // connect() has already shut the socket down by the time it returns false,
  25552. // so the peer sees EOF without waiting for the client to be destroyed.
  25553. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25554. {{"X-Bad", "a\r\nInjected: 1"}});
  25555. EXPECT_FALSE(client.connect());
  25556. t.join();
  25557. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25558. EXPECT_EQ(0, received);
  25559. }
  25560. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25561. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25562. // contains "upgrade" as a substring is a different token and must not
  25563. // start a WebSocket handshake.
  25564. auto make_request = [](const std::vector<std::string> &connection_values) {
  25565. Request req;
  25566. req.method = "GET";
  25567. req.headers.emplace("Upgrade", "websocket");
  25568. for (const auto &value : connection_values) {
  25569. req.headers.emplace("Connection", value);
  25570. }
  25571. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25572. req.headers.emplace("Sec-WebSocket-Version", "13");
  25573. return req;
  25574. };
  25575. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25576. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25577. EXPECT_TRUE(
  25578. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25579. EXPECT_TRUE(
  25580. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25581. EXPECT_TRUE(
  25582. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25583. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25584. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25585. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25586. EXPECT_FALSE(
  25587. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25588. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25589. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25590. }
  25591. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25592. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25593. // asks recipients to match each protocol-name case-insensitively, and RFC
  25594. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25595. // client naming websocket alongside another protocol, or on a second field
  25596. // line, is offering websocket; a value that merely contains "websocket" as a
  25597. // substring is a different protocol name and is not.
  25598. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25599. Request req;
  25600. req.method = "GET";
  25601. for (const auto &value : upgrade_values) {
  25602. req.headers.emplace("Upgrade", value);
  25603. }
  25604. req.headers.emplace("Connection", "Upgrade");
  25605. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25606. req.headers.emplace("Sec-WebSocket-Version", "13");
  25607. return req;
  25608. };
  25609. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25610. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25611. EXPECT_TRUE(
  25612. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25613. EXPECT_TRUE(
  25614. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25615. EXPECT_TRUE(
  25616. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25617. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25618. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25619. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25620. EXPECT_FALSE(
  25621. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25622. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25623. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25624. }
  25625. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25626. Server svr;
  25627. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25628. auto port = svr.bind_to_any_port("localhost");
  25629. std::thread t([&]() { svr.listen_after_bind(); });
  25630. auto se = detail::scope_exit([&] {
  25631. svr.stop();
  25632. t.join();
  25633. });
  25634. svr.wait_until_ready();
  25635. Headers headers = {{"Upgrade", "websocket"},
  25636. {"Connection", "notupgrade"},
  25637. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25638. {"Sec-WebSocket-Version", "13"}};
  25639. Client cli("localhost", port);
  25640. auto res = cli.Get("/ws", headers);
  25641. // The route exists only as a WebSocket route, so a request that fails the
  25642. // handshake check falls through to ordinary routing.
  25643. ASSERT_TRUE(res);
  25644. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25645. }
  25646. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25647. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25648. // Connection value is the only thing left for the client to reject.
  25649. Server svr;
  25650. svr.Get("/ws", [](const Request &req, Response &res) {
  25651. res.status = StatusCode::SwitchingProtocol_101;
  25652. res.set_header("Upgrade", "websocket");
  25653. res.set_header("Connection", "notupgrade");
  25654. res.set_header("Sec-WebSocket-Accept",
  25655. detail::websocket_accept_key(
  25656. req.get_header_value("Sec-WebSocket-Key")));
  25657. });
  25658. auto port = svr.bind_to_any_port("localhost");
  25659. std::thread t([&]() { svr.listen_after_bind(); });
  25660. auto se = detail::scope_exit([&] {
  25661. svr.stop();
  25662. t.join();
  25663. });
  25664. svr.wait_until_ready();
  25665. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25666. auto res = client.connect();
  25667. EXPECT_FALSE(res);
  25668. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25669. EXPECT_FALSE(client.is_open());
  25670. }
  25671. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25672. Server svr;
  25673. svr.Get("/ws", [](const Request &req, Response &res) {
  25674. res.status = StatusCode::SwitchingProtocol_101;
  25675. res.set_header("Upgrade", "websocket");
  25676. res.set_header("Connection", "Upgrade");
  25677. res.set_header("Sec-WebSocket-Accept",
  25678. detail::websocket_accept_key(
  25679. req.get_header_value("Sec-WebSocket-Key")));
  25680. res.set_header("Sec-WebSocket-Protocol", "admin");
  25681. });
  25682. auto port = svr.bind_to_any_port("localhost");
  25683. std::thread t([&]() { svr.listen_after_bind(); });
  25684. auto se = detail::scope_exit([&] {
  25685. svr.stop();
  25686. t.join();
  25687. });
  25688. svr.wait_until_ready();
  25689. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25690. // Server selects a subprotocol the client never offered
  25691. {
  25692. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25693. ws::WebSocketClient client(url, headers);
  25694. auto res = client.connect();
  25695. EXPECT_FALSE(res);
  25696. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25697. EXPECT_FALSE(client.is_open());
  25698. EXPECT_TRUE(client.subprotocol().empty());
  25699. }
  25700. // Client offered none but the server named one anyway
  25701. {
  25702. ws::WebSocketClient client(url);
  25703. auto res = client.connect();
  25704. EXPECT_FALSE(res);
  25705. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25706. EXPECT_FALSE(client.is_open());
  25707. EXPECT_TRUE(client.subprotocol().empty());
  25708. }
  25709. }
  25710. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25711. // The socket path doubles as the URL host, so it must not contain '/'.
  25712. const char *shard = getenv("GTEST_SHARD_INDEX");
  25713. const std::string sock_path =
  25714. shard ? std::string("httplib-ws-") + shard + ".sock"
  25715. : std::string("httplib-ws.sock");
  25716. std::remove(sock_path.c_str());
  25717. Server svr;
  25718. std::mutex mtx;
  25719. std::string received_host;
  25720. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25721. {
  25722. std::lock_guard<std::mutex> lock(mtx);
  25723. received_host = req.get_header_value("Host");
  25724. }
  25725. std::string msg;
  25726. while (ws.read(msg)) {
  25727. ws.send(msg);
  25728. }
  25729. });
  25730. svr.set_address_family(AF_UNIX);
  25731. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25732. auto se = detail::scope_exit([&] {
  25733. svr.stop();
  25734. t.join();
  25735. std::remove(sock_path.c_str());
  25736. });
  25737. svr.wait_until_ready();
  25738. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25739. client.set_address_family(AF_UNIX);
  25740. ASSERT_TRUE(client.connect());
  25741. ASSERT_TRUE(client.send("hello"));
  25742. std::string msg;
  25743. ASSERT_TRUE(client.read(msg));
  25744. client.close();
  25745. {
  25746. std::lock_guard<std::mutex> lock(mtx);
  25747. // There is no host:port for a Unix socket, so the same "localhost"
  25748. // placeholder the HTTP client uses is expected.
  25749. EXPECT_EQ("localhost", received_host);
  25750. }
  25751. }
  25752. // Two threads must never parse WebSocket frames from the same stream.
  25753. // close() used to read the peer's Close reply with its own frame read, so it
  25754. // raced a reader thread that was in the middle of a payload: the payload loop
  25755. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25756. // so bytes taken by close() were replaced with bytes from further along the
  25757. // stream. The message kept its length and silently changed content.
  25758. //
  25759. // The raw peer below sends a frame header plus part of the payload, waits for
  25760. // the handler to call close(), and only then sends the rest. Whichever thread
  25761. // would win the race for those bytes, the message must arrive intact, because
  25762. // close() must not touch the stream while read() owns it.
  25763. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25764. #ifndef _WIN32
  25765. signal(SIGPIPE, SIG_IGN);
  25766. #endif
  25767. const size_t payload_len = 120; // fits the 7-bit length field
  25768. const size_t prefix_len = 8;
  25769. const int attempts = 8;
  25770. std::string expected(payload_len, '\0');
  25771. for (size_t i = 0; i < payload_len; i++) {
  25772. expected[i] = static_cast<char>('a' + i % 26);
  25773. }
  25774. std::atomic<bool> peer_stalled{false};
  25775. std::atomic<bool> handler_done{false};
  25776. std::mutex received_mutex;
  25777. std::vector<std::string> received;
  25778. // Bound every wait, so a regression fails the test instead of hanging the
  25779. // suite.
  25780. auto wait_for = [](const std::atomic<bool> &flag) {
  25781. for (int i = 0; i < 500 && !flag; i++) {
  25782. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25783. }
  25784. };
  25785. Server svr;
  25786. svr.set_websocket_ping_interval(0);
  25787. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25788. std::thread reader([&]() {
  25789. std::string msg;
  25790. while (ws.read(msg)) {
  25791. std::lock_guard<std::mutex> guard(received_mutex);
  25792. received.push_back(msg);
  25793. }
  25794. });
  25795. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25796. // inside a frame when close() runs.
  25797. wait_for(peer_stalled);
  25798. ws.close();
  25799. reader.join();
  25800. handler_done = true;
  25801. });
  25802. auto port = svr.bind_to_any_port("127.0.0.1");
  25803. std::thread t([&]() { svr.listen_after_bind(); });
  25804. auto se = detail::scope_exit([&] {
  25805. svr.stop();
  25806. t.join();
  25807. });
  25808. svr.wait_until_ready();
  25809. auto send_bytes = [](socket_t s, const std::string &data) {
  25810. #ifdef _WIN32
  25811. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  25812. #else
  25813. auto n = ::send(s, data.data(), data.size(), 0);
  25814. #endif
  25815. return n == static_cast<decltype(n)>(data.size());
  25816. };
  25817. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  25818. // Every length used here fits the 7-bit length field.
  25819. auto masked_header = [](uint8_t first_byte, size_t len) {
  25820. std::string h;
  25821. h += static_cast<char>(first_byte);
  25822. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  25823. h.append(4, '\0'); // mask key
  25824. return h;
  25825. };
  25826. for (int attempt = 0; attempt < attempts; attempt++) {
  25827. peer_stalled = false;
  25828. handler_done = false;
  25829. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25830. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  25831. auto se_sock = detail::scope_exit([&] {
  25832. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  25833. });
  25834. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25835. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  25836. sockaddr_in addr{};
  25837. addr.sin_family = AF_INET;
  25838. addr.sin_port = htons(static_cast<uint16_t>(port));
  25839. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25840. ASSERT_EQ(
  25841. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  25842. << "attempt " << attempt;
  25843. ASSERT_TRUE(send_bytes(sock,
  25844. "GET /ws HTTP/1.1\r\n"
  25845. "Host: 127.0.0.1\r\n"
  25846. "Upgrade: websocket\r\n"
  25847. "Connection: Upgrade\r\n"
  25848. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25849. "Sec-WebSocket-Version: 13\r\n"
  25850. "\r\n"))
  25851. << "attempt " << attempt;
  25852. std::string response;
  25853. while (response.find("\r\n\r\n") == std::string::npos) {
  25854. char buf[512];
  25855. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  25856. if (n <= 0) { break; }
  25857. response.append(buf, static_cast<size_t>(n));
  25858. }
  25859. ASSERT_NE(std::string::npos, response.find(" 101 "))
  25860. << "attempt " << attempt;
  25861. // Send the header of a Binary message but only the first prefix_len bytes
  25862. // of its payload, leaving the reader thread stalled inside the payload.
  25863. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  25864. expected.substr(0, prefix_len)))
  25865. << "attempt " << attempt;
  25866. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25867. peer_stalled = true;
  25868. // Let close() send its Close frame and park in its own read before the
  25869. // rest of the payload arrives, so both threads are waiting for it.
  25870. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25871. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  25872. close_frame += static_cast<char>(0x03); // status 1000
  25873. close_frame += static_cast<char>(0xE8);
  25874. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  25875. << "attempt " << attempt;
  25876. // Closing the peer releases the reader thread even on the buggy path,
  25877. // where it waits for bytes another thread already consumed.
  25878. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  25879. detail::close_socket(sock);
  25880. sock = INVALID_SOCKET;
  25881. wait_for(handler_done);
  25882. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  25883. }
  25884. std::lock_guard<std::mutex> guard(received_mutex);
  25885. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  25886. << "a message in flight when close() ran was dropped";
  25887. for (size_t i = 0; i < received.size(); i++) {
  25888. EXPECT_EQ(expected, received[i]) << "message " << i;
  25889. }
  25890. }
  25891. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  25892. // returning the socket, or INVALID_SOCKET.
  25893. static socket_t connect_raw_websocket(int port, const std::string &path) {
  25894. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  25895. if (sock == INVALID_SOCKET) { return sock; }
  25896. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25897. sockaddr_in addr{};
  25898. addr.sin_family = AF_INET;
  25899. addr.sin_port = htons(static_cast<uint16_t>(port));
  25900. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25901. std::string req = "GET " + path +
  25902. " HTTP/1.1\r\n"
  25903. "Host: 127.0.0.1\r\n"
  25904. "Upgrade: websocket\r\n"
  25905. "Connection: Upgrade\r\n"
  25906. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  25907. "Sec-WebSocket-Version: 13\r\n"
  25908. "\r\n";
  25909. std::string res;
  25910. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  25911. detail::send_socket(sock, req.data(), req.size(), 0) ==
  25912. static_cast<ssize_t>(req.size())) {
  25913. char c;
  25914. while (res.find("\r\n\r\n") == std::string::npos &&
  25915. ::recv(sock, &c, 1, 0) == 1) {
  25916. res += c;
  25917. }
  25918. }
  25919. if (res.find(" 101 ") == std::string::npos) {
  25920. detail::close_socket(sock);
  25921. return INVALID_SOCKET;
  25922. }
  25923. return sock;
  25924. }
  25925. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  25926. // The payload must fit the 7-bit length field.
  25927. static std::string masked_frame(uint8_t first_byte,
  25928. const std::string &payload) {
  25929. std::string f;
  25930. f += static_cast<char>(first_byte);
  25931. f += static_cast<char>(0x80 | payload.size());
  25932. f.append(4, '\0');
  25933. return f + payload;
  25934. }
  25935. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  25936. std::atomic<bool> done{false};
  25937. std::string received;
  25938. Server svr;
  25939. svr.set_websocket_ping_interval(0);
  25940. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25941. std::string msg;
  25942. if (ws.read(msg) == ws::Binary) { received = msg; }
  25943. done = true;
  25944. });
  25945. auto port = svr.bind_to_any_port("127.0.0.1");
  25946. std::thread t([&]() { svr.listen_after_bind(); });
  25947. auto se = detail::scope_exit([&] {
  25948. svr.stop();
  25949. t.join();
  25950. });
  25951. svr.wait_until_ready();
  25952. auto sock = connect_raw_websocket(port, "/ws");
  25953. ASSERT_NE(INVALID_SOCKET, sock);
  25954. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25955. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  25956. masked_frame(0x89, "p") + // FIN + Ping
  25957. masked_frame(0x80, "lo"); // FIN + Continuation
  25958. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25959. for (int i = 0; i < 500 && !done; i++) {
  25960. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25961. }
  25962. ASSERT_TRUE(done);
  25963. EXPECT_EQ("Hello", received);
  25964. // The Ping between the fragments is answered with a Pong.
  25965. char pong[3];
  25966. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  25967. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  25968. }
  25969. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  25970. #ifndef _WIN32
  25971. signal(SIGPIPE, SIG_IGN);
  25972. #endif
  25973. std::atomic<bool> read_ended{false};
  25974. std::atomic<bool> sending{true};
  25975. Server svr;
  25976. svr.set_websocket_ping_interval(0);
  25977. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25978. std::thread reader([&]() {
  25979. std::string msg;
  25980. while (ws.read(msg)) {}
  25981. read_ended = true;
  25982. });
  25983. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  25984. ws.close();
  25985. reader.join();
  25986. });
  25987. auto port = svr.bind_to_any_port("127.0.0.1");
  25988. std::thread t([&]() { svr.listen_after_bind(); });
  25989. auto se = detail::scope_exit([&] {
  25990. svr.stop();
  25991. t.join();
  25992. });
  25993. svr.wait_until_ready();
  25994. auto sock = connect_raw_websocket(port, "/ws");
  25995. ASSERT_NE(INVALID_SOCKET, sock);
  25996. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  25997. // A Text message whose empty continuation frames never end
  25998. std::thread sender([&]() {
  25999. auto data = masked_frame(0x01, "");
  26000. while (sending) {
  26001. data += masked_frame(0x00, "");
  26002. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26003. return;
  26004. }
  26005. data.clear();
  26006. }
  26007. });
  26008. for (int i = 0; i < 300 && !read_ended; i++) {
  26009. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26010. }
  26011. sending = false;
  26012. sender.join();
  26013. EXPECT_TRUE(read_ended);
  26014. }
  26015. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26016. Server svr;
  26017. svr.set_websocket_ping_interval(-1);
  26018. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26019. std::string msg;
  26020. while (ws.read(msg)) {}
  26021. });
  26022. auto port = svr.bind_to_any_port("127.0.0.1");
  26023. std::thread t([&]() { svr.listen_after_bind(); });
  26024. auto se = detail::scope_exit([&] {
  26025. svr.stop();
  26026. t.join();
  26027. });
  26028. svr.wait_until_ready();
  26029. auto sock = connect_raw_websocket(port, "/ws");
  26030. ASSERT_NE(INVALID_SOCKET, sock);
  26031. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26032. // Nothing comes while the client stays quiet.
  26033. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26034. char c;
  26035. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26036. }
  26037. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26038. // and that has to end a read() already waiting on the peer, on every platform.
  26039. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26040. // The peer sends no pings, and its handler never calls read(), which is
  26041. // where pongs are written.
  26042. std::mutex mutex;
  26043. std::condition_variable cv;
  26044. auto release = false;
  26045. svr.set_websocket_ping_interval(0);
  26046. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26047. std::unique_lock<std::mutex> lock(mutex);
  26048. cv.wait(lock, [&] { return release; });
  26049. });
  26050. auto port = svr.bind_to_any_port(HOST);
  26051. std::thread t([&]() { svr.listen_after_bind(); });
  26052. auto se = detail::scope_exit([&] {
  26053. {
  26054. std::lock_guard<std::mutex> lock(mutex);
  26055. release = true;
  26056. }
  26057. cv.notify_all();
  26058. svr.stop();
  26059. t.join();
  26060. });
  26061. svr.wait_until_ready();
  26062. ws::WebSocketClient client(std::string(scheme) +
  26063. "://localhost:" + std::to_string(port) + "/ws");
  26064. #ifdef CPPHTTPLIB_SSL_ENABLED
  26065. client.enable_server_certificate_verification(false);
  26066. #endif
  26067. // A ping a second, given up on after two go unanswered: about 3s
  26068. client.set_websocket_ping_interval(1);
  26069. client.set_websocket_max_missed_pongs(2);
  26070. // Well past that, so that a read the timeout ends instead stands out
  26071. client.set_read_timeout(10);
  26072. ASSERT_TRUE(client.connect());
  26073. auto start = std::chrono::steady_clock::now();
  26074. std::string msg;
  26075. EXPECT_EQ(ws::Fail, client.read(msg));
  26076. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26077. std::chrono::steady_clock::now() - start)
  26078. .count(),
  26079. 6000);
  26080. EXPECT_FALSE(client.is_open());
  26081. }
  26082. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26083. Server svr;
  26084. check_pong_timeout_ends_read(svr, "ws");
  26085. }
  26086. #ifdef CPPHTTPLIB_SSL_ENABLED
  26087. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26088. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26089. ASSERT_TRUE(svr.is_valid());
  26090. check_pong_timeout_ends_read(svr, "wss");
  26091. }
  26092. #endif
  26093. // listen() returns only after every handler has, so Server::stop() has to end
  26094. // a WebSocket handler's read() waiting on a client that stays connected and
  26095. // quiet, whether or not the handler bounded its reads, and the client's
  26096. // connection ends with it.
  26097. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26098. bool bounded) {
  26099. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26100. if (bounded) { ws.set_read_timeout(0, 50000); }
  26101. std::string msg;
  26102. while (ws.read(msg) != ws::Fail) {}
  26103. });
  26104. auto port = svr.bind_to_any_port(HOST);
  26105. std::thread t([&]() { svr.listen_after_bind(); });
  26106. auto se = detail::scope_exit([&] {
  26107. if (t.joinable()) {
  26108. svr.stop();
  26109. t.join();
  26110. }
  26111. });
  26112. svr.wait_until_ready();
  26113. ws::WebSocketClient client(std::string(scheme) +
  26114. "://localhost:" + std::to_string(port) + "/ws");
  26115. #ifdef CPPHTTPLIB_SSL_ENABLED
  26116. client.enable_server_certificate_verification(false);
  26117. #endif
  26118. client.set_read_timeout(2);
  26119. ASSERT_TRUE(client.connect());
  26120. auto stopped = std::async(std::launch::async, [&] {
  26121. svr.stop();
  26122. t.join();
  26123. });
  26124. std::string msg;
  26125. EXPECT_EQ(ws::Fail, client.read(msg));
  26126. EXPECT_FALSE(client.is_open());
  26127. auto in_time =
  26128. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26129. // A handler the stop did not reach ends when the client leaves
  26130. if (!in_time) { client.close(); }
  26131. stopped.wait();
  26132. EXPECT_TRUE(in_time);
  26133. }
  26134. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26135. Server svr;
  26136. check_stop_ends_websocket_read(svr, "ws", false);
  26137. }
  26138. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26139. Server svr;
  26140. check_stop_ends_websocket_read(svr, "ws", true);
  26141. }
  26142. #ifdef CPPHTTPLIB_SSL_ENABLED
  26143. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26144. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26145. ASSERT_TRUE(svr.is_valid());
  26146. check_stop_ends_websocket_read(svr, "wss", false);
  26147. }
  26148. #endif
  26149. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26150. // dropped connection, whether the handler waits for a message or for the rest
  26151. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26152. // time out inside the message as well, and the stop ends them too.
  26153. static void check_stop_closes_with_going_away(const std::string &sent,
  26154. bool bounded = false) {
  26155. Server svr;
  26156. svr.set_websocket_ping_interval(0);
  26157. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26158. if (bounded) { ws.set_read_timeout(0, 10000); }
  26159. std::string msg;
  26160. while (ws.read(msg) != ws::Fail) {}
  26161. });
  26162. auto port = svr.bind_to_any_port("127.0.0.1");
  26163. std::thread t([&]() { svr.listen_after_bind(); });
  26164. auto se = detail::scope_exit([&] {
  26165. svr.stop();
  26166. t.join();
  26167. });
  26168. svr.wait_until_ready();
  26169. // Closed before the join above, which a handler the stop did not reach
  26170. // would otherwise hold up.
  26171. auto sock = connect_raw_websocket(port, "/ws");
  26172. ASSERT_NE(INVALID_SOCKET, sock);
  26173. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26174. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26175. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26176. // Let the handler take what was sent and wait for more
  26177. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26178. svr.stop();
  26179. // FIN + Close, its length, then the code: unmasked, from a server
  26180. std::string head;
  26181. char c;
  26182. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26183. head += c;
  26184. }
  26185. const std::string reason = "server stopping";
  26186. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26187. "\x03\xe9",
  26188. head);
  26189. }
  26190. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26191. check_stop_closes_with_going_away("");
  26192. }
  26193. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26194. // A Text frame without FIN: the first fragment of a message
  26195. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26196. }
  26197. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26198. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26199. /*bounded=*/true);
  26200. }
  26201. // A handler that bounds its reads gets control back within its timeout even
  26202. // while a message arrives in pieces, and the message whole once the last has
  26203. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26204. // sent a while after the one before, much longer than the handler's timeout.
  26205. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26206. const std::string &expected) {
  26207. std::atomic<bool> done{false};
  26208. std::string received;
  26209. std::chrono::steady_clock::duration longest{};
  26210. Server svr;
  26211. svr.set_websocket_ping_interval(0);
  26212. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26213. ws.set_read_timeout(0, 10000);
  26214. std::string msg;
  26215. ws::ReadResult r;
  26216. do {
  26217. auto began = std::chrono::steady_clock::now();
  26218. r = ws.read(msg);
  26219. longest = (std::max)(longest, std::chrono::steady_clock::now() - began);
  26220. } while (r == ws::Timeout);
  26221. if (r == ws::Text) { received = msg; }
  26222. done = true;
  26223. });
  26224. auto port = svr.bind_to_any_port("127.0.0.1");
  26225. std::thread t([&]() { svr.listen_after_bind(); });
  26226. auto se = detail::scope_exit([&] {
  26227. svr.stop();
  26228. t.join();
  26229. });
  26230. svr.wait_until_ready();
  26231. auto sock = connect_raw_websocket(port, "/ws");
  26232. ASSERT_NE(INVALID_SOCKET, sock);
  26233. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26234. for (const auto &piece : pieces) {
  26235. ASSERT_EQ(static_cast<ssize_t>(piece.size()),
  26236. detail::send_socket(sock, piece.data(), piece.size(), 0));
  26237. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26238. }
  26239. for (int i = 0; i < 500 && !done; i++) {
  26240. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26241. }
  26242. ASSERT_TRUE(done);
  26243. EXPECT_EQ(expected, received);
  26244. // Far under the 200 ms between the pieces, however loaded the machine
  26245. EXPECT_LT(longest, std::chrono::milliseconds(150));
  26246. }
  26247. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26248. // The header's first byte, then its second with half the mask key, then
  26249. // the rest: what a frame written in several writes may look like when
  26250. // Nagle's algorithm holds the later ones back for an ACK.
  26251. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26252. check_bounded_read_resumes(
  26253. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26254. }
  26255. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26256. check_bounded_read_resumes(
  26257. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26258. }
  26259. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26260. Server svr;
  26261. svr.set_websocket_ping_interval(0);
  26262. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26263. std::string msg;
  26264. while (ws.read(msg)) {}
  26265. });
  26266. auto port = svr.bind_to_any_port("127.0.0.1");
  26267. std::thread t([&]() { svr.listen_after_bind(); });
  26268. auto se = detail::scope_exit([&] {
  26269. svr.stop();
  26270. t.join();
  26271. });
  26272. svr.wait_until_ready();
  26273. // Each Close payload and the reply it should get: an echo when valid, 1002
  26274. // otherwise.
  26275. std::vector<std::pair<std::string, std::string>> cases = {
  26276. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26277. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26278. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26279. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26280. };
  26281. // Also between the fragments of a message.
  26282. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26283. for (const auto &c : cases) {
  26284. auto sock = connect_raw_websocket(port, "/ws");
  26285. ASSERT_NE(INVALID_SOCKET, sock);
  26286. auto frames = prefix + masked_frame(0x88, c.first);
  26287. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26288. std::string reply;
  26289. char buf[256];
  26290. while (reply.size() < 2 + c.second.size()) {
  26291. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26292. if (n <= 0) { break; }
  26293. reply.append(buf, static_cast<size_t>(n));
  26294. }
  26295. detail::close_socket(sock);
  26296. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26297. c.second,
  26298. reply);
  26299. }
  26300. }
  26301. }
  26302. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26303. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26304. protected:
  26305. void SetUp() override {
  26306. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26307. SERVER_PRIVATE_KEY_FILE);
  26308. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26309. std::string msg;
  26310. ws::ReadResult ret;
  26311. while ((ret = ws.read(msg))) {
  26312. if (ret == ws::Binary) {
  26313. ws.send(msg.data(), msg.size());
  26314. } else {
  26315. ws.send(msg);
  26316. }
  26317. }
  26318. });
  26319. port_ = server_->bind_to_any_port(HOST);
  26320. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26321. server_->wait_until_ready();
  26322. }
  26323. void TearDown() override {
  26324. server_->stop();
  26325. if (server_thread_.joinable()) { server_thread_.join(); }
  26326. }
  26327. std::unique_ptr<SSLServer> server_;
  26328. std::thread server_thread_;
  26329. int port_ = 0;
  26330. };
  26331. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26332. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26333. {
  26334. ws::WebSocketClient client(url);
  26335. client.enable_server_certificate_verification(false);
  26336. auto calls = 0;
  26337. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26338. calls++;
  26339. return false;
  26340. });
  26341. EXPECT_FALSE(client.connect());
  26342. EXPECT_GT(calls, 0);
  26343. }
  26344. {
  26345. ws::WebSocketClient client(url);
  26346. client.enable_server_certificate_verification(false);
  26347. client.set_session_verifier([](tls::session_t) {
  26348. return SSLVerifierResponse::CertificateRejected;
  26349. });
  26350. EXPECT_FALSE(client.connect());
  26351. }
  26352. {
  26353. ws::WebSocketClient client(url);
  26354. client.enable_server_certificate_verification(false);
  26355. client.set_session_verifier([](tls::session_t) {
  26356. return SSLVerifierResponse::CertificateAccepted;
  26357. });
  26358. EXPECT_TRUE(client.connect());
  26359. }
  26360. }
  26361. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26362. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26363. "/ws-echo");
  26364. client.enable_server_certificate_verification(false);
  26365. ASSERT_TRUE(client.connect());
  26366. ASSERT_TRUE(client.is_open());
  26367. ASSERT_TRUE(client.send("Hello WSS"));
  26368. std::string msg;
  26369. EXPECT_EQ(ws::Text, client.read(msg));
  26370. EXPECT_EQ("Hello WSS", msg);
  26371. client.close();
  26372. }
  26373. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26374. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26375. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26376. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26377. // client (without calling close() first) is the only path that runs
  26378. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26379. // bug exactly.
  26380. //
  26381. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26382. // when linked against an instrumented libssl; run under Valgrind to catch it
  26383. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26384. // suite (the freed session otherwise stalls on the close handshake) — this test
  26385. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26386. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26387. {
  26388. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26389. "/ws-echo");
  26390. client.enable_server_certificate_verification(false);
  26391. client.set_read_timeout(2, 0);
  26392. client.set_write_timeout(2, 0);
  26393. ASSERT_TRUE(client.connect());
  26394. ASSERT_TRUE(client.is_open());
  26395. ASSERT_TRUE(client.send("still open"));
  26396. // Intentionally do NOT call client.close(): leaving scope runs
  26397. // shutdown_and_close() with the WebSocket still open, which must send the
  26398. // close frame while the TLS session is still alive.
  26399. }
  26400. }
  26401. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26402. // shutdown_and_close() at the start of connect(), reproducing the same
  26403. // use-after-free within the test body rather than at scope exit. The second
  26404. // connect must succeed and echo, proving the close handshake ran over a live
  26405. // session. See the note above about memory-tool requirements.
  26406. TEST_F(WebSocketSSLIntegrationTest,
  26407. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26408. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26409. "/ws-echo");
  26410. client.enable_server_certificate_verification(false);
  26411. client.set_read_timeout(2, 0);
  26412. client.set_write_timeout(2, 0);
  26413. ASSERT_TRUE(client.connect());
  26414. ASSERT_TRUE(client.is_open());
  26415. ASSERT_TRUE(client.send("still open"));
  26416. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26417. // the still-open connection, which must not touch a freed TLS session.
  26418. ASSERT_TRUE(client.connect());
  26419. ASSERT_TRUE(client.is_open());
  26420. ASSERT_TRUE(client.send("after reconnect"));
  26421. std::string msg;
  26422. EXPECT_EQ(ws::Text, client.read(msg));
  26423. EXPECT_EQ("after reconnect", msg);
  26424. client.close();
  26425. }
  26426. #endif
  26427. #ifdef CPPHTTPLIB_SSL_ENABLED
  26428. class WebSocketSSLCATest : public ::testing::Test {
  26429. protected:
  26430. void SetUp() override {
  26431. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26432. SERVER_PRIVATE_KEY_FILE);
  26433. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26434. std::string msg;
  26435. while (ws.read(msg)) {
  26436. ws.send(msg);
  26437. }
  26438. });
  26439. port_ = server_->bind_to_any_port("127.0.0.1");
  26440. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26441. server_->wait_until_ready();
  26442. }
  26443. void TearDown() override {
  26444. server_->stop();
  26445. if (server_thread_.joinable()) { server_thread_.join(); }
  26446. }
  26447. std::string url() const {
  26448. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26449. }
  26450. std::unique_ptr<SSLServer> server_;
  26451. std::thread server_thread_;
  26452. int port_ = 0;
  26453. };
  26454. // A custom CA loaded as PEM verifies the server with full certificate
  26455. // verification enabled
  26456. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26457. ws::WebSocketClient client(url());
  26458. std::string cert;
  26459. read_file(SERVER_CERT2_FILE, cert);
  26460. client.load_ca_cert_store(cert.c_str(), cert.size());
  26461. ASSERT_TRUE(client.connect());
  26462. ASSERT_TRUE(client.send("hello"));
  26463. std::string msg;
  26464. EXPECT_EQ(ws::Text, client.read(msg));
  26465. EXPECT_EQ("hello", msg);
  26466. client.close();
  26467. }
  26468. // A custom CA that does not cover the server must fail verification (the
  26469. // custom CA is exclusive; system certs are not loaded alongside it)
  26470. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26471. ws::WebSocketClient client(url());
  26472. std::string cert;
  26473. read_file(CLIENT_CA_CERT_FILE, cert);
  26474. client.load_ca_cert_store(cert.c_str(), cert.size());
  26475. auto res = client.connect();
  26476. ASSERT_FALSE(res);
  26477. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26478. EXPECT_EQ(-1, res.status());
  26479. EXPECT_NE(0u, res.ssl_backend_error());
  26480. }
  26481. // The same CA as a file path rather than PEM in memory
  26482. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26483. ws::WebSocketClient client(url());
  26484. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26485. ASSERT_TRUE(client.connect());
  26486. ASSERT_TRUE(client.send("hello"));
  26487. std::string msg;
  26488. EXPECT_EQ(ws::Text, client.read(msg));
  26489. EXPECT_EQ("hello", msg);
  26490. client.close();
  26491. }
  26492. // ...and a CA file that does not cover the server still fails, so it is the
  26493. // path above that decides the outcome
  26494. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  26495. ws::WebSocketClient client(url());
  26496. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26497. ASSERT_FALSE(client.connect());
  26498. }
  26499. // Regression test: reconnecting with a native custom CA store used to reuse
  26500. // a store handle the previous TLS context had already freed (use-after-free
  26501. // under the OpenSSL backend). The context now lives as long as the client.
  26502. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  26503. ws::WebSocketClient client(url());
  26504. std::string cert;
  26505. read_file(SERVER_CERT2_FILE, cert);
  26506. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  26507. ASSERT_TRUE(client.connect());
  26508. client.close();
  26509. ASSERT_TRUE(client.connect());
  26510. ASSERT_TRUE(client.send("again"));
  26511. std::string msg;
  26512. EXPECT_EQ(ws::Text, client.read(msg));
  26513. EXPECT_EQ("again", msg);
  26514. client.close();
  26515. }
  26516. // Regression test: a certificate with a trusted chain but no identity match
  26517. // for the server IP must be rejected. The Mbed TLS backend used to skip
  26518. // verification entirely for IP hosts, so this connection succeeded there.
  26519. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  26520. // chain verification while the identity check must still fail.
  26521. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  26522. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26523. ASSERT_TRUE(svr.is_valid());
  26524. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26525. std::string msg;
  26526. while (ws.read(msg)) {
  26527. ws.send(msg);
  26528. }
  26529. });
  26530. auto port = svr.bind_to_any_port("127.0.0.1");
  26531. auto t = std::thread([&]() { svr.listen_after_bind(); });
  26532. auto se = detail::scope_exit([&] {
  26533. svr.stop();
  26534. t.join();
  26535. });
  26536. svr.wait_until_ready();
  26537. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  26538. "/echo");
  26539. std::string cert;
  26540. read_file(SERVER_CERT_FILE, cert);
  26541. client.load_ca_cert_store(cert.c_str(), cert.size());
  26542. ASSERT_FALSE(client.connect());
  26543. }
  26544. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  26545. // SNI, so nothing binds the host name to the TLS session. These bind the
  26546. // server to "localhost" instead, the only shape that exercises the SNI and
  26547. // hostname-verification path with certificate verification left enabled.
  26548. class WebSocketSSLDnsHostTest : public ::testing::Test {
  26549. protected:
  26550. void Start(const char *cert_file) {
  26551. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  26552. SERVER_PRIVATE_KEY_FILE);
  26553. ASSERT_TRUE(server_->is_valid());
  26554. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26555. std::string msg;
  26556. while (ws.read(msg)) {
  26557. ws.send(msg);
  26558. }
  26559. });
  26560. port_ = server_->bind_to_any_port("localhost");
  26561. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26562. server_->wait_until_ready();
  26563. }
  26564. void TearDown() override {
  26565. if (server_) { server_->stop(); }
  26566. if (server_thread_.joinable()) { server_thread_.join(); }
  26567. }
  26568. std::string url() const {
  26569. return "wss://localhost:" + std::to_string(port_) + "/echo";
  26570. }
  26571. std::unique_ptr<SSLServer> server_;
  26572. std::thread server_thread_;
  26573. int port_ = 0;
  26574. };
  26575. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  26576. // out and the connection is usable
  26577. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  26578. Start(SERVER_CERT2_FILE);
  26579. ws::WebSocketClient client(url());
  26580. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26581. ASSERT_TRUE(client.connect());
  26582. ASSERT_TRUE(client.send("hello"));
  26583. std::string msg;
  26584. EXPECT_EQ(ws::Text, client.read(msg));
  26585. EXPECT_EQ("hello", msg);
  26586. client.close();
  26587. }
  26588. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  26589. // while the identity check must still reject "localhost"
  26590. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  26591. Start(SERVER_CERT_FILE);
  26592. ws::WebSocketClient client(url());
  26593. client.set_ca_cert_path(SERVER_CERT_FILE);
  26594. auto res = client.connect();
  26595. ASSERT_FALSE(res);
  26596. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  26597. EXPECT_EQ(-1, res.status());
  26598. }
  26599. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  26600. // disabled: the chain is still checked, only the identity check is skipped
  26601. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  26602. Start(SERVER_CERT_FILE);
  26603. ws::WebSocketClient client(url());
  26604. client.set_ca_cert_path(SERVER_CERT_FILE);
  26605. client.enable_server_hostname_verification(false);
  26606. ASSERT_TRUE(client.connect());
  26607. ASSERT_TRUE(client.send("hello"));
  26608. std::string msg;
  26609. EXPECT_EQ(ws::Text, client.read(msg));
  26610. EXPECT_EQ("hello", msg);
  26611. client.close();
  26612. }
  26613. // A CA that did not sign the server certificate fails the chain, even though
  26614. // the name would match
  26615. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  26616. Start(SERVER_CERT2_FILE);
  26617. ws::WebSocketClient client(url());
  26618. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26619. ASSERT_FALSE(client.connect());
  26620. }
  26621. // With verification disabled, neither the chain nor the name is checked
  26622. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  26623. Start(SERVER_CERT_FILE);
  26624. ws::WebSocketClient client(url());
  26625. client.enable_server_certificate_verification(false);
  26626. ASSERT_TRUE(client.connect());
  26627. ASSERT_TRUE(client.send("hello"));
  26628. std::string msg;
  26629. EXPECT_EQ(ws::Text, client.read(msg));
  26630. EXPECT_EQ("hello", msg);
  26631. client.close();
  26632. }
  26633. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  26634. protected:
  26635. void SetUp() override {
  26636. server_ = httplib::detail::make_unique<SSLServer>(
  26637. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  26638. ASSERT_TRUE(server_->is_valid());
  26639. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26640. std::string msg;
  26641. while (ws.read(msg)) {
  26642. ws.send(msg);
  26643. }
  26644. });
  26645. port_ = server_->bind_to_any_port("localhost");
  26646. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26647. server_->wait_until_ready();
  26648. }
  26649. void TearDown() override {
  26650. server_->stop();
  26651. if (server_thread_.joinable()) { server_thread_.join(); }
  26652. }
  26653. std::string url() const {
  26654. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26655. }
  26656. void ConnectWithClientCert(const std::string &client_cert_file,
  26657. const std::string &client_private_key_file,
  26658. const char *private_key_password) {
  26659. std::string cert_pem, key_pem;
  26660. read_file(client_cert_file, cert_pem);
  26661. read_file(client_private_key_file, key_pem);
  26662. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  26663. key_pem.c_str(), key_pem.size(),
  26664. private_key_password};
  26665. ConnectWithPem(pem);
  26666. }
  26667. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  26668. ws::WebSocketClient client(url(), pem);
  26669. ASSERT_TRUE(client.is_valid());
  26670. client.enable_server_certificate_verification(false);
  26671. ASSERT_TRUE(client.connect());
  26672. ASSERT_TRUE(client.send("hello"));
  26673. std::string msg;
  26674. EXPECT_EQ(ws::Text, client.read(msg));
  26675. EXPECT_EQ("hello", msg);
  26676. client.close();
  26677. }
  26678. std::unique_ptr<SSLServer> server_;
  26679. std::thread server_thread_;
  26680. int port_ = 0;
  26681. };
  26682. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  26683. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  26684. }
  26685. // Control for the tests above: the fixture's server really does require a
  26686. // client certificate, so it is the PEM the constructor installed that decides
  26687. // the outcome.
  26688. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  26689. ws::WebSocketClient client(url());
  26690. ASSERT_TRUE(client.is_valid());
  26691. client.enable_server_certificate_verification(false);
  26692. EXPECT_FALSE(client.connect());
  26693. }
  26694. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  26695. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  26696. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  26697. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  26698. }
  26699. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  26700. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  26701. std::string cert_pem, key_pem;
  26702. read_file(CLIENT_CERT_FILE, cert_pem);
  26703. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  26704. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  26705. std::vector<char> key(key_pem.begin(), key_pem.end());
  26706. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  26707. key.size(), nullptr};
  26708. ConnectWithPem(pem);
  26709. }
  26710. #endif
  26711. #if !defined(_WIN32)
  26712. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  26713. auto secret_dir = std::string("./symlink_test_secret");
  26714. auto served_dir = std::string("./symlink_test_served");
  26715. auto secret_file = secret_dir + "/secret.txt";
  26716. auto symlink_path = served_dir + "/escape";
  26717. // Setup: create directories and files
  26718. mkdir(secret_dir.c_str(), 0755);
  26719. mkdir(served_dir.c_str(), 0755);
  26720. {
  26721. std::ofstream ofs(secret_file);
  26722. ofs << "SECRET_DATA";
  26723. }
  26724. // Create symlink using absolute path so it resolves correctly
  26725. #ifdef PATH_MAX
  26726. char abs_secret[PATH_MAX];
  26727. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  26728. #else
  26729. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  26730. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  26731. ASSERT_NE(nullptr, abs_secret);
  26732. #endif
  26733. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  26734. auto se = detail::scope_exit([&] {
  26735. unlink(symlink_path.c_str());
  26736. unlink(secret_file.c_str());
  26737. rmdir(served_dir.c_str());
  26738. rmdir(secret_dir.c_str());
  26739. });
  26740. Server svr;
  26741. svr.set_mount_point("/", served_dir);
  26742. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26743. auto se2 = detail::scope_exit([&] {
  26744. svr.stop();
  26745. listen_thread.join();
  26746. });
  26747. svr.wait_until_ready();
  26748. Client cli("localhost", PORT);
  26749. // Symlink pointing outside base dir should be blocked
  26750. auto res = cli.Get("/escape/secret.txt");
  26751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26752. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26753. }
  26754. #else
  26755. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  26756. auto secret_dir = std::string("junction_test_secret");
  26757. auto served_dir = std::string("junction_test_served");
  26758. auto secret_file = secret_dir + "\\secret.txt";
  26759. auto junction_path = served_dir + "\\escape";
  26760. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  26761. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  26762. {
  26763. std::ofstream ofs(secret_file);
  26764. ofs << "SECRET_DATA";
  26765. }
  26766. // A junction needs no privilege to create, unlike a symlink
  26767. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  26768. ASSERT_EQ(0, std::system(cmd.c_str()));
  26769. auto se = detail::scope_exit([&] {
  26770. ::RemoveDirectoryA(junction_path.c_str());
  26771. std::remove(secret_file.c_str());
  26772. ::RemoveDirectoryA(served_dir.c_str());
  26773. ::RemoveDirectoryA(secret_dir.c_str());
  26774. });
  26775. Server svr;
  26776. svr.set_mount_point("/", served_dir);
  26777. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26778. auto se2 = detail::scope_exit([&] {
  26779. svr.stop();
  26780. listen_thread.join();
  26781. });
  26782. svr.wait_until_ready();
  26783. Client cli("localhost", PORT);
  26784. // Junction pointing outside base dir should be blocked
  26785. auto res = cli.Get("/escape/secret.txt");
  26786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26787. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26788. }
  26789. #endif
  26790. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  26791. // "GET /smuggled" request), reads the first response, and only then sends the
  26792. // embedded request as the body. Returns how many times /smuggled ran.
  26793. //
  26794. // The body is sent AFTER receiving the first response (as in the original
  26795. // PoC) so that the stream_line_reader cannot buffer it together with the
  26796. // headers of the first request.
  26797. static int count_smuggled_requests(const std::string &outer_head,
  26798. std::string &first_response) {
  26799. Server svr;
  26800. svr.set_mount_point("/", "./www");
  26801. std::atomic<int> smuggled_count(0);
  26802. svr.Get("/smuggled", [&](const Request &, Response &res) {
  26803. smuggled_count++;
  26804. res.set_content("oops", "text/plain");
  26805. });
  26806. svr.Post("/post", [&](const Request &req, Response &res) {
  26807. res.set_content(req.body, "text/plain");
  26808. });
  26809. auto port = svr.bind_to_any_port("localhost");
  26810. thread t = thread([&] { svr.listen_after_bind(); });
  26811. auto se = detail::scope_exit([&] {
  26812. svr.stop();
  26813. t.join();
  26814. });
  26815. svr.wait_until_ready();
  26816. auto error = Error::Success;
  26817. auto sock = detail::create_client_socket(
  26818. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  26819. /*connection_timeout_sec=*/2, 0,
  26820. /*read_timeout_sec=*/2, 0,
  26821. /*write_timeout_sec=*/2, 0, std::string(), error);
  26822. EXPECT_NE(INVALID_SOCKET, sock);
  26823. if (sock == INVALID_SOCKET) { return -1; }
  26824. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  26825. // The "smuggled" request will be sent as the body of the outer request
  26826. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  26827. "Host: localhost\r\n"
  26828. "Connection: close\r\n"
  26829. "\r\n";
  26830. auto head = outer_head;
  26831. auto len = std::to_string(smuggled.size());
  26832. for (auto pos = head.find("{len}"); pos != std::string::npos;
  26833. pos = head.find("{len}", pos + len.size())) {
  26834. head.replace(pos, 5, len);
  26835. }
  26836. // Step 1: Send only the outer request headers (no body yet)
  26837. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  26838. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  26839. // Step 2: Read the first response
  26840. char buf[4096];
  26841. for (;;) {
  26842. auto n = recv(sock, buf, sizeof(buf), 0);
  26843. if (n <= 0) break;
  26844. first_response.append(buf, static_cast<size_t>(n));
  26845. // Stop once we have a complete response (headers + body)
  26846. auto hdr_end = first_response.find("\r\n\r\n");
  26847. if (hdr_end != std::string::npos) {
  26848. // Check for Content-Length to know when the body is complete
  26849. auto cl_pos = first_response.find("Content-Length:");
  26850. if (cl_pos != std::string::npos) {
  26851. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  26852. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  26853. auto cl = std::stoul(
  26854. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  26855. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  26856. } else {
  26857. break; // No Content-Length, assume headers-only response
  26858. }
  26859. }
  26860. }
  26861. // Step 3: Now send the body, which looks like a new HTTP request. On a
  26862. // vulnerable server the keep-alive loop reads this as a second request. The
  26863. // server may already have closed the connection, so the result is ignored.
  26864. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  26865. // Half-close so that a server which drained the body sees EOF and closes,
  26866. // instead of the read below waiting for the read timeout.
  26867. #ifdef _WIN32
  26868. ::shutdown(sock, SD_SEND);
  26869. #else
  26870. ::shutdown(sock, SHUT_WR);
  26871. #endif
  26872. // Step 4: Read until the server closes the connection
  26873. for (;;) {
  26874. auto n = recv(sock, buf, sizeof(buf), 0);
  26875. if (n <= 0) break;
  26876. }
  26877. return smuggled_count.load();
  26878. }
  26879. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  26880. // A GET request with Content-Length to a static file handler must have its
  26881. // body drained before the keep-alive connection is reused. Otherwise the
  26882. // unread body bytes are interpreted as the next HTTP request.
  26883. std::string first_response;
  26884. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26885. "Host: localhost\r\n"
  26886. "Content-Length: {len}\r\n"
  26887. "\r\n",
  26888. first_response));
  26889. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  26890. }
  26891. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  26892. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  26893. // be answered with 400 and the connection closed. Treating it as "no body"
  26894. // leaves the body to be parsed as the next request.
  26895. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  26896. const char *targets[] = {
  26897. "GET /file", // handler that never reads the body
  26898. "GET /not-found", // no handler matches (404)
  26899. "POST /post", // handler that reads the body
  26900. };
  26901. for (auto target : targets) {
  26902. for (auto value : values) {
  26903. std::string first_response;
  26904. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  26905. " HTTP/1.1\r\n"
  26906. "Host: localhost\r\n"
  26907. "Content-Length: " +
  26908. value + "\r\n\r\n",
  26909. first_response))
  26910. << target << " with Content-Length: " << value;
  26911. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  26912. << target << " with Content-Length: " << value;
  26913. }
  26914. }
  26915. }
  26916. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  26917. // A 400 for an unparseable request line leaves the rest of the message
  26918. // unread, so the connection must be closed rather than reused.
  26919. std::string first_response;
  26920. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  26921. "Host: localhost\r\n"
  26922. "Content-Length: {len}\r\n"
  26923. "\r\n",
  26924. first_response));
  26925. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26926. }
  26927. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  26928. // Same as above for a header block that fails to parse.
  26929. std::string first_response;
  26930. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  26931. "Host: localhost\r\n"
  26932. "Bad Header\r\n"
  26933. "Content-Length: {len}\r\n"
  26934. "\r\n",
  26935. first_response));
  26936. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  26937. }
  26938. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  26939. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  26940. // server must not read another request on that connection, even when the
  26941. // request had no body to drain.
  26942. std::string first_response;
  26943. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  26944. "Host: localhost\r\n"
  26945. "\r\n",
  26946. first_response));
  26947. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  26948. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  26949. }
  26950. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  26951. // A content reader that stops early leaves the stream inside the body.
  26952. // Draining the whole Content-Length from there, or reading the body again,
  26953. // reads into the next request, and whatever follows is parsed as a request
  26954. // of its own.
  26955. Server svr;
  26956. std::atomic<int> smuggled_count(0);
  26957. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  26958. svr.Post("/upload", [](const Request &req, Response &res,
  26959. const ContentReader &content_reader) {
  26960. // Stop at the last chunk, so the whole body has been read however it
  26961. // arrives.
  26962. auto length = req.get_header_value_u64("Content-Length");
  26963. size_t total = 0;
  26964. auto consumed = content_reader([&](const char *, size_t n) {
  26965. total += n;
  26966. return total < length;
  26967. });
  26968. EXPECT_FALSE(consumed);
  26969. if (req.has_param("retry")) {
  26970. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  26971. }
  26972. // Replace the 400 the aborted read set, which would close the connection.
  26973. res.set_redirect("/done");
  26974. });
  26975. auto port = svr.bind_to_any_port(HOST);
  26976. thread t = thread([&] { svr.listen_after_bind(); });
  26977. auto se = detail::scope_exit([&] {
  26978. svr.stop();
  26979. t.join();
  26980. });
  26981. svr.wait_until_ready();
  26982. // A front end sees the second request as a POST whose body is the GET. The
  26983. // first body is as long as the POST's headers, so draining it again reads
  26984. // exactly those and leaves the GET to be parsed next.
  26985. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  26986. "Host: localhost\r\n"
  26987. "\r\n";
  26988. std::string second_head = "POST /post HTTP/1.1\r\n"
  26989. "Host: localhost\r\n"
  26990. "Content-Length: " +
  26991. std::to_string(inner.size()) +
  26992. "\r\n"
  26993. "\r\n";
  26994. for (auto target : {"/upload", "/upload?retry"}) {
  26995. smuggled_count = 0;
  26996. std::string request = "POST " + std::string(target) +
  26997. " HTTP/1.1\r\n"
  26998. "Host: localhost\r\n"
  26999. "Content-Length: " +
  27000. std::to_string(second_head.size()) +
  27001. "\r\n"
  27002. "\r\n" +
  27003. std::string(second_head.size(), 'A') + second_head +
  27004. inner;
  27005. std::string response;
  27006. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27007. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27008. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27009. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27010. EXPECT_EQ(0, smuggled_count.load()) << target;
  27011. }
  27012. }
  27013. // An error response closes the connection anyway, so the body is left unread
  27014. // with a redirect, such as one to a login page.
  27015. static void serve_redirects(Server &svr,
  27016. const std::function<void(int)> &client) {
  27017. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27018. res.set_redirect("/login");
  27019. return Server::HandlerResponse::Handled;
  27020. });
  27021. auto port = svr.bind_to_any_port(HOST);
  27022. ASSERT_GT(port, 0);
  27023. thread t = thread([&] { svr.listen_after_bind(); });
  27024. auto se = detail::scope_exit([&] {
  27025. svr.stop();
  27026. t.join();
  27027. ASSERT_FALSE(svr.is_running());
  27028. });
  27029. svr.wait_until_ready();
  27030. client(port);
  27031. }
  27032. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27033. Server svr;
  27034. serve_redirects(svr, [](int port) {
  27035. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27036. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27037. std::to_string(body.size()) + "\r\n\r\n" + body +
  27038. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27039. std::string resp;
  27040. ASSERT_TRUE(send_request(1, req, &resp, port));
  27041. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27042. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27043. });
  27044. }
  27045. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27046. Server svr;
  27047. svr.set_read_timeout(0, 200000);
  27048. serve_redirects(svr, [](int port) {
  27049. // A byte every 100 ms keeps each read within the read timeout, but not the
  27050. // body as a whole, so the server closes and the bytes sent after that fail.
  27051. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27052. "Content-Length: 10\r\n\r\n"};
  27053. parts.resize(11, "x");
  27054. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27055. });
  27056. }
  27057. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27058. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27059. // must be rejected with 400 Bad Request.
  27060. Server svr;
  27061. svr.Post("/test", [&](const Request &, Response &res) {
  27062. res.set_content("ok", "text/plain");
  27063. });
  27064. thread t = thread([&] { svr.listen(HOST, PORT); });
  27065. auto se = detail::scope_exit([&] {
  27066. svr.stop();
  27067. t.join();
  27068. ASSERT_FALSE(svr.is_running());
  27069. });
  27070. svr.wait_until_ready();
  27071. // Exact "chunked"
  27072. {
  27073. auto req = "POST /test HTTP/1.1\r\n"
  27074. "Host: localhost\r\n"
  27075. "Content-Length: 5\r\n"
  27076. "Transfer-Encoding: chunked\r\n"
  27077. "Connection: close\r\n"
  27078. "\r\n"
  27079. "hello";
  27080. std::string response;
  27081. ASSERT_TRUE(send_request(1, req, &response));
  27082. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27083. response.substr(0, response.find("\r\n")));
  27084. }
  27085. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27086. {
  27087. auto req = "POST /test HTTP/1.1\r\n"
  27088. "Host: localhost\r\n"
  27089. "Content-Length: 5\r\n"
  27090. "Transfer-Encoding: gzip, chunked\r\n"
  27091. "Connection: close\r\n"
  27092. "\r\n"
  27093. "hello";
  27094. std::string response;
  27095. ASSERT_TRUE(send_request(1, req, &response));
  27096. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27097. response.substr(0, response.find("\r\n")));
  27098. }
  27099. }
  27100. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27101. Server svr;
  27102. svr.Post("/test", [&](const Request &, Response &res) {
  27103. res.set_content("ok", "text/plain");
  27104. });
  27105. thread t = thread([&] { svr.listen(HOST, PORT); });
  27106. auto se = detail::scope_exit([&] {
  27107. svr.stop();
  27108. t.join();
  27109. ASSERT_FALSE(svr.is_running());
  27110. });
  27111. svr.wait_until_ready();
  27112. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27113. // length cannot be determined, so the server must answer 400 and close
  27114. // rather than treat the request as bodyless and leave the body in the
  27115. // socket for the next request to pick up.
  27116. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27117. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27118. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27119. std::string response;
  27120. ASSERT_TRUE(send_request(1, req, &response));
  27121. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27122. response.substr(0, response.find("\r\n")))
  27123. << transfer_encoding;
  27124. }
  27125. // RFC 9110 5.3: the codings may also be split across several
  27126. // Transfer-Encoding lines, which combine in the order they were received.
  27127. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27128. // just like the single-line "chunked, gzip" above.
  27129. {
  27130. auto req = "POST /test HTTP/1.1\r\n"
  27131. "Host: localhost\r\n"
  27132. "Transfer-Encoding: chunked\r\n"
  27133. "Transfer-Encoding: gzip\r\n"
  27134. "\r\n"
  27135. "0\r\n\r\n";
  27136. std::string response;
  27137. ASSERT_TRUE(send_request(1, req, &response));
  27138. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27139. response.substr(0, response.find("\r\n")));
  27140. }
  27141. }
  27142. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27143. Server svr;
  27144. svr.Post("/test", [&](const Request &, Response &res) {
  27145. res.set_content("ok", "text/plain");
  27146. });
  27147. auto port = svr.bind_to_any_port(HOST);
  27148. ASSERT_GT(port, 0);
  27149. thread t = thread([&] { svr.listen_after_bind(); });
  27150. auto se = detail::scope_exit([&] {
  27151. svr.stop();
  27152. t.join();
  27153. ASSERT_FALSE(svr.is_running());
  27154. });
  27155. svr.wait_until_ready();
  27156. for (auto transfer_encoding :
  27157. {"Transfer-Encoding: gzip, chunked\r\n",
  27158. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27159. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27160. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27161. transfer_encoding + "\r\n0\r\n\r\n";
  27162. std::string response;
  27163. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27164. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27165. response.substr(0, response.find("\r\n")))
  27166. << transfer_encoding;
  27167. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27168. << transfer_encoding;
  27169. }
  27170. }
  27171. // Regression for issue #2450: a DELETE without Content-Length on a
  27172. // keep-alive connection must not let the post-response drain consume the
  27173. // next request's bytes.
  27174. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27175. Server svr;
  27176. std::atomic<int> delete_count(0);
  27177. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27178. delete_count++;
  27179. res.status = StatusCode::NoContent_204;
  27180. });
  27181. auto port = svr.bind_to_any_port(HOST);
  27182. thread t = thread([&] { svr.listen_after_bind(); });
  27183. auto se = detail::scope_exit([&] {
  27184. svr.stop();
  27185. t.join();
  27186. });
  27187. svr.wait_until_ready();
  27188. auto error = Error::Success;
  27189. auto sock = detail::create_client_socket(
  27190. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27191. /*connection_timeout_sec=*/2, 0,
  27192. /*read_timeout_sec=*/2, 0,
  27193. /*write_timeout_sec=*/2, 0, std::string(), error);
  27194. ASSERT_NE(INVALID_SOCKET, sock);
  27195. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27196. auto send_request_and_read_response = [&](const std::string &req,
  27197. std::string &out) -> bool {
  27198. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27199. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27200. char buf[4096];
  27201. for (;;) {
  27202. auto n = recv(sock, buf, sizeof(buf), 0);
  27203. if (n <= 0) { return !out.empty(); }
  27204. out.append(buf, static_cast<size_t>(n));
  27205. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27206. }
  27207. };
  27208. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27209. "Host: localhost\r\n"
  27210. "\r\n";
  27211. std::string resp1;
  27212. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27213. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27214. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27215. "Host: localhost\r\n"
  27216. "Connection: close\r\n"
  27217. "\r\n";
  27218. std::string resp2;
  27219. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27220. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27221. EXPECT_EQ(2, delete_count.load());
  27222. }
  27223. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27224. Server svr;
  27225. svr.Post("/ingest", [&](const Request &, Response &res,
  27226. const ContentReader &content_reader) {
  27227. auto consumed = content_reader([](const char *, size_t) { return false; });
  27228. EXPECT_FALSE(consumed);
  27229. res.status = StatusCode::Conflict_409;
  27230. res.set_header("Connection", "close");
  27231. });
  27232. auto port = svr.bind_to_any_port(HOST);
  27233. thread t = thread([&] { svr.listen_after_bind(); });
  27234. auto se = detail::scope_exit([&] {
  27235. svr.stop();
  27236. t.join();
  27237. });
  27238. svr.wait_until_ready();
  27239. auto error = Error::Success;
  27240. auto sock = detail::create_client_socket(
  27241. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27242. /*connection_timeout_sec=*/2, 0,
  27243. /*read_timeout_sec=*/1, 0,
  27244. /*write_timeout_sec=*/2, 0, std::string(), error);
  27245. ASSERT_NE(INVALID_SOCKET, sock);
  27246. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27247. std::string request = "POST /ingest HTTP/1.1\r\n"
  27248. "Host: localhost\r\n"
  27249. "Transfer-Encoding: chunked\r\n"
  27250. "\r\n"
  27251. "4\r\n"
  27252. "data\r\n";
  27253. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27254. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27255. std::string response;
  27256. ssize_t received = 0;
  27257. do {
  27258. char buf[4096];
  27259. received = recv(sock, buf, sizeof(buf), 0);
  27260. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27261. } while (received > 0);
  27262. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27263. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27264. EXPECT_EQ(0, received);
  27265. }
  27266. namespace no_proxy_test {
  27267. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27268. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27269. // calling listen().
  27270. class ScopedServer {
  27271. public:
  27272. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27273. ~ScopedServer() {
  27274. svr_.stop();
  27275. if (th_.joinable()) { th_.join(); }
  27276. }
  27277. Server &svr() { return svr_; }
  27278. int port() const { return port_; }
  27279. void listen() {
  27280. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27281. svr_.wait_until_ready();
  27282. }
  27283. private:
  27284. Server svr_;
  27285. std::thread th_;
  27286. int port_ = 0;
  27287. };
  27288. class ProxyAndTargetServers {
  27289. public:
  27290. ProxyAndTargetServers() {
  27291. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27292. proxy_hits_++;
  27293. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27294. res.set_content("via-proxy", "text/plain");
  27295. });
  27296. target_.Get(".*", [this](const Request &req, Response &res) {
  27297. target_hits_++;
  27298. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27299. res.set_content("direct", "text/plain");
  27300. });
  27301. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27302. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27303. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27304. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27305. proxy_mock_.wait_until_ready();
  27306. target_.wait_until_ready();
  27307. }
  27308. ~ProxyAndTargetServers() {
  27309. proxy_mock_.stop();
  27310. target_.stop();
  27311. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27312. if (target_thread_.joinable()) { target_thread_.join(); }
  27313. }
  27314. Server &proxy_mock() { return proxy_mock_; }
  27315. Server &target() { return target_; }
  27316. int proxy_port() const { return proxy_port_; }
  27317. int target_port() const { return target_port_; }
  27318. int proxy_hits() const { return proxy_hits_.load(); }
  27319. int target_hits() const { return target_hits_.load(); }
  27320. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27321. void reset_counters() {
  27322. proxy_hits_ = 0;
  27323. target_hits_ = 0;
  27324. last_had_proxy_authz_ = false;
  27325. }
  27326. private:
  27327. Server proxy_mock_;
  27328. Server target_;
  27329. std::thread proxy_thread_;
  27330. std::thread target_thread_;
  27331. int proxy_port_ = 0;
  27332. int target_port_ = 0;
  27333. std::atomic<int> proxy_hits_{0};
  27334. std::atomic<int> target_hits_{0};
  27335. std::atomic<bool> last_had_proxy_authz_{false};
  27336. };
  27337. inline std::unique_ptr<Client> make_client(const std::string &host,
  27338. ProxyAndTargetServers &s) {
  27339. auto cli = detail::make_unique<Client>(host, s.target_port());
  27340. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27341. cli->set_proxy("127.0.0.1", s.proxy_port());
  27342. return cli;
  27343. }
  27344. } // namespace no_proxy_test
  27345. using no_proxy_test::make_client;
  27346. using no_proxy_test::ProxyAndTargetServers;
  27347. // A stream request carries the credentials a buffered request does
  27348. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27349. no_proxy_test::ScopedServer origin;
  27350. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27351. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27352. });
  27353. origin.listen();
  27354. Client cli("127.0.0.1", origin.port());
  27355. cli.set_basic_auth("user", "pass");
  27356. auto handle = cli.open_stream("GET", "/x");
  27357. ASSERT_TRUE(handle.is_valid());
  27358. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27359. Client bearer("127.0.0.1", origin.port());
  27360. bearer.set_bearer_token_auth("tok");
  27361. auto handle2 = bearer.open_stream("GET", "/x");
  27362. ASSERT_TRUE(handle2.is_valid());
  27363. EXPECT_EQ("Bearer tok", read_all(handle2));
  27364. }
  27365. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27366. // takes its own credentials, as for a buffered request
  27367. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27368. std::string target, authz, proxy_authz;
  27369. no_proxy_test::ScopedServer proxy;
  27370. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27371. target = req.target;
  27372. authz = req.get_header_value("Authorization");
  27373. proxy_authz = req.get_header_value("Proxy-Authorization");
  27374. res.set_content("ok", "text/plain");
  27375. });
  27376. proxy.listen();
  27377. Client cli("origin.example", 8080);
  27378. cli.set_proxy("127.0.0.1", proxy.port());
  27379. cli.set_proxy_basic_auth("puser", "ppass");
  27380. cli.set_basic_auth("user", "pass");
  27381. auto handle = cli.open_stream("GET", "/x");
  27382. ASSERT_TRUE(handle.is_valid());
  27383. EXPECT_EQ("ok", read_all(handle));
  27384. EXPECT_EQ("http://origin.example:8080/x", target);
  27385. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27386. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27387. }
  27388. // In absolute-form the path follows the authority, so a path that does not
  27389. // begin with '/' would make the proxy connect to another host
  27390. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27391. std::vector<std::string> targets;
  27392. no_proxy_test::ScopedServer proxy;
  27393. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27394. targets.push_back(req.target);
  27395. res.set_content("ok", "text/plain");
  27396. });
  27397. proxy.listen();
  27398. Client cli("origin.example", 8080);
  27399. cli.set_proxy("127.0.0.1", proxy.port());
  27400. cli.set_basic_auth("user", "pass");
  27401. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27402. auto res = cli.Get(path);
  27403. EXPECT_FALSE(res) << path;
  27404. auto handle = cli.open_stream("GET", path);
  27405. EXPECT_FALSE(handle.is_valid()) << path;
  27406. }
  27407. EXPECT_TRUE(targets.empty());
  27408. auto res = cli.Get("/x");
  27409. ASSERT_TRUE(res);
  27410. ASSERT_EQ(1u, targets.size());
  27411. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27412. }
  27413. TEST(NoProxyTest, ExactHostnameBypasses) {
  27414. ProxyAndTargetServers s;
  27415. auto cli = make_client("example.com", s);
  27416. cli->set_no_proxy({"example.com"});
  27417. auto res = cli->Get("/");
  27418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27419. EXPECT_EQ(0, s.proxy_hits());
  27420. EXPECT_EQ(1, s.target_hits());
  27421. }
  27422. TEST(NoProxyTest, SubdomainBypasses) {
  27423. ProxyAndTargetServers s;
  27424. auto cli = make_client("foo.example.com", s);
  27425. cli->set_no_proxy({"example.com"});
  27426. auto res = cli->Get("/");
  27427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27428. EXPECT_EQ(0, s.proxy_hits());
  27429. EXPECT_EQ(1, s.target_hits());
  27430. }
  27431. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27432. // Regression guard: "evilexample.com" must not be considered a subdomain
  27433. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27434. // check would let traffic bypass the proxy and leak credentials direct
  27435. // to the attacker host.
  27436. ProxyAndTargetServers s;
  27437. auto cli = make_client("evilexample.com", s);
  27438. cli->set_no_proxy({"example.com"});
  27439. auto res = cli->Get("/");
  27440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27441. EXPECT_GE(s.proxy_hits(), 1);
  27442. EXPECT_EQ(0, s.target_hits());
  27443. }
  27444. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27445. ProxyAndTargetServers s;
  27446. auto cli = make_client("example.com.evil.com", s);
  27447. cli->set_no_proxy({"example.com"});
  27448. auto res = cli->Get("/");
  27449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27450. EXPECT_GE(s.proxy_hits(), 1);
  27451. EXPECT_EQ(0, s.target_hits());
  27452. }
  27453. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27454. ProxyAndTargetServers s;
  27455. auto cli = make_client("example.com", s);
  27456. cli->set_no_proxy({".example.com"});
  27457. auto res = cli->Get("/");
  27458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27459. EXPECT_EQ(0, s.proxy_hits());
  27460. EXPECT_EQ(1, s.target_hits());
  27461. }
  27462. TEST(NoProxyTest, CaseInsensitiveHostname) {
  27463. ProxyAndTargetServers s;
  27464. auto cli = make_client("Example.COM", s);
  27465. cli->set_no_proxy({"EXAMPLE.com"});
  27466. auto res = cli->Get("/");
  27467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27468. EXPECT_EQ(0, s.proxy_hits());
  27469. EXPECT_EQ(1, s.target_hits());
  27470. }
  27471. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27472. ProxyAndTargetServers s;
  27473. auto cli = make_client("example.com.", s);
  27474. cli->set_no_proxy({"example.com"});
  27475. auto res = cli->Get("/");
  27476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27477. EXPECT_EQ(0, s.proxy_hits());
  27478. EXPECT_EQ(1, s.target_hits());
  27479. }
  27480. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27481. // Trailing dots must be normalized on BOTH sides — host and entry.
  27482. // An implementation that only strips the host-side trailing dot would
  27483. // fail to match host "example.com" against entry "example.com." because
  27484. // a literal substring search would compare 11 chars against 12.
  27485. ProxyAndTargetServers s;
  27486. auto cli = make_client("example.com", s);
  27487. cli->set_no_proxy({"example.com."});
  27488. auto res = cli->Get("/");
  27489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27490. EXPECT_EQ(0, s.proxy_hits());
  27491. EXPECT_EQ(1, s.target_hits());
  27492. }
  27493. TEST(NoProxyTest, WildcardBypassesEverything) {
  27494. ProxyAndTargetServers s;
  27495. auto cli = make_client("anything.invalid.test", s);
  27496. cli->set_no_proxy({"*"});
  27497. auto res = cli->Get("/");
  27498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27499. EXPECT_EQ(0, s.proxy_hits());
  27500. EXPECT_EQ(1, s.target_hits());
  27501. }
  27502. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  27503. ProxyAndTargetServers s;
  27504. Client cli("127.0.0.1", s.target_port());
  27505. cli.set_proxy("127.0.0.1", s.proxy_port());
  27506. cli.set_no_proxy({"127.0.0.1"});
  27507. auto res = cli.Get("/");
  27508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27509. EXPECT_EQ(0, s.proxy_hits());
  27510. EXPECT_EQ(1, s.target_hits());
  27511. }
  27512. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  27513. ProxyAndTargetServers s;
  27514. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  27515. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  27516. cli.set_proxy("127.0.0.1", s.proxy_port());
  27517. cli.set_no_proxy({"::1"});
  27518. auto res = cli.Get("/");
  27519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27520. EXPECT_EQ(0, s.proxy_hits());
  27521. EXPECT_EQ(1, s.target_hits());
  27522. }
  27523. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  27524. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  27525. // must still be recognized as IPv6 for CIDR matching. Implementations
  27526. // that detect IPv6 only when the host begins with '[' would parse the
  27527. // host as a hostname and miss the match.
  27528. ProxyAndTargetServers s;
  27529. Client cli("fe80::1", s.target_port());
  27530. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27531. cli.set_proxy("127.0.0.1", s.proxy_port());
  27532. cli.set_no_proxy({"fe80::/10"});
  27533. auto res = cli.Get("/");
  27534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27535. EXPECT_EQ(0, s.proxy_hits());
  27536. EXPECT_EQ(1, s.target_hits());
  27537. }
  27538. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  27539. ProxyAndTargetServers s;
  27540. Client cli("::1", s.target_port());
  27541. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  27542. cli.set_proxy("127.0.0.1", s.proxy_port());
  27543. cli.set_no_proxy({"[::1]"});
  27544. auto res = cli.Get("/");
  27545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27546. EXPECT_EQ(0, s.proxy_hits());
  27547. EXPECT_EQ(1, s.target_hits());
  27548. }
  27549. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  27550. ProxyAndTargetServers s;
  27551. Client cli("fe80::1", s.target_port());
  27552. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27553. cli.set_proxy("127.0.0.1", s.proxy_port());
  27554. cli.set_no_proxy({"[fe80::]/10"});
  27555. auto res = cli.Get("/");
  27556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27557. EXPECT_EQ(0, s.proxy_hits());
  27558. EXPECT_EQ(1, s.target_hits());
  27559. }
  27560. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  27561. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  27562. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  27563. // tricks via address-family conversion.
  27564. ProxyAndTargetServers s;
  27565. Client cli("::ffff:127.0.0.1", s.target_port());
  27566. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  27567. cli.set_proxy("127.0.0.1", s.proxy_port());
  27568. cli.set_no_proxy({"127.0.0.1"});
  27569. auto res = cli.Get("/");
  27570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27571. EXPECT_GE(s.proxy_hits(), 1);
  27572. EXPECT_EQ(0, s.target_hits());
  27573. }
  27574. TEST(NoProxyTest, IPv4CidrMatch) {
  27575. ProxyAndTargetServers s;
  27576. Client cli("127.0.0.1", s.target_port());
  27577. cli.set_proxy("127.0.0.1", s.proxy_port());
  27578. cli.set_no_proxy({"127.0.0.0/8"});
  27579. auto res = cli.Get("/");
  27580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27581. EXPECT_EQ(0, s.proxy_hits());
  27582. EXPECT_EQ(1, s.target_hits());
  27583. }
  27584. TEST(NoProxyTest, IPv4CidrNonMatch) {
  27585. ProxyAndTargetServers s;
  27586. Client cli("127.0.0.1", s.target_port());
  27587. cli.set_proxy("127.0.0.1", s.proxy_port());
  27588. cli.set_no_proxy({"10.0.0.0/8"});
  27589. auto res = cli.Get("/");
  27590. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27591. EXPECT_GE(s.proxy_hits(), 1);
  27592. EXPECT_EQ(0, s.target_hits());
  27593. }
  27594. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  27595. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  27596. // IPv4 target matches.
  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({"0.0.0.0/0"});
  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, IPv4CidrSingleHostNoSlash) {
  27607. ProxyAndTargetServers s;
  27608. Client cli("127.0.0.1", s.target_port());
  27609. cli.set_proxy("127.0.0.1", s.proxy_port());
  27610. cli.set_no_proxy({"127.0.0.1"});
  27611. auto res = cli.Get("/");
  27612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27613. EXPECT_EQ(0, s.proxy_hits());
  27614. EXPECT_EQ(1, s.target_hits());
  27615. }
  27616. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  27617. ProxyAndTargetServers s;
  27618. Client cli("127.0.0.1", s.target_port());
  27619. cli.set_proxy("127.0.0.1", s.proxy_port());
  27620. cli.set_no_proxy({"127.0.0.0/33"});
  27621. auto res = cli.Get("/");
  27622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27623. EXPECT_GE(s.proxy_hits(), 1);
  27624. EXPECT_EQ(0, s.target_hits());
  27625. }
  27626. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  27627. // Empty prefix after the slash must be rejected, not silently treated as /32.
  27628. ProxyAndTargetServers s;
  27629. Client cli("127.0.0.1", s.target_port());
  27630. cli.set_proxy("127.0.0.1", s.proxy_port());
  27631. cli.set_no_proxy({"127.0.0.1/"});
  27632. auto res = cli.Get("/");
  27633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27634. EXPECT_GE(s.proxy_hits(), 1);
  27635. EXPECT_EQ(0, s.target_hits());
  27636. }
  27637. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  27638. ProxyAndTargetServers s;
  27639. auto cli = make_client("internal.corp", s);
  27640. cli->set_proxy_basic_auth("u", "p");
  27641. cli->set_no_proxy({"internal.corp"});
  27642. auto res = cli->Get("/");
  27643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27644. EXPECT_EQ(1, s.target_hits());
  27645. EXPECT_EQ(0, s.proxy_hits());
  27646. EXPECT_FALSE(s.last_had_proxy_authz())
  27647. << "Proxy-Authorization must not be sent direct to the target";
  27648. }
  27649. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  27650. ProxyAndTargetServers s;
  27651. auto cli = make_client("public.example", s);
  27652. cli->set_proxy_basic_auth("u", "p");
  27653. cli->set_no_proxy({"internal.corp"}); // does not match
  27654. auto res = cli->Get("/");
  27655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27656. EXPECT_GE(s.proxy_hits(), 1);
  27657. EXPECT_TRUE(s.last_had_proxy_authz());
  27658. }
  27659. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  27660. std::atomic<int> hits{0};
  27661. std::atomic<int> hits_with_authz{0};
  27662. no_proxy_test::ScopedServer proxy_mock;
  27663. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27664. hits++;
  27665. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  27666. if (req.target.find("/redir") != std::string::npos) {
  27667. res.set_redirect("http://other.example/landed");
  27668. } else {
  27669. res.set_content("via-proxy", "text/plain");
  27670. }
  27671. });
  27672. proxy_mock.listen();
  27673. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  27674. hits = 0;
  27675. hits_with_authz = 0;
  27676. Client cli("public.example", 80);
  27677. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27678. cli.set_proxy_basic_auth(c.first, c.second);
  27679. cli.set_follow_location(true);
  27680. // The redirect to another host goes through the proxy as well
  27681. auto res = cli.Get("/redir");
  27682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27683. EXPECT_EQ(2, hits.load());
  27684. EXPECT_EQ(2, hits_with_authz.load());
  27685. }
  27686. }
  27687. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  27688. ProxyAndTargetServers s;
  27689. auto cli = make_client("anything.test", s);
  27690. auto res = cli->Get("/");
  27691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27692. EXPECT_GE(s.proxy_hits(), 1);
  27693. EXPECT_EQ(0, s.target_hits());
  27694. }
  27695. TEST(NoProxyTest, PortSpecificEntryRejected) {
  27696. ProxyAndTargetServers s;
  27697. auto cli = make_client("example.com", s);
  27698. cli->set_no_proxy({"example.com:8080"});
  27699. auto res = cli->Get("/");
  27700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27701. EXPECT_GE(s.proxy_hits(), 1);
  27702. EXPECT_EQ(0, s.target_hits());
  27703. }
  27704. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  27705. ProxyAndTargetServers s;
  27706. auto cli = make_client("anything.test", s);
  27707. cli->set_no_proxy({"", " ", "\t"});
  27708. auto res = cli->Get("/");
  27709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27710. EXPECT_GE(s.proxy_hits(), 1);
  27711. EXPECT_EQ(0, s.target_hits());
  27712. }
  27713. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  27714. // An entry with leading/trailing whitespace must still match — env-style
  27715. // values are commonly pasted with stray spaces and an implementation
  27716. // that feeds the raw token directly to inet_pton would fail to match
  27717. // valid CIDRs because of the spaces.
  27718. ProxyAndTargetServers s;
  27719. Client cli("127.0.0.1", s.target_port());
  27720. cli.set_proxy("127.0.0.1", s.proxy_port());
  27721. cli.set_no_proxy({" 127.0.0.0/8 "});
  27722. auto res = cli.Get("/");
  27723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27724. EXPECT_EQ(0, s.proxy_hits());
  27725. EXPECT_EQ(1, s.target_hits());
  27726. }
  27727. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  27728. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  27729. // go direct and must NOT carry Proxy-Authorization.
  27730. std::atomic<int> proxy_hits{0};
  27731. std::atomic<int> target_hits{0};
  27732. std::atomic<bool> target_saw_authz{false};
  27733. no_proxy_test::ScopedServer proxy_mock, target;
  27734. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27735. proxy_hits++;
  27736. res.status = 302;
  27737. res.set_header("Location", "http://127.0.0.1:" +
  27738. std::to_string(target.port()) + "/landed");
  27739. });
  27740. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27741. target_hits++;
  27742. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  27743. res.set_content("direct", "text/plain");
  27744. });
  27745. proxy_mock.listen();
  27746. target.listen();
  27747. Client cli("public.example", target.port());
  27748. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27749. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27750. cli.set_proxy_basic_auth("u", "p");
  27751. cli.set_no_proxy({"127.0.0.1"});
  27752. cli.set_follow_location(true);
  27753. auto res = cli.Get("/redir");
  27754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27755. EXPECT_GE(proxy_hits.load(), 1);
  27756. EXPECT_GE(target_hits.load(), 1);
  27757. EXPECT_FALSE(target_saw_authz.load());
  27758. }
  27759. #ifdef CPPHTTPLIB_SSL_ENABLED
  27760. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  27761. // Direct origin replying 407 must not trigger the digest retry; otherwise
  27762. // proxy creds would be sent to the (possibly hostile) origin.
  27763. std::atomic<int> target_hits{0};
  27764. std::atomic<bool> target_saw_proxy_authz{false};
  27765. no_proxy_test::ScopedServer target;
  27766. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27767. target_hits++;
  27768. if (req.has_header("Proxy-Authorization")) {
  27769. target_saw_proxy_authz = true;
  27770. }
  27771. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27772. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  27773. "nonce=\"abc\", algorithm=MD5");
  27774. });
  27775. target.listen();
  27776. // The proxy address is set to the target's port: the bypass MUST kick in;
  27777. // if it doesn't, the test still routes "via proxy" to the same server and
  27778. // the Proxy-Authorization assertion below catches the leak.
  27779. Client cli("evil.example", target.port());
  27780. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  27781. cli.set_proxy("127.0.0.1", target.port());
  27782. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27783. cli.set_no_proxy({"evil.example"});
  27784. auto res = cli.Get("/x");
  27785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27786. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27787. EXPECT_EQ(1, target_hits.load());
  27788. EXPECT_FALSE(target_saw_proxy_authz.load());
  27789. }
  27790. #endif
  27791. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  27792. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  27793. std::atomic<int> proxy_hits{0};
  27794. std::atomic<int> bypass_hits{0};
  27795. std::atomic<bool> proxy_saw_c_url{false};
  27796. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  27797. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27798. proxy_hits++;
  27799. if (req.path.find("/start") != std::string::npos) {
  27800. res.status = 302;
  27801. res.set_header("Location", "http://127.0.0.1:" +
  27802. std::to_string(bypass_server.port()) +
  27803. "/middle");
  27804. return;
  27805. }
  27806. if (req.path.find("/end") != std::string::npos) {
  27807. proxy_saw_c_url = true;
  27808. res.set_content("c-via-proxy", "text/plain");
  27809. return;
  27810. }
  27811. res.set_content("unexpected", "text/plain");
  27812. });
  27813. // public.example's "advertised" port is arbitrary (the request never lands
  27814. // there — it goes through the proxy), but use a dynamic value to stay
  27815. // friendly with sharded parallel runs.
  27816. int public_port = bypass_server.port();
  27817. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  27818. bypass_hits++;
  27819. res.status = 302;
  27820. res.set_header("Location", "http://public.example:" +
  27821. std::to_string(public_port) + "/end");
  27822. });
  27823. proxy_mock.listen();
  27824. bypass_server.listen();
  27825. Client cli("public.example", public_port);
  27826. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27827. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27828. cli.set_no_proxy({"127.0.0.1"});
  27829. cli.set_follow_location(true);
  27830. auto res = cli.Get("/start");
  27831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27832. EXPECT_EQ(StatusCode::OK_200, res->status);
  27833. EXPECT_EQ("c-via-proxy", res->body);
  27834. EXPECT_GE(proxy_hits.load(), 2);
  27835. EXPECT_GE(bypass_hits.load(), 1);
  27836. EXPECT_TRUE(proxy_saw_c_url.load());
  27837. }
  27838. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  27839. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  27840. // request reconnects to the correct endpoint.
  27841. std::atomic<int> proxy_hits{0};
  27842. std::atomic<int> target_hits{0};
  27843. no_proxy_test::ScopedServer proxy_mock, target;
  27844. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27845. proxy_hits++;
  27846. res.set_content("via-proxy", "text/plain");
  27847. });
  27848. target.svr().Get(".*", [&](const Request &, Response &res) {
  27849. target_hits++;
  27850. res.set_content("direct", "text/plain");
  27851. });
  27852. proxy_mock.listen();
  27853. target.listen();
  27854. Client cli("public.example", target.port());
  27855. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27856. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27857. cli.set_keep_alive(true);
  27858. auto res1 = cli.Get("/a");
  27859. ASSERT_TRUE(res1);
  27860. EXPECT_EQ("via-proxy", res1->body);
  27861. EXPECT_EQ(1, proxy_hits.load());
  27862. EXPECT_EQ(0, target_hits.load());
  27863. cli.set_no_proxy({"public.example"});
  27864. auto res2 = cli.Get("/b");
  27865. ASSERT_TRUE(res2);
  27866. EXPECT_EQ("direct", res2->body);
  27867. EXPECT_EQ(1, proxy_hits.load());
  27868. EXPECT_EQ(1, target_hits.load());
  27869. }
  27870. // Forward declarations (see the base64_encode note).
  27871. namespace httplib {
  27872. namespace detail {
  27873. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  27874. int shutdown_socket(socket_t sock) noexcept;
  27875. } // namespace detail
  27876. } // namespace httplib
  27877. namespace proxy_tunnel_test {
  27878. const char *const kTunnelEstablished =
  27879. "HTTP/1.1 200 Connection established\r\n\r\n";
  27880. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  27881. using ConnectReply = std::function<std::string(const std::string &head)>;
  27882. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  27883. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  27884. class ScopedConnectProxy {
  27885. public:
  27886. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  27887. : forward_port_(forward_port), reply_(std::move(reply)) {
  27888. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  27889. if (listen_sock_ == INVALID_SOCKET) { return; }
  27890. auto a = loopback(0);
  27891. auto addr = reinterpret_cast<sockaddr *>(&a);
  27892. socklen_t alen = sizeof(a);
  27893. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  27894. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  27895. ::listen(listen_sock_, 4) != 0) {
  27896. return;
  27897. }
  27898. port_ = ntohs(a.sin_port);
  27899. th_ = std::thread([this] { run(); });
  27900. }
  27901. ~ScopedConnectProxy() {
  27902. if (th_.joinable()) {
  27903. stop_ = true;
  27904. auto wake = connect_to(port_);
  27905. th_.join();
  27906. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  27907. }
  27908. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  27909. }
  27910. int port() const { return port_; }
  27911. int connect_hits() const { return connect_hits_.load(); }
  27912. // Head of the last CONNECT request, as the proxy saw it on the wire.
  27913. std::string connect_request() const {
  27914. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27915. return connect_request_;
  27916. }
  27917. private:
  27918. static sockaddr_in loopback(int port) {
  27919. sockaddr_in a{};
  27920. a.sin_family = AF_INET;
  27921. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  27922. a.sin_port = htons(static_cast<unsigned short>(port));
  27923. return a;
  27924. }
  27925. static socket_t connect_to(int port) {
  27926. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  27927. if (sock == INVALID_SOCKET) { return sock; }
  27928. auto a = loopback(port);
  27929. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  27930. detail::close_socket(sock);
  27931. return INVALID_SOCKET;
  27932. }
  27933. return sock;
  27934. }
  27935. static bool send_all(socket_t sock, const char *data, size_t size) {
  27936. while (size > 0) {
  27937. auto n = detail::send_socket(sock, data, size, 0);
  27938. if (n <= 0) { return false; }
  27939. data += n;
  27940. size -= static_cast<size_t>(n);
  27941. }
  27942. return true;
  27943. }
  27944. void run() {
  27945. for (;;) {
  27946. auto client = ::accept(listen_sock_, nullptr, nullptr);
  27947. if (stop_) {
  27948. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  27949. return;
  27950. }
  27951. if (client == INVALID_SOCKET) { continue; }
  27952. serve(client);
  27953. detail::close_socket(client);
  27954. }
  27955. }
  27956. void serve(socket_t client) {
  27957. std::string head;
  27958. char buf[2048];
  27959. while (head.find("\r\n\r\n") == std::string::npos) {
  27960. if (detail::select_read(client, 5, 0) <= 0) { return; }
  27961. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  27962. if (n <= 0) { return; }
  27963. head.append(buf, static_cast<size_t>(n));
  27964. }
  27965. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  27966. connect_hits_++;
  27967. {
  27968. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  27969. connect_request_ = head;
  27970. }
  27971. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  27972. if (!send_all(client, res.data(), res.size()) ||
  27973. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  27974. return;
  27975. }
  27976. auto origin = connect_to(forward_port_);
  27977. if (origin == INVALID_SOCKET) { return; }
  27978. // When either side stops, shut both down so the other pump returns too.
  27979. auto pump = [&](socket_t from, socket_t to) {
  27980. char b[8192];
  27981. for (;;) {
  27982. auto n = detail::read_socket(from, b, sizeof(b), 0);
  27983. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  27984. }
  27985. detail::shutdown_socket(client);
  27986. detail::shutdown_socket(origin);
  27987. };
  27988. std::thread up([&] { pump(client, origin); });
  27989. pump(origin, client);
  27990. up.join();
  27991. detail::close_socket(origin);
  27992. }
  27993. int forward_port_;
  27994. ConnectReply reply_;
  27995. socket_t listen_sock_ = INVALID_SOCKET;
  27996. int port_ = 0;
  27997. std::thread th_;
  27998. std::atomic<bool> stop_{false};
  27999. std::atomic<int> connect_hits_{0};
  28000. mutable std::mutex connect_request_mutex_;
  28001. std::string connect_request_;
  28002. };
  28003. } // namespace proxy_tunnel_test
  28004. #ifdef CPPHTTPLIB_SSL_ENABLED
  28005. namespace proxy_tunnel_test {
  28006. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28007. class ScopedSSLServer {
  28008. public:
  28009. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28010. port_ = svr_.bind_to_any_port("127.0.0.1");
  28011. }
  28012. ~ScopedSSLServer() {
  28013. svr_.stop();
  28014. if (th_.joinable()) { th_.join(); }
  28015. }
  28016. SSLServer &svr() { return svr_; }
  28017. int port() const { return port_; }
  28018. void listen() {
  28019. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28020. svr_.wait_until_ready();
  28021. }
  28022. private:
  28023. SSLServer svr_;
  28024. std::thread th_;
  28025. int port_ = 0;
  28026. };
  28027. // Sends one request through the CONNECT proxy to the TLS origin with a
  28028. // credential configured for each hop, and checks that each credential reaches
  28029. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28030. // origin's (every header in origin_headers) on the tunnelled request.
  28031. void CredentialsStayWithTheirHop(
  28032. const std::function<void(SSLClient &)> &set_credentials,
  28033. const std::string &scheme,
  28034. const std::vector<std::string> &origin_headers = {"Authorization"},
  28035. bool stream = false) {
  28036. std::atomic<int> origin_hits{0};
  28037. std::atomic<bool> origin_saw_proxy_authz{false};
  28038. std::atomic<bool> origin_saw_headers{false};
  28039. ScopedSSLServer origin;
  28040. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28041. origin_hits++;
  28042. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28043. origin_saw_headers =
  28044. std::all_of(origin_headers.begin(), origin_headers.end(),
  28045. [&](const std::string &h) { return req.has_header(h); });
  28046. res.set_content("ok", "text/plain");
  28047. });
  28048. origin.listen();
  28049. ScopedConnectProxy proxy(origin.port());
  28050. ASSERT_NE(0, proxy.port());
  28051. // Pinned to 127.0.0.1 for the same reason as the test below.
  28052. SSLClient cli("127.0.0.1", origin.port());
  28053. cli.enable_server_certificate_verification(false);
  28054. cli.set_proxy("127.0.0.1", proxy.port());
  28055. set_credentials(cli);
  28056. if (stream) {
  28057. auto handle = cli.open_stream("GET", "/x");
  28058. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28059. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28060. } else {
  28061. auto res = cli.Get("/x");
  28062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28063. EXPECT_EQ(StatusCode::OK_200, res->status);
  28064. }
  28065. EXPECT_EQ(1, origin_hits.load());
  28066. EXPECT_EQ(1, proxy.connect_hits());
  28067. EXPECT_TRUE(origin_saw_headers.load());
  28068. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28069. << "Proxy-Authorization must not be sent inside the tunnel";
  28070. auto connect_req = proxy.connect_request();
  28071. EXPECT_NE(std::string::npos,
  28072. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28073. for (const auto &h : origin_headers) {
  28074. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28075. << h << " must not be sent to the proxy on CONNECT";
  28076. }
  28077. }
  28078. } // namespace proxy_tunnel_test
  28079. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28080. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28081. [](SSLClient &cli) {
  28082. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28083. cli.set_basic_auth("origin-user", "origin-pass");
  28084. },
  28085. "Basic");
  28086. }
  28087. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28088. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28089. [](SSLClient &cli) {
  28090. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28091. cli.set_basic_auth("origin-user", "origin-pass");
  28092. },
  28093. "Basic", {"Authorization"}, true);
  28094. }
  28095. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28096. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28097. [](SSLClient &cli) {
  28098. cli.set_proxy_bearer_token_auth("proxy-token");
  28099. cli.set_bearer_token_auth("origin-token");
  28100. },
  28101. "Bearer");
  28102. }
  28103. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28104. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28105. [](SSLClient &cli) {
  28106. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28107. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28108. {"Cookie", "sid=origin-session"},
  28109. {"X-Api-Key", "origin-key"}});
  28110. },
  28111. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28112. }
  28113. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28114. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28115. // retry; otherwise proxy creds would be sent to the origin.
  28116. std::atomic<int> origin_hits{0};
  28117. std::atomic<bool> origin_saw_proxy_authz{false};
  28118. proxy_tunnel_test::ScopedSSLServer origin;
  28119. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28120. origin_hits++;
  28121. if (req.has_header("Proxy-Authorization")) {
  28122. origin_saw_proxy_authz = true;
  28123. }
  28124. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28125. res.set_header("Proxy-Authenticate",
  28126. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28127. "algorithm=MD5");
  28128. });
  28129. origin.listen();
  28130. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28131. ASSERT_NE(0, proxy.port());
  28132. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28133. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28134. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28135. // and answer with its own status, making this test flaky.
  28136. SSLClient cli("127.0.0.1", origin.port());
  28137. cli.enable_server_certificate_verification(false);
  28138. cli.set_proxy("127.0.0.1", proxy.port());
  28139. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28140. auto res = cli.Get("/x");
  28141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28142. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28143. EXPECT_EQ(1, origin_hits.load());
  28144. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28145. EXPECT_EQ(1, proxy.connect_hits());
  28146. }
  28147. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28148. std::string origin_sni;
  28149. std::string origin_host;
  28150. proxy_tunnel_test::ScopedSSLServer origin;
  28151. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28152. origin_sni = req.sni();
  28153. origin_host = req.get_header_value("Host");
  28154. res.set_content("ok", "text/plain");
  28155. });
  28156. origin.listen();
  28157. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28158. ASSERT_NE(0, proxy.port());
  28159. SSLClient cli("origin.example", origin.port());
  28160. cli.enable_server_certificate_verification(false);
  28161. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28162. cli.set_proxy("127.0.0.1", proxy.port());
  28163. auto res = cli.Get("/x");
  28164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28165. EXPECT_EQ(StatusCode::OK_200, res->status);
  28166. auto port = std::to_string(origin.port());
  28167. auto target = "127.0.0.1:" + port;
  28168. auto connect_req = proxy.connect_request();
  28169. EXPECT_EQ(1, proxy.connect_hits());
  28170. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28171. EXPECT_NE(std::string::npos,
  28172. connect_req.find("\r\nHost: " + target + "\r\n"));
  28173. EXPECT_EQ("origin.example", origin_sni);
  28174. EXPECT_EQ("origin.example:" + port, origin_host);
  28175. }
  28176. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28177. proxy_tunnel_test::ScopedSSLServer origin;
  28178. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28179. res.set_content("ok", "text/plain");
  28180. });
  28181. origin.listen();
  28182. proxy_tunnel_test::ScopedConnectProxy proxy(
  28183. origin.port(), [](const std::string &head) -> std::string {
  28184. if (head.find(
  28185. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28186. std::string::npos) {
  28187. return proxy_tunnel_test::kTunnelEstablished;
  28188. }
  28189. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28190. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28191. "nonce=\"abc\", algorithm=MD5\r\n"
  28192. "Content-Length: 0\r\n\r\n";
  28193. });
  28194. ASSERT_NE(0, proxy.port());
  28195. SSLClient cli("origin.example", origin.port());
  28196. cli.enable_server_certificate_verification(false);
  28197. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28198. cli.set_proxy("127.0.0.1", proxy.port());
  28199. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28200. auto res = cli.Get("/x");
  28201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28202. EXPECT_EQ(StatusCode::OK_200, res->status);
  28203. // The retried CONNECT is the one the proxy saw last.
  28204. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28205. auto connect_req = proxy.connect_request();
  28206. EXPECT_EQ(2, proxy.connect_hits());
  28207. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28208. EXPECT_NE(std::string::npos,
  28209. connect_req.find("\r\nHost: " + target + "\r\n"));
  28210. }
  28211. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28212. proxy_tunnel_test::ScopedSSLServer origin;
  28213. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28214. res.set_content("ok", "text/plain");
  28215. });
  28216. origin.listen();
  28217. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28218. ASSERT_NE(0, proxy.port());
  28219. SSLClient cli("origin.example", origin.port());
  28220. cli.enable_server_certificate_verification(false);
  28221. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28222. cli.set_proxy("127.0.0.1", proxy.port());
  28223. auto res = cli.Get("/x");
  28224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28225. EXPECT_EQ(StatusCode::OK_200, res->status);
  28226. auto target = "origin.example:" + std::to_string(origin.port());
  28227. auto connect_req = proxy.connect_request();
  28228. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28229. EXPECT_NE(std::string::npos,
  28230. connect_req.find("\r\nHost: " + target + "\r\n"));
  28231. }
  28232. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28233. proxy_tunnel_test::ScopedSSLServer origin;
  28234. auto port = std::to_string(origin.port());
  28235. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28236. res.set_redirect("https://next.example:" + port + "/y");
  28237. });
  28238. origin.svr().Get("/y", [](const Request &, Response &res) {
  28239. res.set_content("ok", "text/plain");
  28240. });
  28241. origin.listen();
  28242. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28243. ASSERT_NE(0, proxy.port());
  28244. SSLClient cli("origin.example", origin.port());
  28245. cli.enable_server_certificate_verification(false);
  28246. cli.set_tunnel_hostname_addr_map(
  28247. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28248. cli.set_proxy("127.0.0.1", proxy.port());
  28249. cli.set_follow_location(true);
  28250. auto res = cli.Get("/x");
  28251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28252. EXPECT_EQ("ok", res->body);
  28253. // The last CONNECT is the redirect client's.
  28254. ASSERT_EQ(2, proxy.connect_hits());
  28255. auto target = "127.0.0.1:" + port;
  28256. auto connect_req = proxy.connect_request();
  28257. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28258. EXPECT_NE(std::string::npos,
  28259. connect_req.find("\r\nHost: " + target + "\r\n"));
  28260. }
  28261. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28262. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28263. std::atomic<int> origin_hits{0};
  28264. proxy_tunnel_test::ScopedSSLServer origin;
  28265. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28266. origin_hits++;
  28267. res.set_content("ok", "text/plain");
  28268. });
  28269. origin.listen();
  28270. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28271. ASSERT_NE(0, proxy.port());
  28272. SSLClient cli("127.0.0.1", origin.port());
  28273. cli.enable_server_certificate_verification(false);
  28274. cli.set_proxy("127.0.0.1", proxy.port());
  28275. cli.set_keep_alive(true);
  28276. cli.set_session_verifier(
  28277. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28278. auto res = cli.Get("/x");
  28279. EXPECT_FALSE(res);
  28280. ASSERT_FALSE(cli.is_socket_open());
  28281. res = cli.Get("/x");
  28282. EXPECT_FALSE(res);
  28283. EXPECT_EQ(2, proxy.connect_hits());
  28284. auto handle = cli.open_stream("GET", "/x");
  28285. EXPECT_FALSE(handle.is_valid());
  28286. EXPECT_EQ(3, proxy.connect_hits());
  28287. EXPECT_EQ(0, origin_hits.load());
  28288. }
  28289. #endif
  28290. namespace proxy_tunnel_test {
  28291. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28292. // anything else gets a 407 with `challenge`.
  28293. ConnectReply require_proxy_auth(const std::string &expected,
  28294. const std::string &challenge) {
  28295. return [=](const std::string &head) -> std::string {
  28296. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28297. std::string::npos) {
  28298. return kTunnelEstablished;
  28299. }
  28300. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28301. "Proxy-Authenticate: " +
  28302. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28303. };
  28304. }
  28305. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28306. // request, then echoes.
  28307. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28308. ws.send(
  28309. "authorization:" + req.get_header_value("Authorization") +
  28310. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28311. std::string msg;
  28312. while (ws.read(msg)) {
  28313. ws.send(msg);
  28314. }
  28315. }
  28316. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28317. class ScopedWebSocketOrigin {
  28318. public:
  28319. ScopedWebSocketOrigin() {
  28320. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28321. server_.listen();
  28322. }
  28323. int port() const { return server_.port(); }
  28324. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28325. std::string url() const {
  28326. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28327. }
  28328. private:
  28329. no_proxy_test::ScopedServer server_;
  28330. };
  28331. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28332. // passed as a constructor header, and checks that each reaches only its hop.
  28333. void WebSocketCredentialsStayWithTheirHop(
  28334. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28335. const std::string &proxy_authz, const std::string &origin_authz) {
  28336. ScopedWebSocketOrigin origin;
  28337. ScopedConnectProxy proxy(
  28338. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28339. ASSERT_NE(0, proxy.port());
  28340. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28341. client.set_proxy("127.0.0.1", proxy.port());
  28342. set_proxy_credentials(client);
  28343. auto res = client.connect();
  28344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28345. std::string msg;
  28346. ASSERT_TRUE(client.read(msg));
  28347. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28348. client.close();
  28349. EXPECT_EQ(1, proxy.connect_hits());
  28350. EXPECT_EQ(std::string::npos,
  28351. proxy.connect_request().find("\r\nAuthorization: "))
  28352. << "origin credentials must not be sent to the proxy";
  28353. }
  28354. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28355. void WebSocketSetterCredentialsStayWithTheirHop(
  28356. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28357. const std::string &proxy_authz, const std::string &origin_authz) {
  28358. ScopedWebSocketOrigin origin;
  28359. ScopedConnectProxy proxy(
  28360. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28361. ASSERT_NE(0, proxy.port());
  28362. ws::WebSocketClient client(origin.url());
  28363. client.set_proxy("127.0.0.1", proxy.port());
  28364. set_credentials(client);
  28365. auto res = client.connect();
  28366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28367. std::string msg;
  28368. ASSERT_TRUE(client.read(msg));
  28369. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28370. client.close();
  28371. EXPECT_EQ(1, proxy.connect_hits());
  28372. EXPECT_EQ(std::string::npos,
  28373. proxy.connect_request().find("\r\nAuthorization: "))
  28374. << "origin credentials must not be sent to the proxy";
  28375. }
  28376. } // namespace proxy_tunnel_test
  28377. namespace {
  28378. // Connects `client` and returns the Authorization header its upgrade
  28379. // request carried, or "<failed>" when the connection could not be opened.
  28380. std::string websocket_authorization(ws::WebSocketClient &client) {
  28381. if (!client.connect()) { return "<failed>"; }
  28382. std::string msg;
  28383. if (!client.read(msg)) { return "<failed>"; }
  28384. client.close();
  28385. auto prefix = std::string("authorization:");
  28386. auto end = msg.find("|proxy-authorization:");
  28387. return msg.substr(prefix.size(), end - prefix.size());
  28388. }
  28389. } // namespace
  28390. TEST(WebSocketClientAuthTest, BasicAuth) {
  28391. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28392. ws::WebSocketClient client(origin.url());
  28393. client.set_basic_auth("user", "pass");
  28394. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28395. websocket_authorization(client));
  28396. }
  28397. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28398. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28399. ws::WebSocketClient client(origin.url());
  28400. client.set_basic_auth("user", "");
  28401. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28402. websocket_authorization(client));
  28403. }
  28404. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28405. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28406. ws::WebSocketClient client(origin.url());
  28407. client.set_bearer_token_auth("token123");
  28408. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28409. }
  28410. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28411. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28412. ws::WebSocketClient client(origin.url());
  28413. client.set_bearer_token_auth("token123");
  28414. client.set_basic_auth("user", "pass");
  28415. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28416. websocket_authorization(client));
  28417. }
  28418. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28419. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28420. ws::WebSocketClient client(origin.url(),
  28421. {{"Authorization", "Bearer from-header"}});
  28422. client.set_bearer_token_auth("from-setter");
  28423. client.set_basic_auth("user", "pass");
  28424. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28425. }
  28426. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28427. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28428. ws::WebSocketClient client(origin.url());
  28429. EXPECT_EQ("", websocket_authorization(client));
  28430. client.set_bearer_token_auth("first");
  28431. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28432. client.set_bearer_token_auth("second");
  28433. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28434. client.set_bearer_token_auth("");
  28435. EXPECT_EQ("", websocket_authorization(client));
  28436. }
  28437. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28438. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28439. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28440. ASSERT_NE(0, proxy.port());
  28441. ws::WebSocketClient client(origin.url());
  28442. client.set_proxy("127.0.0.1", proxy.port());
  28443. auto res = client.connect();
  28444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28445. std::string msg;
  28446. ASSERT_TRUE(client.read(msg));
  28447. ASSERT_TRUE(client.send("hello"));
  28448. ASSERT_TRUE(client.read(msg));
  28449. EXPECT_EQ("hello", msg);
  28450. client.close();
  28451. EXPECT_EQ(1, proxy.connect_hits());
  28452. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28453. auto connect_req = proxy.connect_request();
  28454. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28455. EXPECT_NE(std::string::npos,
  28456. connect_req.find("\r\nHost: " + target + "\r\n"));
  28457. }
  28458. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28459. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28460. [](ws::WebSocketClient &cli) {
  28461. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28462. },
  28463. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28464. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28465. }
  28466. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28467. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28468. [](ws::WebSocketClient &cli) {
  28469. cli.set_proxy_bearer_token_auth("proxy-token");
  28470. },
  28471. "Bearer proxy-token", "Bearer origin-token");
  28472. }
  28473. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28474. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28475. [](ws::WebSocketClient &cli) {
  28476. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28477. cli.set_basic_auth("origin-user", "origin-pass");
  28478. },
  28479. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28480. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28481. }
  28482. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28483. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28484. [](ws::WebSocketClient &cli) {
  28485. cli.set_proxy_bearer_token_auth("proxy-token");
  28486. cli.set_bearer_token_auth("origin-token");
  28487. },
  28488. "Bearer proxy-token", "Bearer origin-token");
  28489. }
  28490. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  28491. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28492. proxy_tunnel_test::ScopedConnectProxy proxy(
  28493. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28494. "Basic " + detail::base64_encode("proxy-user:"),
  28495. "Basic realm=\"proxy\""));
  28496. ASSERT_NE(0, proxy.port());
  28497. ws::WebSocketClient client(origin.url());
  28498. client.set_proxy("127.0.0.1", proxy.port());
  28499. client.set_proxy_basic_auth("proxy-user", "");
  28500. auto res = client.connect();
  28501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28502. client.close();
  28503. EXPECT_EQ(1, proxy.connect_hits());
  28504. }
  28505. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  28506. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28507. proxy_tunnel_test::ScopedConnectProxy proxy(
  28508. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28509. "Bearer proxy-token", "Basic realm=\"proxy\""));
  28510. ASSERT_NE(0, proxy.port());
  28511. ws::WebSocketClient client(origin.url());
  28512. client.set_proxy("127.0.0.1", proxy.port());
  28513. auto res = client.connect();
  28514. EXPECT_FALSE(res);
  28515. EXPECT_EQ(Error::ProxyConnection, res.error());
  28516. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  28517. EXPECT_EQ("Basic realm=\"proxy\"",
  28518. res.get_header_value("Proxy-Authenticate"));
  28519. EXPECT_FALSE(client.is_open());
  28520. }
  28521. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  28522. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28523. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28524. ASSERT_NE(0, proxy.port());
  28525. ws::WebSocketClient client(origin.url());
  28526. client.set_proxy("127.0.0.1", proxy.port());
  28527. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28528. client.set_no_proxy({"127.0.0.1"});
  28529. auto res = client.connect();
  28530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28531. std::string msg;
  28532. ASSERT_TRUE(client.read(msg));
  28533. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28534. << "proxy credentials must not reach a bypassed origin";
  28535. client.close();
  28536. EXPECT_EQ(0, proxy.connect_hits());
  28537. }
  28538. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  28539. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28540. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28541. ASSERT_NE(0, proxy.port());
  28542. ws::WebSocketClient client(origin.url());
  28543. client.set_proxy("127.0.0.1", proxy.port());
  28544. ASSERT_TRUE(client.connect());
  28545. ASSERT_TRUE(client.connect());
  28546. client.close();
  28547. EXPECT_EQ(2, proxy.connect_hits());
  28548. }
  28549. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28550. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28551. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28552. ASSERT_NE(0, proxy.port());
  28553. auto port = std::to_string(origin.port());
  28554. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28555. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28556. client.set_proxy("127.0.0.1", proxy.port());
  28557. auto res = client.connect();
  28558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28559. std::string msg;
  28560. ASSERT_TRUE(client.read(msg));
  28561. client.close();
  28562. EXPECT_EQ(1, proxy.connect_hits());
  28563. auto target = "127.0.0.1:" + port;
  28564. auto connect_req = proxy.connect_request();
  28565. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28566. EXPECT_NE(std::string::npos,
  28567. connect_req.find("\r\nHost: " + target + "\r\n"));
  28568. }
  28569. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28570. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28571. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28572. ASSERT_NE(0, proxy.port());
  28573. auto port = std::to_string(origin.port());
  28574. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28575. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28576. client.set_proxy("127.0.0.1", proxy.port());
  28577. auto res = client.connect();
  28578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28579. client.close();
  28580. auto target = "origin.example:" + port;
  28581. auto connect_req = proxy.connect_request();
  28582. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28583. EXPECT_NE(std::string::npos,
  28584. connect_req.find("\r\nHost: " + target + "\r\n"));
  28585. }
  28586. #ifdef CPPHTTPLIB_SSL_ENABLED
  28587. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  28588. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28589. proxy_tunnel_test::ScopedConnectProxy proxy(
  28590. origin.port(), [](const std::string &head) -> std::string {
  28591. if (head.find(
  28592. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28593. std::string::npos) {
  28594. return proxy_tunnel_test::kTunnelEstablished;
  28595. }
  28596. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28597. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28598. "nonce=\"abc\", algorithm=MD5\r\n"
  28599. "Content-Length: 0\r\n\r\n";
  28600. });
  28601. ASSERT_NE(0, proxy.port());
  28602. ws::WebSocketClient client(origin.url());
  28603. client.set_proxy("127.0.0.1", proxy.port());
  28604. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28605. auto res = client.connect();
  28606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28607. std::string msg;
  28608. ASSERT_TRUE(client.read(msg));
  28609. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  28610. client.close();
  28611. EXPECT_EQ(2, proxy.connect_hits());
  28612. }
  28613. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  28614. proxy_tunnel_test::ScopedSSLServer origin;
  28615. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  28616. origin.listen();
  28617. proxy_tunnel_test::ScopedConnectProxy proxy(
  28618. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28619. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  28620. ASSERT_NE(0, proxy.port());
  28621. ws::WebSocketClient client(
  28622. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  28623. client.enable_server_certificate_verification(false);
  28624. client.set_proxy("127.0.0.1", proxy.port());
  28625. client.set_proxy_bearer_token_auth("proxy-token");
  28626. auto res = client.connect();
  28627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28628. std::string msg;
  28629. ASSERT_TRUE(client.read(msg));
  28630. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28631. << "Proxy-Authorization must not be sent inside the tunnel";
  28632. client.close();
  28633. EXPECT_EQ(1, proxy.connect_hits());
  28634. }
  28635. #endif