test.cc 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. ctx_t create_client_context();
  75. void set_verify_client(ctx_t ctx, bool require);
  76. session_t create_session(ctx_t ctx, socket_t sock);
  77. void free_session(session_t session);
  78. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  79. time_t timeout_usec, TlsError *err,
  80. const std::function<bool()> &interrupted);
  81. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  82. time_t timeout_usec, TlsError *err,
  83. const std::function<bool()> &interrupted);
  84. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  85. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  86. void shutdown(session_t session, bool graceful);
  87. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  88. namespace impl {
  89. SecTrustSettingsResult
  90. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  91. } // namespace impl
  92. #endif
  93. } // namespace tls
  94. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  95. namespace detail {
  96. bool ssl_free_buffers_is_safe(unsigned long version);
  97. } // namespace detail
  98. #endif
  99. } // namespace httplib
  100. #endif
  101. using namespace std;
  102. using namespace httplib;
  103. const char *HOST = "localhost";
  104. static int get_base_port() {
  105. const char *shard = getenv("GTEST_SHARD_INDEX");
  106. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  107. }
  108. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  109. // New standalone tests MUST use svr.bind_to_any_port() instead.
  110. const int PORT = get_base_port();
  111. const string LONG_QUERY_VALUE = string(25000, '@');
  112. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  113. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  114. const string TOO_LONG_QUERY_URL =
  115. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  116. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  117. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  118. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  119. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  120. return file.name == key;
  121. });
  122. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  123. return *it;
  124. #else
  125. if (it != items.end()) { return *it; }
  126. throw std::runtime_error("invalid multipart form data name error");
  127. #endif
  128. }
  129. static void read_file(const std::string &path, std::string &out) {
  130. std::ifstream fs(path, std::ios_base::binary);
  131. if (!fs) {
  132. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  133. return;
  134. #else
  135. throw std::runtime_error("File not found: " + path);
  136. #endif
  137. }
  138. fs.seekg(0, std::ios_base::end);
  139. auto size = fs.tellg();
  140. fs.seekg(0);
  141. out.resize(static_cast<size_t>(size));
  142. fs.read(&out[0], static_cast<std::streamsize>(size));
  143. }
  144. // Failures of the services that the *_Online tests reach, unrelated to the
  145. // client under test: httpbingo.org intermittently answers with gateway errors,
  146. // and badssl.com drops connections from CI runners before it sends its
  147. // certificate. A handshake that fails before any verdict on the certificate is
  148. // left to the tests against local servers.
  149. static bool is_service_failure(const Result &res) {
  150. if (res) {
  151. return res->status == StatusCode::BadGateway_502 ||
  152. res->status == StatusCode::ServiceUnavailable_503 ||
  153. res->status == StatusCode::GatewayTimeout_504;
  154. }
  155. return res.error() == Error::SSLConnection;
  156. }
  157. template <typename F> static Result retry_service_failures(F &&send) {
  158. auto res = send();
  159. for (auto wait : {1, 2}) {
  160. if (!is_service_failure(res)) { break; }
  161. std::this_thread::sleep_for(std::chrono::seconds(wait));
  162. res = send();
  163. }
  164. return res;
  165. }
  166. #define SKIP_ON_SERVICE_FAILURE(res) \
  167. do { \
  168. if (is_service_failure(res)) { \
  169. if (res) { \
  170. GTEST_SKIP() << "service failure: status " << (res)->status; \
  171. } else { \
  172. GTEST_SKIP() << "service failure: " << to_string((res).error()); \
  173. } \
  174. } \
  175. } while (0)
  176. class UnixSocketTest : public ::testing::Test {
  177. protected:
  178. void TearDown() override { std::remove(pathname_.c_str()); }
  179. void client_GET(const std::string &addr) {
  180. httplib::Client cli{addr};
  181. cli.set_address_family(AF_UNIX);
  182. ASSERT_TRUE(cli.is_valid());
  183. const auto &result = cli.Get(pattern_);
  184. ASSERT_TRUE(result) << "error: " << result.error();
  185. const auto &resp = result.value();
  186. EXPECT_EQ(resp.status, StatusCode::OK_200);
  187. EXPECT_EQ(resp.body, content_);
  188. }
  189. static std::string make_sock_path() {
  190. const char *shard = getenv("GTEST_SHARD_INDEX");
  191. return shard ? std::string("./httplib-server-") + shard + ".sock"
  192. : "./httplib-server.sock";
  193. }
  194. const std::string pathname_{make_sock_path()};
  195. const std::string pattern_{"/hi"};
  196. const std::string content_{"Hello World!"};
  197. };
  198. TEST_F(UnixSocketTest, pathname) {
  199. httplib::Server svr;
  200. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  201. res.set_content(content_, "text/plain");
  202. });
  203. std::thread t{[&] {
  204. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  205. }};
  206. auto se = detail::scope_exit([&] {
  207. svr.stop();
  208. t.join();
  209. ASSERT_FALSE(svr.is_running());
  210. });
  211. svr.wait_until_ready();
  212. ASSERT_TRUE(svr.is_running());
  213. client_GET(pathname_);
  214. // ".//x.sock", which is not taken for a URL
  215. client_GET("./" + pathname_.substr(1));
  216. }
  217. #if defined(__linux__) || \
  218. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  219. TEST_F(UnixSocketTest, PeerPid) {
  220. httplib::Server svr;
  221. std::string remote_port_val;
  222. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  223. res.set_content(content_, "text/plain");
  224. remote_port_val = std::to_string(req.remote_port);
  225. });
  226. std::thread t{[&] {
  227. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  228. }};
  229. auto se = detail::scope_exit([&] {
  230. svr.stop();
  231. t.join();
  232. ASSERT_FALSE(svr.is_running());
  233. });
  234. svr.wait_until_ready();
  235. ASSERT_TRUE(svr.is_running());
  236. client_GET(pathname_);
  237. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  238. }
  239. #endif
  240. #ifdef __linux__
  241. TEST_F(UnixSocketTest, abstract) {
  242. constexpr char svr_path[]{"\x00httplib-server.sock"};
  243. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  244. httplib::Server svr;
  245. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  246. res.set_content(content_, "text/plain");
  247. });
  248. std::thread t{[&] {
  249. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  250. }};
  251. auto se = detail::scope_exit([&] {
  252. svr.stop();
  253. t.join();
  254. ASSERT_FALSE(svr.is_running());
  255. });
  256. svr.wait_until_ready();
  257. ASSERT_TRUE(svr.is_running());
  258. client_GET(abstract_addr);
  259. }
  260. #endif
  261. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  262. httplib::Server svr;
  263. std::string received_host_header;
  264. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  265. // Capture the Host header sent by the client
  266. auto host_iter = req.headers.find("Host");
  267. if (host_iter != req.headers.end()) {
  268. received_host_header = host_iter->second;
  269. }
  270. res.set_content(content_, "text/plain");
  271. });
  272. std::thread t{[&] {
  273. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  274. }};
  275. auto se = detail::scope_exit([&] {
  276. svr.stop();
  277. t.join();
  278. ASSERT_FALSE(svr.is_running());
  279. });
  280. svr.wait_until_ready();
  281. ASSERT_TRUE(svr.is_running());
  282. // Test that Host header is automatically set to "localhost" for Unix socket
  283. // connections
  284. httplib::Client cli{pathname_};
  285. cli.set_address_family(AF_UNIX);
  286. ASSERT_TRUE(cli.is_valid());
  287. const auto &result = cli.Get(pattern_);
  288. ASSERT_TRUE(result) << "error: " << result.error();
  289. const auto &resp = result.value();
  290. EXPECT_EQ(resp.status, StatusCode::OK_200);
  291. EXPECT_EQ(resp.body, content_);
  292. // Verify that Host header was automatically set to "localhost"
  293. EXPECT_EQ(received_host_header, "localhost");
  294. }
  295. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  296. // Another socket in the working directory, which a Location can name as
  297. // its host
  298. const auto other_path = "other-" + pathname_.substr(2);
  299. httplib::Server svr;
  300. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  301. // An absolute Location naming the Host this client sends
  302. res.set_redirect("http://localhost" + pattern_);
  303. });
  304. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  305. res.set_redirect("http://" + other_path + pattern_);
  306. });
  307. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  308. res.set_redirect("http://mapped.test" + pattern_);
  309. });
  310. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  311. res.set_header("X-Auth", req.get_header_value("Authorization"));
  312. res.set_content(content_, "text/plain");
  313. });
  314. httplib::Server other;
  315. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  316. res.set_content("other", "text/plain");
  317. });
  318. std::thread t{[&] {
  319. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  320. }};
  321. std::thread t2{[&] {
  322. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  323. }};
  324. auto se = detail::scope_exit([&] {
  325. svr.stop();
  326. other.stop();
  327. t.join();
  328. t2.join();
  329. std::remove(other_path.c_str());
  330. });
  331. svr.wait_until_ready();
  332. other.wait_until_ready();
  333. httplib::Client cli{pathname_};
  334. cli.set_address_family(AF_UNIX);
  335. cli.set_follow_location(true);
  336. cli.set_bearer_token_auth("token");
  337. // Another host: the same socket, without the credentials
  338. auto res = cli.Get("/cross");
  339. ASSERT_TRUE(res) << "error: " << res.error();
  340. EXPECT_EQ(StatusCode::OK_200, res->status);
  341. EXPECT_EQ(content_, res->body);
  342. EXPECT_EQ("", res->get_header_value("X-Auth"));
  343. // localhost is this client's own host
  344. res = cli.Get("/redirect");
  345. ASSERT_TRUE(res) << "error: " << res.error();
  346. EXPECT_EQ(StatusCode::OK_200, res->status);
  347. EXPECT_EQ(content_, res->body);
  348. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  349. // A host the caller mapped to a socket goes there
  350. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  351. res = cli.Get("/mapped");
  352. ASSERT_TRUE(res) << "error: " << res.error();
  353. EXPECT_EQ(StatusCode::OK_200, res->status);
  354. EXPECT_EQ("other", res->body);
  355. }
  356. #ifndef _WIN32
  357. TEST(SocketStream, wait_writable_UNIX) {
  358. int fds[2];
  359. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  360. const auto asSocketStream = [&](socket_t fd,
  361. std::function<bool(Stream &)> func) {
  362. return detail::process_client_socket(
  363. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  364. };
  365. asSocketStream(fds[0], [&](Stream &s0) {
  366. EXPECT_EQ(s0.socket(), fds[0]);
  367. EXPECT_TRUE(s0.wait_writable());
  368. EXPECT_TRUE(s0.is_peer_alive());
  369. EXPECT_EQ(0, close(fds[1]));
  370. EXPECT_FALSE(s0.is_peer_alive());
  371. return true;
  372. });
  373. EXPECT_EQ(0, close(fds[0]));
  374. }
  375. TEST(SocketStream, wait_writable_INET) {
  376. sockaddr_in addr;
  377. memset(&addr, 0, sizeof(addr));
  378. addr.sin_family = AF_INET;
  379. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  380. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  381. int disconnected_svr_sock = -1;
  382. std::thread svr{[&] {
  383. const int s = socket(AF_INET, SOCK_STREAM, 0);
  384. ASSERT_LE(0, s);
  385. // PORT + 1 is shared with the SSL redirect tests and with
  386. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  387. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  388. // because that happens on a worker thread the ASSERT does not stop the
  389. // test: it runs on and fails at the disconnected_svr_sock check instead.
  390. default_socket_options(s);
  391. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  392. ASSERT_EQ(0, listen(s, 1));
  393. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  394. ASSERT_EQ(0, close(s));
  395. }};
  396. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  397. std::thread cli{[&] {
  398. const int s = socket(AF_INET, SOCK_STREAM, 0);
  399. ASSERT_LE(0, s);
  400. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  401. ASSERT_EQ(0, close(s));
  402. }};
  403. cli.join();
  404. svr.join();
  405. ASSERT_NE(disconnected_svr_sock, -1);
  406. const auto asSocketStream = [&](socket_t fd,
  407. std::function<bool(Stream &)> func) {
  408. return detail::process_client_socket(
  409. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  410. };
  411. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  412. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  413. // wait_writable() returns true because select_write() only checks if the
  414. // send buffer has space. Peer disconnection is detected later by send().
  415. EXPECT_TRUE(ss.wait_writable());
  416. return true;
  417. });
  418. ASSERT_EQ(0, close(disconnected_svr_sock));
  419. }
  420. #endif // #ifndef _WIN32
  421. TEST(SetSocketOptTest, TcpNoDelay) {
  422. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  423. ASSERT_NE(sock, INVALID_SOCKET);
  424. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  425. int val = 0;
  426. socklen_t len = sizeof(val);
  427. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  428. reinterpret_cast<char *>(&val), &len));
  429. EXPECT_NE(val, 0);
  430. detail::close_socket(sock);
  431. }
  432. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  433. // accept() reports failures through WSAGetLastError() on Windows and through
  434. // errno everywhere else. Asking the wrong one is what made the accept loop
  435. // treat every recoverable failure as fatal on Windows.
  436. struct Classification {
  437. bool resource;
  438. bool transient;
  439. };
  440. auto classify = [](int err) {
  441. #ifdef _WIN32
  442. WSASetLastError(err);
  443. #else
  444. errno = err;
  445. #endif
  446. // Read both before asserting: an assertion may clobber the error slot.
  447. Classification c;
  448. c.resource = detail::is_accept_resource_error();
  449. c.transient = detail::is_accept_transient_error();
  450. return c;
  451. };
  452. #ifdef _WIN32
  453. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  454. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  455. WSAECONNRESET, WSAECONNABORTED};
  456. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  457. #else
  458. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  459. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  460. ECONNABORTED};
  461. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  462. #endif
  463. for (auto err : resource_errors) {
  464. const auto c = classify(err);
  465. EXPECT_TRUE(c.resource) << "error " << err;
  466. EXPECT_FALSE(c.transient) << "error " << err;
  467. }
  468. for (auto err : transient_errors) {
  469. const auto c = classify(err);
  470. EXPECT_TRUE(c.transient) << "error " << err;
  471. EXPECT_FALSE(c.resource) << "error " << err;
  472. }
  473. for (auto err : fatal_errors) {
  474. const auto c = classify(err);
  475. EXPECT_FALSE(c.resource) << "error " << err;
  476. EXPECT_FALSE(c.transient) << "error " << err;
  477. }
  478. #ifdef _WIN32
  479. WSASetLastError(0);
  480. #else
  481. errno = 0;
  482. #endif
  483. }
  484. TEST(ClientTest, MoveConstructible) {
  485. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  486. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  487. }
  488. TEST(ClientTest, MoveAssignable) {
  489. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  490. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  491. }
  492. #ifdef _WIN32
  493. TEST(StartupTest, WSAStartup) {
  494. WSADATA wsaData;
  495. int ret = WSAStartup(0x0002, &wsaData);
  496. ASSERT_EQ(0, ret);
  497. }
  498. #endif
  499. TEST(DecodePathTest, PercentCharacter) {
  500. EXPECT_EQ(
  501. decode_path_component(
  502. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  503. U8("descrip=Gastos áéíóúñÑ 6"));
  504. }
  505. TEST(DecodePathTest, PercentCharacterNUL) {
  506. string expected;
  507. expected.push_back('x');
  508. expected.push_back('\0');
  509. expected.push_back('x');
  510. EXPECT_EQ(decode_path_component("x%00x"), expected);
  511. }
  512. TEST(DecodePathTest, UnicodeEncoding) {
  513. // %u0041 = 'A' (1-byte UTF-8)
  514. EXPECT_EQ("A", decode_path_component("%u0041"));
  515. // %u00E9 = 'é' (2-byte UTF-8)
  516. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  517. // %u3042 = 'あ' (3-byte UTF-8)
  518. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  519. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  520. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  521. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  522. // neighbours)
  523. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  524. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  525. }
  526. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  527. // A sign or whitespace inside the two-character escape window must not be
  528. // accepted as a valid percent-encoding; the sequence is passed through
  529. // literally, matching decode_uri_component / decode_path_component.
  530. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  531. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  532. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  533. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  534. // Well-formed escapes still decode.
  535. EXPECT_EQ("-", decode_query_component("%2D", false));
  536. EXPECT_EQ("A", decode_query_component("%41", false));
  537. }
  538. TEST(SanitizeFilenameTest, VariousPatterns) {
  539. // Path traversal
  540. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  541. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  542. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  543. // Normal and edge cases
  544. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  545. EXPECT_EQ("filename.txt",
  546. httplib::sanitize_filename("/path/to/filename.txt"));
  547. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  548. EXPECT_EQ("", httplib::sanitize_filename(".."));
  549. EXPECT_EQ("", httplib::sanitize_filename(""));
  550. // Null bytes stripped
  551. EXPECT_EQ("safe.txt",
  552. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  553. // Whitespace-only rejected
  554. EXPECT_EQ("", httplib::sanitize_filename(" "));
  555. }
  556. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  557. // before it is dropped; anywhere else it is an ordinary file name character.
  558. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  559. #ifdef _WIN32
  560. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  561. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  562. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  563. #else
  564. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  565. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  566. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  567. #endif
  568. }
  569. // Forward declaration (see the base64_encode note below): split builds move the
  570. // definition into httplib.cc, so re-declaring it here lets the test link.
  571. namespace httplib {
  572. namespace detail {
  573. bool is_chunked_transfer_encoding(const Headers &headers);
  574. } // namespace detail
  575. } // namespace httplib
  576. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  577. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  578. auto make = [](std::initializer_list<const char *> lines) {
  579. Headers h;
  580. for (auto te : lines) {
  581. if (te) { h.emplace("Transfer-Encoding", te); }
  582. }
  583. return h;
  584. };
  585. // Sole coding, matched case-insensitively.
  586. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  587. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  588. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  589. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  590. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  591. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  592. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  593. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  594. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  595. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  596. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  597. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  598. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  599. // were received, into one list. Headers preserves that order, so the answer
  600. // is decided by the last coding of the last line and the order the lines
  601. // arrived in is significant.
  602. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  603. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  604. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  605. // The split can fall anywhere in the list.
  606. EXPECT_TRUE(
  607. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  608. EXPECT_FALSE(
  609. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  610. // A trailing line naming no coding leaves the list ending in nothing, so it
  611. // must not inherit the chunked from the line before it.
  612. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  613. }
  614. // Forward declarations (see the base64_encode note below).
  615. namespace httplib {
  616. namespace detail {
  617. bool parse_status_line(const char *line, std::string &version, int &status,
  618. std::string &reason);
  619. std::string file_extension(const std::string &path);
  620. std::string
  621. find_content_type(const std::string &path,
  622. const std::map<std::string, std::string> &user_data,
  623. const std::string &default_content_type);
  624. bool can_compress_content_type(const std::string &content_type);
  625. bool is_prohibited_header_name(const std::string &name);
  626. bool is_valid_path(const std::string &path);
  627. #ifdef CPPHTTPLIB_SSL_ENABLED
  628. bool match_hostname(const std::string &pattern, const std::string &hostname);
  629. #endif
  630. } // namespace detail
  631. } // namespace httplib
  632. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  633. struct {
  634. const char *line;
  635. const char *version;
  636. int status;
  637. const char *reason;
  638. } cases[] = {
  639. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  640. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  641. // The reason phrase may be empty, or left out along with its space.
  642. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  643. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  644. };
  645. for (const auto &c : cases) {
  646. std::string version;
  647. int status = 0;
  648. std::string reason = "unset";
  649. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  650. << c.line;
  651. EXPECT_EQ(c.version, version);
  652. EXPECT_EQ(c.status, status);
  653. EXPECT_EQ(c.reason, reason);
  654. }
  655. }
  656. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  657. const char *lines[] = {
  658. "HTTP/2 200 OK\r\n",
  659. "HTTP/1.2 200 OK\r\n",
  660. "HTTP/1.1 20 OK\r\n",
  661. "HTTP/1.1 2000 OK\r\n",
  662. "HTTP/1.1 2x0 OK\r\n",
  663. "HTTP/1.1 200 OK\r\n",
  664. "HTTP/1.1 200OK\r\n",
  665. "HTTP/1.1 200 O\rK\r\n",
  666. "HTTP/1.1 200 OK",
  667. "HTTP/1.1 200 OK\r\nX",
  668. "",
  669. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  670. "HTTP/1.1 200 OK\n",
  671. #endif
  672. };
  673. for (auto line : lines) {
  674. std::string version;
  675. int status = 0;
  676. std::string reason;
  677. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  678. << line;
  679. }
  680. }
  681. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  682. // Long enough to overflow the stack when matched with std::regex.
  683. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  684. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  685. std::string version;
  686. int status = 0;
  687. std::string reason;
  688. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  689. EXPECT_EQ(200, status);
  690. EXPECT_EQ(long_reason, reason);
  691. }
  692. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  693. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  694. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  695. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  696. EXPECT_EQ("", detail::file_extension("noext"));
  697. EXPECT_EQ("", detail::file_extension("a."));
  698. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  699. EXPECT_EQ("", detail::file_extension("a.b-c"));
  700. // Long enough to overflow the stack when matched with std::regex.
  701. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  702. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  703. }
  704. #ifdef CPPHTTPLIB_SSL_ENABLED
  705. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  706. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  707. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  708. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  709. // A wildcard needs two labels after it, in the leftmost label only
  710. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  711. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  712. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  713. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  714. EXPECT_FALSE(
  715. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  716. // No name may have an empty label
  717. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  718. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  719. }
  720. #endif
  721. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  722. detail::case_ignore::hash hash;
  723. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  724. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  725. // Long enough to overflow the stack if hashed one call per character.
  726. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  727. }
  728. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  729. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  730. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  731. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  732. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  733. // Same 26-bit hash as html, svg and js.
  734. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  735. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  736. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  737. }
  738. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  739. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  740. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  741. }
  742. }
  743. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  744. // name anywhere else.
  745. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  746. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  747. #ifdef _WIN32
  748. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  749. #else
  750. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  751. #endif
  752. }
  753. }
  754. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  755. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  756. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  757. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  758. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  759. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  760. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  761. // Same 26-bit hash as application/json.
  762. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  763. }
  764. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  765. Request req;
  766. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  767. EXPECT_TRUE(req.is_multipart_form_data());
  768. std::string boundary;
  769. EXPECT_TRUE(detail::parse_multipart_boundary(
  770. req.get_header_value("Content-Type"), boundary));
  771. EXPECT_EQ("x", boundary);
  772. }
  773. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  774. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  775. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  776. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  777. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  778. // Same 26-bit hash as REMOTE_ADDR.
  779. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  780. }
  781. // Forward declaration: in split builds split.py strips `inline` and moves the
  782. // definition into httplib.cc, so detail::base64_encode is not visible from the
  783. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  784. // in both header-only and split builds.
  785. namespace httplib {
  786. namespace detail {
  787. std::string base64_encode(const std::string &in);
  788. } // namespace detail
  789. } // namespace httplib
  790. TEST(Base64EncodeTest, KnownAnswers) {
  791. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  792. // where the accumulator's top bit is already set before the next shift.
  793. EXPECT_EQ("", detail::base64_encode(""));
  794. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  795. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  796. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  797. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  798. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  799. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  800. // High bytes keep the top bit set across several rounds.
  801. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  802. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  803. }
  804. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  805. string unescapedCharacters = "-_.!~*'()";
  806. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  807. }
  808. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  809. string reservedCharacters = ";,/?:@&=+$";
  810. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  811. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  812. }
  813. TEST(ClientQueryOrder, PreserveOrder) {
  814. // This test reproduces Issue #2259: client may reorder query parameters
  815. // when sending a GET request. The expected behavior is that the client
  816. // preserves the original query string order when the caller supplied it
  817. // as part of the path.
  818. Server svr;
  819. svr.Get("/", [&](const Request &req, Response &res) {
  820. // Echo back the raw target so the test can assert ordering
  821. res.set_content(req.target, "text/plain");
  822. });
  823. std::thread t{[&] { svr.listen(HOST, PORT); }};
  824. auto se = detail::scope_exit([&] {
  825. svr.stop();
  826. t.join();
  827. ASSERT_FALSE(svr.is_running());
  828. });
  829. svr.wait_until_ready();
  830. Client cli(HOST, PORT);
  831. ASSERT_TRUE(cli.is_valid());
  832. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  833. auto res = cli.Get(original);
  834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  835. // Expect the echoed target to exactly match the original path (order
  836. // preserved)
  837. EXPECT_EQ(res->body, original);
  838. }
  839. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  840. string chineseCharacters = U8("中国語");
  841. string russianCharacters = U8("дом");
  842. string brazilianCharacters = U8("óculos");
  843. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  844. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  845. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  846. "%D0%B4%D0%BE%D0%BC");
  847. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  848. }
  849. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  850. string unescapedCharacters = "-_.!~*'()";
  851. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  852. }
  853. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  854. string reservedCharacters = ";,/?:@&=+$";
  855. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  856. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  857. }
  858. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  859. string chineseCharacters = U8("中国語");
  860. string russianCharacters = U8("дом");
  861. string brazilianCharacters = U8("óculos");
  862. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  863. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  864. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  865. "%D0%B4%D0%BE%D0%BC");
  866. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  867. }
  868. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  869. // Issue #2082 use case: encoding path component with ampersand
  870. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  871. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  872. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  873. }
  874. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  875. string unescapedCharacters = "-_.!~*'()";
  876. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  877. }
  878. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  879. string reservedCharacters = ";,/?:@&=+$#";
  880. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  881. }
  882. TEST(EncodeUriTest, TestUTF8Characters) {
  883. string chineseCharacters = U8("中国語");
  884. string russianCharacters = U8("дом");
  885. string brazilianCharacters = U8("óculos");
  886. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  887. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  888. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  889. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  890. }
  891. TEST(EncodeUriTest, TestCompleteUri) {
  892. string uri =
  893. "https://example.com/path/to/resource?query=value&param=test#fragment";
  894. EXPECT_EQ(
  895. httplib::encode_uri(uri),
  896. "https://example.com/path/to/resource?query=value&param=test#fragment");
  897. }
  898. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  899. string uri =
  900. "https://example.com/path with spaces/file name.html?q=hello world";
  901. EXPECT_EQ(httplib::encode_uri(uri),
  902. "https://example.com/path%20with%20spaces/"
  903. "file%20name.html?q=hello%20world");
  904. }
  905. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  906. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  907. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  908. }
  909. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  910. string unescapedCharacters = "-_.!~*'()";
  911. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  912. }
  913. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  914. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  915. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  916. string encodedBrazilian = "%C3%B3culos";
  917. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  918. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  919. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  920. }
  921. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  922. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  923. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  924. "Piri Tommy Villiers - on & on");
  925. }
  926. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  927. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  928. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  929. }
  930. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  931. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  932. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  933. }
  934. TEST(DecodeUriTest, TestUTF8Characters) {
  935. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  936. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  937. string encodedBrazilian = "%C3%B3culos";
  938. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  939. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  940. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  941. }
  942. TEST(DecodeUriTest, TestCompleteUri) {
  943. string encodedUri = "https://example.com/path%20with%20spaces/"
  944. "file%20name.html?q=hello%20world";
  945. EXPECT_EQ(
  946. httplib::decode_uri(encodedUri),
  947. "https://example.com/path with spaces/file name.html?q=hello world");
  948. }
  949. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  950. string original =
  951. "https://example.com/path with spaces/file name.html?q=hello world";
  952. string encoded = httplib::encode_uri(original);
  953. string decoded = httplib::decode_uri(encoded);
  954. EXPECT_EQ(decoded, original);
  955. }
  956. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  957. // decode_uri is the inverse of encode_uri: an escaped reserved character
  958. // stays encoded so it is not promoted into a real delimiter, while
  959. // non-reserved escapes still decode (like JS decodeURI).
  960. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  961. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  962. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  963. "%3F%3A%40%26%3D%2B%24%2C%3B");
  964. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  965. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  966. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  967. "http://example.com/a%2Fb");
  968. // decode_uri_component still decodes the reserved character.
  969. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  970. }
  971. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  972. string original = "Piri Tommy Villiers - on & on";
  973. string encoded = httplib::encode_uri_component(original);
  974. string decoded = httplib::decode_uri_component(encoded);
  975. EXPECT_EQ(decoded, original);
  976. }
  977. TEST(TrimTests, TrimStringTests) {
  978. EXPECT_EQ("abc", detail::trim_copy("abc"));
  979. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  980. EXPECT_TRUE(detail::trim_copy("").empty());
  981. }
  982. TEST(AsciiTest, LocaleIndependentClassification) {
  983. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  984. // which consult the global C locale: std::isalnum(0xC5) can return true
  985. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  986. // helpers must classify every byte by the ASCII grammar alone.
  987. for (int i = 0; i < 256; i++) {
  988. auto c = static_cast<char>(i);
  989. auto is_digit = i >= '0' && i <= '9';
  990. auto is_upper = i >= 'A' && i <= 'Z';
  991. auto is_lower = i >= 'a' && i <= 'z';
  992. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  993. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  994. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  995. << "byte " << i;
  996. }
  997. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  998. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  999. // Non-ASCII bytes must be percent-encoded, never passed through as
  1000. // alphanumeric.
  1001. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  1002. }
  1003. TEST(FromCharsTest, Double) {
  1004. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  1005. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  1006. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  1007. auto parse = [](const std::string &s, double &v) {
  1008. return detail::from_chars(s.data(), s.data() + s.size(), v);
  1009. };
  1010. double v = -1.0;
  1011. // Representative quality values.
  1012. EXPECT_EQ(parse("0", v).ec, std::errc{});
  1013. EXPECT_DOUBLE_EQ(v, 0.0);
  1014. EXPECT_EQ(parse("1", v).ec, std::errc{});
  1015. EXPECT_DOUBLE_EQ(v, 1.0);
  1016. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  1017. EXPECT_DOUBLE_EQ(v, 0.8);
  1018. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  1019. EXPECT_DOUBLE_EQ(v, 0.001);
  1020. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  1021. EXPECT_DOUBLE_EQ(v, 1.0);
  1022. // A missing integer or fractional part is tolerated.
  1023. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  1024. EXPECT_DOUBLE_EQ(v, 0.5);
  1025. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  1026. EXPECT_DOUBLE_EQ(v, 5.0);
  1027. // Values outside [0, 1] still parse; the caller range-checks them.
  1028. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  1029. EXPECT_DOUBLE_EQ(v, 123.456);
  1030. // Stops at the first byte that is not part of the number and reports where.
  1031. std::string trailing = "0.9, text/html";
  1032. auto r = parse(trailing, v);
  1033. EXPECT_EQ(r.ec, std::errc{});
  1034. EXPECT_DOUBLE_EQ(v, 0.9);
  1035. EXPECT_EQ(*r.ptr, ',');
  1036. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  1037. // outright, and an 'e'/'E' simply ends the number.
  1038. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  1039. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  1040. std::string exp_input = "1.5e3";
  1041. r = parse(exp_input, v);
  1042. EXPECT_EQ(r.ec, std::errc{});
  1043. EXPECT_DOUBLE_EQ(v, 1.5);
  1044. EXPECT_EQ(*r.ptr, 'e');
  1045. // Invalid inputs.
  1046. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1047. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1048. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1049. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1050. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1051. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1052. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1053. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1054. std::errc{});
  1055. EXPECT_DOUBLE_EQ(v, 0.0);
  1056. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1057. std::errc{});
  1058. EXPECT_GE(v, 0.0);
  1059. EXPECT_LE(v, 1.0);
  1060. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1061. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1062. }
  1063. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1064. // Simple case without quality values
  1065. std::vector<std::string> result1;
  1066. EXPECT_TRUE(detail::parse_accept_header(
  1067. "text/html,application/json,text/plain", result1));
  1068. EXPECT_EQ(result1.size(), 3U);
  1069. EXPECT_EQ(result1[0], "text/html");
  1070. EXPECT_EQ(result1[1], "application/json");
  1071. EXPECT_EQ(result1[2], "text/plain");
  1072. // With quality values
  1073. std::vector<std::string> result2;
  1074. EXPECT_TRUE(detail::parse_accept_header(
  1075. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1076. EXPECT_EQ(result2.size(), 3U);
  1077. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1078. EXPECT_EQ(result2[1], "text/html");
  1079. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1080. }
  1081. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1082. // Mixed with and without quality values
  1083. std::vector<std::string> result;
  1084. EXPECT_TRUE(detail::parse_accept_header(
  1085. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1086. EXPECT_EQ(result.size(), 3U);
  1087. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1088. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1089. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1090. }
  1091. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1092. // Empty header
  1093. std::vector<std::string> empty_result;
  1094. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1095. EXPECT_TRUE(empty_result.empty());
  1096. // Single type
  1097. std::vector<std::string> single_result;
  1098. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1099. EXPECT_EQ(single_result.size(), 1U);
  1100. EXPECT_EQ(single_result[0], "application/json");
  1101. // Wildcard types
  1102. std::vector<std::string> wildcard_result;
  1103. EXPECT_TRUE(detail::parse_accept_header(
  1104. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1105. EXPECT_EQ(wildcard_result.size(), 3U);
  1106. EXPECT_EQ(wildcard_result[0], "application/json");
  1107. EXPECT_EQ(wildcard_result[1], "text/*");
  1108. EXPECT_EQ(wildcard_result[2], "*/*");
  1109. }
  1110. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1111. // Common browser Accept header
  1112. std::vector<std::string> browser_result;
  1113. EXPECT_TRUE(
  1114. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1115. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1116. browser_result));
  1117. EXPECT_EQ(browser_result.size(), 6U);
  1118. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1119. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1120. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1121. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1122. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1123. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1124. // API client header
  1125. std::vector<std::string> api_result;
  1126. EXPECT_TRUE(detail::parse_accept_header(
  1127. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1128. api_result));
  1129. EXPECT_EQ(api_result.size(), 3U);
  1130. EXPECT_EQ(api_result[0], "application/json");
  1131. EXPECT_EQ(api_result[1], "application/xml");
  1132. EXPECT_EQ(api_result[2], "text/plain");
  1133. }
  1134. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1135. // Quality value with 3 decimal places
  1136. std::vector<std::string> decimal_result;
  1137. EXPECT_TRUE(detail::parse_accept_header(
  1138. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1139. EXPECT_EQ(decimal_result.size(), 2U);
  1140. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1141. EXPECT_EQ(decimal_result[1], "text/html");
  1142. // Zero quality (should still be included but with lowest priority)
  1143. std::vector<std::string> zero_q_result;
  1144. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1145. zero_q_result));
  1146. EXPECT_EQ(zero_q_result.size(), 2U);
  1147. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1148. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1149. // No spaces around commas
  1150. std::vector<std::string> no_space_result;
  1151. EXPECT_TRUE(detail::parse_accept_header(
  1152. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1153. no_space_result));
  1154. EXPECT_EQ(no_space_result.size(), 3U);
  1155. EXPECT_EQ(no_space_result[0], "text/html");
  1156. EXPECT_EQ(no_space_result[1], "application/json");
  1157. EXPECT_EQ(no_space_result[2], "text/plain");
  1158. }
  1159. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1160. // Quality values always use '.' as the decimal separator, so parsing must
  1161. // not depend on the process locale. An embedding application may have
  1162. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1163. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1164. std::string saved = cur ? cur : "C";
  1165. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1166. "fr_FR.UTF-8"};
  1167. bool switched = false;
  1168. for (const auto loc : comma_locales) {
  1169. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1170. std::localeconv()->decimal_point[0] == ',') {
  1171. switched = true;
  1172. break;
  1173. }
  1174. }
  1175. if (!switched) {
  1176. std::setlocale(LC_NUMERIC, saved.c_str());
  1177. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1178. }
  1179. // The higher-weighted type appears later in the list, so a correct parse
  1180. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1181. // sensitive parse reads both weights as 0 and leaves the original order.
  1182. std::vector<std::string> result;
  1183. EXPECT_TRUE(detail::parse_accept_header(
  1184. "application/json;q=0.1,text/html;q=0.9", result));
  1185. ASSERT_EQ(result.size(), 2U);
  1186. EXPECT_EQ(result[0], "text/html");
  1187. EXPECT_EQ(result[1], "application/json");
  1188. std::setlocale(LC_NUMERIC, saved.c_str());
  1189. }
  1190. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1191. std::vector<std::string> result;
  1192. // Invalid quality value (> 1.0)
  1193. EXPECT_FALSE(
  1194. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1195. // Invalid quality value (< 0.0)
  1196. EXPECT_FALSE(
  1197. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1198. // Invalid quality value (not a number)
  1199. EXPECT_FALSE(detail::parse_accept_header(
  1200. "text/html;q=invalid,application/json", result));
  1201. // A valid numeric prefix does not make the entire quality value valid.
  1202. EXPECT_FALSE(detail::parse_accept_header(
  1203. "text/html;q=0.5junk,application/json", result));
  1204. // Empty quality value
  1205. EXPECT_FALSE(
  1206. detail::parse_accept_header("text/html;q=,application/json", result));
  1207. // Invalid media type format (no slash and not wildcard)
  1208. EXPECT_FALSE(
  1209. detail::parse_accept_header("invalidtype,application/json", result));
  1210. // Valid cases should still work
  1211. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1212. EXPECT_EQ(result.size(), 1U);
  1213. EXPECT_EQ(result[0], "*/*");
  1214. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1215. EXPECT_EQ(result.size(), 1U);
  1216. EXPECT_EQ(result[0], "*");
  1217. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1218. EXPECT_EQ(result.size(), 1U);
  1219. EXPECT_EQ(result[0], "text/*");
  1220. }
  1221. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1222. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1223. // and must not be answered with 400 Bad Request.
  1224. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1225. struct {
  1226. const char *value;
  1227. std::vector<std::string> expected;
  1228. } cases[] = {
  1229. {",application/json", {"application/json"}},
  1230. {"text/html,", {"text/html"}},
  1231. {"text/html,,*/*", {"text/html", "*/*"}},
  1232. // An empty element may be spelled with whitespace in it
  1233. {"text/html, , application/json", {"text/html", "application/json"}},
  1234. // Nothing but empty elements is an empty list, which means the same
  1235. // thing as no Accept header at all
  1236. {",,,", {}},
  1237. // Quality values still apply across ignored empty elements
  1238. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1239. };
  1240. for (const auto &c : cases) {
  1241. std::vector<std::string> result;
  1242. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1243. << "value: " << c.value;
  1244. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1245. }
  1246. // An invalid entry is still rejected when empty elements surround it
  1247. std::vector<std::string> result;
  1248. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1249. }
  1250. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1251. // or ';' inside one does not end the list element or the parameter. Section
  1252. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1253. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1254. struct {
  1255. const char *value;
  1256. std::vector<std::string> expected;
  1257. } cases[] = {
  1258. {"text/html;profile=\"a,b\",application/json",
  1259. {"text/html", "application/json"}},
  1260. // A "q=" inside a quoted value is not the weight
  1261. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1262. {"text/html", "application/json"}},
  1263. // The weight after a quoted value still applies
  1264. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1265. {"application/json", "text/html"}},
  1266. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1267. {"application/json", "text/html"}},
  1268. {"text/html;profile=\"a\\\"b\",application/json",
  1269. {"text/html", "application/json"}},
  1270. // An escaped backslash does not escape the '"' after it
  1271. {"text/html;profile=\"a\\\\\",application/json",
  1272. {"text/html", "application/json"}},
  1273. };
  1274. for (const auto &c : cases) {
  1275. std::vector<std::string> result;
  1276. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1277. << "value: " << c.value;
  1278. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1279. }
  1280. }
  1281. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1282. Server svr;
  1283. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1284. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1285. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1286. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1287. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1288. res.set_content("ok", "text/plain");
  1289. });
  1290. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1291. EXPECT_TRUE(false);
  1292. res.set_content("bad request", "text/plain");
  1293. });
  1294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. listen_thread.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. Client cli("localhost", PORT);
  1302. {
  1303. auto res = cli.Get(
  1304. "/accept_ok",
  1305. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1307. EXPECT_EQ(StatusCode::OK_200, res->status);
  1308. }
  1309. {
  1310. auto res = cli.Get("/accept_bad_request",
  1311. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1313. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1314. }
  1315. }
  1316. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1317. Server svr;
  1318. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1319. res.set_content("ok", "text/plain");
  1320. });
  1321. std::atomic<int> start_count{0};
  1322. std::atomic<bool> running_when_called{false};
  1323. svr.set_start_handler([&]() {
  1324. running_when_called = svr.is_running();
  1325. start_count++;
  1326. });
  1327. auto port = svr.bind_to_any_port(HOST);
  1328. std::thread t([&]() { svr.listen_after_bind(); });
  1329. auto se = detail::scope_exit([&] {
  1330. svr.stop();
  1331. t.join();
  1332. ASSERT_FALSE(svr.is_running());
  1333. });
  1334. svr.wait_until_ready();
  1335. // A successful request proves the accept loop is running, which the start
  1336. // handler precedes; so by now the handler must have run exactly once.
  1337. Client cli(HOST, port);
  1338. cli.set_connection_timeout(std::chrono::seconds(5));
  1339. auto res = cli.Get("/");
  1340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1341. EXPECT_EQ(StatusCode::OK_200, res->status);
  1342. EXPECT_EQ(1, start_count.load());
  1343. EXPECT_TRUE(running_when_called.load());
  1344. }
  1345. TEST(DivideTest, DivideStringTests) {
  1346. auto divide = [](const std::string &str, char d) {
  1347. std::string lhs;
  1348. std::string rhs;
  1349. detail::divide(str, d,
  1350. [&](const char *lhs_data, std::size_t lhs_size,
  1351. const char *rhs_data, std::size_t rhs_size) {
  1352. lhs.assign(lhs_data, lhs_size);
  1353. rhs.assign(rhs_data, rhs_size);
  1354. });
  1355. return std::make_pair(std::move(lhs), std::move(rhs));
  1356. };
  1357. {
  1358. const auto res = divide("", '=');
  1359. EXPECT_EQ(res.first, "");
  1360. EXPECT_EQ(res.second, "");
  1361. }
  1362. {
  1363. const auto res = divide("=", '=');
  1364. EXPECT_EQ(res.first, "");
  1365. EXPECT_EQ(res.second, "");
  1366. }
  1367. {
  1368. const auto res = divide(" ", '=');
  1369. EXPECT_EQ(res.first, " ");
  1370. EXPECT_EQ(res.second, "");
  1371. }
  1372. {
  1373. const auto res = divide("a", '=');
  1374. EXPECT_EQ(res.first, "a");
  1375. EXPECT_EQ(res.second, "");
  1376. }
  1377. {
  1378. const auto res = divide("a=", '=');
  1379. EXPECT_EQ(res.first, "a");
  1380. EXPECT_EQ(res.second, "");
  1381. }
  1382. {
  1383. const auto res = divide("=b", '=');
  1384. EXPECT_EQ(res.first, "");
  1385. EXPECT_EQ(res.second, "b");
  1386. }
  1387. {
  1388. const auto res = divide("a=b", '=');
  1389. EXPECT_EQ(res.first, "a");
  1390. EXPECT_EQ(res.second, "b");
  1391. }
  1392. {
  1393. const auto res = divide("a=b=", '=');
  1394. EXPECT_EQ(res.first, "a");
  1395. EXPECT_EQ(res.second, "b=");
  1396. }
  1397. {
  1398. const auto res = divide("a=b=c", '=');
  1399. EXPECT_EQ(res.first, "a");
  1400. EXPECT_EQ(res.second, "b=c");
  1401. }
  1402. }
  1403. TEST(SplitTest, ParseQueryString) {
  1404. string s = "key1=val1&key2=val2&key3=val3";
  1405. Params dic;
  1406. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1407. [&](const char *b, const char *e) {
  1408. string key, val;
  1409. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1410. if (key.empty()) {
  1411. key.assign(b2, e2);
  1412. } else {
  1413. val.assign(b2, e2);
  1414. }
  1415. });
  1416. dic.emplace(key, val);
  1417. });
  1418. EXPECT_EQ("val1", dic.find("key1")->second);
  1419. EXPECT_EQ("val2", dic.find("key2")->second);
  1420. EXPECT_EQ("val3", dic.find("key3")->second);
  1421. }
  1422. TEST(SplitTest, ParseInvalidQueryTests) {
  1423. {
  1424. string s = " ";
  1425. Params dict;
  1426. detail::parse_query_text(s, dict);
  1427. EXPECT_TRUE(dict.empty());
  1428. }
  1429. {
  1430. string s = " = =";
  1431. Params dict;
  1432. detail::parse_query_text(s, dict);
  1433. EXPECT_TRUE(dict.empty());
  1434. }
  1435. }
  1436. TEST(ParseQueryTest, ParseQueryString) {
  1437. {
  1438. std::string s = "key1=val1&key2=val2&key3=val3";
  1439. Params dic;
  1440. detail::parse_query_text(s, dic);
  1441. EXPECT_EQ("val1", dic.find("key1")->second);
  1442. EXPECT_EQ("val2", dic.find("key2")->second);
  1443. EXPECT_EQ("val3", dic.find("key3")->second);
  1444. }
  1445. {
  1446. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1447. Params dic;
  1448. detail::parse_query_text(s, dic);
  1449. EXPECT_EQ("", dic.find("key1")->second);
  1450. EXPECT_EQ("val1", dic.find("key2")->second);
  1451. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1452. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1453. }
  1454. }
  1455. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1456. Params dic;
  1457. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1458. dic.emplace("key1", "val1");
  1459. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1460. dic.emplace("key2", "val2");
  1461. dic.emplace("key3", "val3");
  1462. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1463. }
  1464. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1465. Params params;
  1466. params.emplace("a", "1");
  1467. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1468. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1469. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1470. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1471. // Long enough to overflow the stack when matched with std::regex.
  1472. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1473. EXPECT_EQ("/p?" + long_query + "&a=1",
  1474. append_query_params("/p?" + long_query, params));
  1475. }
  1476. // Joins every entry of a Headers or Params into "key=value " so a whole
  1477. // traversal can be compared in one assertion. Both are instantiations of the
  1478. // same insertion-ordered container, so one helper serves both.
  1479. template <typename Map> static std::string entries_to_string(const Map &m) {
  1480. std::string s;
  1481. for (const auto &entry : m) {
  1482. s += entry.first + "=" + entry.second + " ";
  1483. }
  1484. return s;
  1485. }
  1486. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1487. // Params used to be a std::multimap, which sorted by name and handed the
  1488. // caller's query back alphabetised. A client signing its query string could
  1489. // not reproduce the order it asked for.
  1490. Params dic;
  1491. dic.emplace("zulu", "1");
  1492. dic.emplace("alpha", "2");
  1493. dic.emplace("mike", "3");
  1494. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1495. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1496. }
  1497. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1498. Params dic;
  1499. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1500. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1501. }
  1502. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1503. Request req;
  1504. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1505. req.params);
  1506. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1507. EXPECT_EQ("first", req.get_param_value("tag"));
  1508. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1509. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1510. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1511. EXPECT_EQ("", req.get_param_value("tag", 3));
  1512. }
  1513. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1514. // Params shares its container with Headers, which matches field names
  1515. // case-insensitively. Parameter names must not pick that up.
  1516. Params dic;
  1517. dic.emplace("Key", "upper");
  1518. dic.emplace("key", "lower");
  1519. EXPECT_EQ(2U, dic.size());
  1520. EXPECT_EQ(1U, dic.count("Key"));
  1521. EXPECT_EQ(1U, dic.count("key"));
  1522. EXPECT_EQ("upper", dic.find("Key")->second);
  1523. EXPECT_EQ("lower", dic.find("key")->second);
  1524. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1525. }
  1526. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1527. Server svr;
  1528. std::string order;
  1529. svr.Get("/order", [&](const Request &req, Response &res) {
  1530. order = entries_to_string(req.params);
  1531. res.set_content("ok", "text/plain");
  1532. });
  1533. auto port = svr.bind_to_any_port(HOST);
  1534. thread t = thread([&] { svr.listen_after_bind(); });
  1535. auto se = detail::scope_exit([&] {
  1536. svr.stop();
  1537. t.join();
  1538. ASSERT_FALSE(svr.is_running());
  1539. });
  1540. svr.wait_until_ready();
  1541. Client cli(HOST, port);
  1542. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1543. ASSERT_TRUE(res);
  1544. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1545. }
  1546. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1547. Server svr;
  1548. std::string field_order, file_order;
  1549. svr.Post("/order", [&](const Request &req, Response &res) {
  1550. for (const auto &field : req.form.fields) {
  1551. field_order += field.first + "=" + field.second.content + " ";
  1552. }
  1553. for (const auto &file : req.form.files) {
  1554. file_order += file.first + "=" + file.second.filename + " ";
  1555. }
  1556. res.set_content("ok", "text/plain");
  1557. });
  1558. auto port = svr.bind_to_any_port(HOST);
  1559. thread t = thread([&] { svr.listen_after_bind(); });
  1560. auto se = detail::scope_exit([&] {
  1561. svr.stop();
  1562. t.join();
  1563. ASSERT_FALSE(svr.is_running());
  1564. });
  1565. svr.wait_until_ready();
  1566. UploadFormDataItems items = {
  1567. {"zulu", "1", "", ""},
  1568. {"alpha", "2", "", ""},
  1569. {"mike", "3", "", ""},
  1570. {"zebra", "z", "z.txt", "text/plain"},
  1571. {"apple", "a", "a.txt", "text/plain"},
  1572. };
  1573. Client cli(HOST, port);
  1574. auto res = cli.Post("/order", items);
  1575. ASSERT_TRUE(res);
  1576. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1577. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1578. }
  1579. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1580. Server svr;
  1581. std::vector<std::string> values;
  1582. std::string first, second, out_of_range, order;
  1583. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1584. values = req.form.get_fields("tag");
  1585. first = req.form.get_field("tag", 0);
  1586. second = req.form.get_field("tag", 1);
  1587. out_of_range = req.form.get_field("tag", 2);
  1588. for (const auto &field : req.form.fields) {
  1589. order += field.first + "=" + field.second.content + " ";
  1590. }
  1591. res.set_content("ok", "text/plain");
  1592. });
  1593. auto port = svr.bind_to_any_port(HOST);
  1594. thread t = thread([&] { svr.listen_after_bind(); });
  1595. auto se = detail::scope_exit([&] {
  1596. svr.stop();
  1597. t.join();
  1598. ASSERT_FALSE(svr.is_running());
  1599. });
  1600. svr.wait_until_ready();
  1601. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1602. // not adjacent in the container.
  1603. UploadFormDataItems items = {
  1604. {"tag", "first", "", ""},
  1605. {"other", "x", "", ""},
  1606. {"tag", "second", "", ""},
  1607. };
  1608. Client cli(HOST, port);
  1609. auto res = cli.Post("/repeated", items);
  1610. ASSERT_TRUE(res);
  1611. ASSERT_EQ(2U, values.size());
  1612. EXPECT_EQ("first", values[0]);
  1613. EXPECT_EQ("second", values[1]);
  1614. EXPECT_EQ("first", first);
  1615. EXPECT_EQ("second", second);
  1616. // std::multimap already kept entries sharing a name in insertion order, so
  1617. // everything above passes without this change too. The whole traversal is
  1618. // what tells the two apart: sorting by name would hoist "other" to the front
  1619. // and the two "tag" parts would end up adjacent.
  1620. EXPECT_EQ("tag=first other=x tag=second ", order);
  1621. // Advancing past the last entry of a name used to run off the container;
  1622. // the container's saturating increment makes it return the default instead.
  1623. EXPECT_EQ("", out_of_range);
  1624. }
  1625. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1626. Server svr;
  1627. std::string file_names;
  1628. svr.Post("/upload", [&](const Request &req, Response &res) {
  1629. for (const auto &file : req.form.files) {
  1630. file_names += file.first + "|" + file.second.filename + " ";
  1631. }
  1632. res.set_content("ok", "text/plain");
  1633. });
  1634. auto port = svr.bind_to_any_port(HOST);
  1635. thread t = thread([&] { svr.listen_after_bind(); });
  1636. auto se = detail::scope_exit([&] {
  1637. svr.stop();
  1638. t.join();
  1639. ASSERT_FALSE(svr.is_running());
  1640. });
  1641. svr.wait_until_ready();
  1642. // A trailing backslash would otherwise escape the closing quote.
  1643. UploadFormDataItems items = {
  1644. {"dir\\", "x", "a.txt", "text/plain"},
  1645. {"b", "y", "a\\\\b.txt", "text/plain"},
  1646. };
  1647. Client cli(HOST, port);
  1648. auto res = cli.Post("/upload", items);
  1649. ASSERT_TRUE(res);
  1650. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1651. }
  1652. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1653. // Server::read_content() keeps a FormFields::iterator alive across the
  1654. // content callbacks that fill the part it points at. The container is
  1655. // vector-backed, so a later emplace can reallocate and invalidate an older
  1656. // iterator; 64 parts grow the vector through seven reallocations, which
  1657. // checks that every part's content still lands in its own entry.
  1658. const size_t part_count = 64;
  1659. // One formula for both the parts sent and the values expected back, so the
  1660. // two cannot drift apart.
  1661. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1662. auto content_of = [](size_t i) {
  1663. return std::string(64, static_cast<char>('a' + (i % 26)));
  1664. };
  1665. Server svr;
  1666. std::vector<std::pair<std::string, std::string>> received;
  1667. svr.Post("/many", [&](const Request &req, Response &res) {
  1668. for (const auto &field : req.form.fields) {
  1669. received.emplace_back(field.first, field.second.content);
  1670. }
  1671. res.set_content("ok", "text/plain");
  1672. });
  1673. auto port = svr.bind_to_any_port(HOST);
  1674. thread t = thread([&] { svr.listen_after_bind(); });
  1675. auto se = detail::scope_exit([&] {
  1676. svr.stop();
  1677. t.join();
  1678. ASSERT_FALSE(svr.is_running());
  1679. });
  1680. svr.wait_until_ready();
  1681. UploadFormDataItems items;
  1682. for (size_t i = 0; i < part_count; i++) {
  1683. items.push_back({name_of(i), content_of(i), "", ""});
  1684. }
  1685. Client cli(HOST, port);
  1686. auto res = cli.Post("/many", items);
  1687. ASSERT_TRUE(res);
  1688. ASSERT_EQ(part_count, received.size());
  1689. for (size_t i = 0; i < part_count; i++) {
  1690. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1691. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1692. }
  1693. }
  1694. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1695. string content_type = "multipart/form-data; boundary=something";
  1696. string boundary;
  1697. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1698. EXPECT_TRUE(ret);
  1699. EXPECT_EQ(boundary, "something");
  1700. }
  1701. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1702. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1703. string boundary;
  1704. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1705. EXPECT_TRUE(ret);
  1706. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1707. }
  1708. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1709. string content_type =
  1710. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1711. string boundary;
  1712. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1713. EXPECT_TRUE(ret);
  1714. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1715. }
  1716. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1717. string content_type =
  1718. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1719. string boundary;
  1720. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1721. EXPECT_TRUE(ret);
  1722. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1723. }
  1724. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1725. const string boundary(70, 'a');
  1726. string content_type = "multipart/form-data; boundary=" + boundary;
  1727. string parsed;
  1728. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1729. EXPECT_TRUE(ret);
  1730. EXPECT_EQ(parsed, boundary);
  1731. }
  1732. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1733. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1734. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1735. string parsed;
  1736. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1737. EXPECT_FALSE(ret);
  1738. }
  1739. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1740. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1741. // is 72 characters on the wire and still valid.
  1742. const string boundary(70, 'a');
  1743. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1744. string parsed;
  1745. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1746. EXPECT_EQ(parsed, boundary);
  1747. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1748. parsed.clear();
  1749. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1750. }
  1751. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1752. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1753. // The parameter parser must not treat that '=' as the key/value separator.
  1754. string content_type =
  1755. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1756. "charset=UTF-8";
  1757. string parsed;
  1758. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1759. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1760. }
  1761. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1762. // A ';' inside the quoted-string is part of the value, not a parameter
  1763. // separator, so it must not truncate the boundary.
  1764. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1765. string parsed;
  1766. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1767. EXPECT_EQ(parsed, "a;b");
  1768. }
  1769. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1770. string parsed;
  1771. EXPECT_TRUE(detail::parse_multipart_boundary(
  1772. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1773. EXPECT_EQ("a\\b", parsed);
  1774. EXPECT_TRUE(detail::parse_multipart_boundary(
  1775. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1776. EXPECT_EQ("a\"b", parsed);
  1777. }
  1778. TEST(ParseDispositionParamsTest, QuotedValues) {
  1779. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1780. // ';' and '=' are ordinary characters inside one.
  1781. struct {
  1782. const char *value;
  1783. std::vector<std::pair<const char *, const char *>> expected;
  1784. } cases[] = {
  1785. {"name=\"file1\"; filename=\"a.txt\"",
  1786. {{"name", "file1"}, {"filename", "a.txt"}}},
  1787. // MIME parameter names are case-insensitive, but their values are not.
  1788. {"NaMe=\"Upload\"; FiLeNaMe=\"Report.TXT\"",
  1789. {{"name", "Upload"}, {"filename", "Report.TXT"}}},
  1790. // Whitespace around '=' and ';' is still trimmed
  1791. {"name=\"file2\" ;filename = \"a.html\"",
  1792. {{"name", "file2"}, {"filename", "a.html"}}},
  1793. // '=' inside the value used to leave only the text after the last one
  1794. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1795. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1796. {"name=\"x=y\"", {{"name", "x=y"}}},
  1797. // ';' inside the value used to truncate the pair and leave a bogus one
  1798. {"name=\"file3\"; filename=\"a;b.txt\"",
  1799. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1800. // An unquoted value keeps working, and so does filename*
  1801. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1802. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1803. // A parameter with no key is dropped rather than turned into one whose
  1804. // key is the value
  1805. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1806. // An escaped quote does not end the value
  1807. {"name=\"a\\\"; filename=evil.php\"",
  1808. {{"name", "a\"; filename=evil.php"}}},
  1809. // Other backslashes, as in a Windows path, are kept
  1810. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1811. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1812. };
  1813. for (const auto &c : cases) {
  1814. Params params;
  1815. detail::parse_disposition_params(c.value, params);
  1816. for (const auto &kv : c.expected) {
  1817. auto it = params.find(kv.first);
  1818. ASSERT_NE(it, params.end())
  1819. << "value: " << c.value << ", key: " << kv.first;
  1820. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1821. }
  1822. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1823. }
  1824. }
  1825. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1826. Server svr;
  1827. std::string filename;
  1828. std::string content;
  1829. svr.Post("/upload", [&](const Request &req, Response &) {
  1830. const auto &file = req.form.get_file("file");
  1831. filename = file.filename;
  1832. content = file.content;
  1833. });
  1834. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1835. auto se = detail::scope_exit([&] {
  1836. svr.stop();
  1837. thread.join();
  1838. ASSERT_FALSE(svr.is_running());
  1839. });
  1840. svr.wait_until_ready();
  1841. std::string body = "--B\r\n"
  1842. "Content-Disposition: form-data; name=\"file\"; "
  1843. "filename=\"a.txt\"\r\n"
  1844. "Content-Type: text/plain\r\n"
  1845. "\r\n"
  1846. "hello\r\n"
  1847. "--B--\r\n";
  1848. Client cli(HOST, PORT);
  1849. auto res = cli.Post(
  1850. "/upload",
  1851. [&](size_t offset, DataSink &sink) {
  1852. if (offset < body.size()) {
  1853. sink.write(&body[offset], 1);
  1854. } else {
  1855. sink.done();
  1856. }
  1857. return true;
  1858. },
  1859. "multipart/form-data; boundary=B");
  1860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1861. EXPECT_EQ(StatusCode::OK_200, res->status);
  1862. EXPECT_EQ("a.txt", filename);
  1863. EXPECT_EQ("hello", content);
  1864. }
  1865. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1866. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1867. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1868. Server svr;
  1869. std::string field_value, file_name, file_filename;
  1870. bool has_field = false, has_file = false;
  1871. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1872. has_field = req.form.has_field("x=y");
  1873. field_value = req.form.get_field("x=y");
  1874. has_file = req.form.has_file("file1");
  1875. const auto &file = req.form.get_file("file1");
  1876. file_name = file.name;
  1877. file_filename = file.filename;
  1878. res.set_content("ok", "text/plain");
  1879. });
  1880. auto port = svr.bind_to_any_port(HOST);
  1881. thread t = thread([&] { svr.listen_after_bind(); });
  1882. auto se = detail::scope_exit([&] {
  1883. svr.stop();
  1884. t.join();
  1885. ASSERT_FALSE(svr.is_running());
  1886. });
  1887. svr.wait_until_ready();
  1888. UploadFormDataItems items = {
  1889. {"x=y", "field-value", "", ""},
  1890. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1891. };
  1892. Client cli(HOST, port);
  1893. auto res = cli.Post("/quoted", items);
  1894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1895. ASSERT_EQ(StatusCode::OK_200, res->status);
  1896. EXPECT_TRUE(has_field);
  1897. EXPECT_EQ("field-value", field_value);
  1898. EXPECT_TRUE(has_file);
  1899. EXPECT_EQ("file1", file_name);
  1900. EXPECT_EQ("a;b=report.pdf", file_filename);
  1901. }
  1902. TEST(GetHeaderValueTest, DefaultValue) {
  1903. Headers headers = {{"Dummy", "Dummy"}};
  1904. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1905. EXPECT_STREQ("text/plain", val);
  1906. }
  1907. TEST(GetHeaderValueTest, DefaultValueInt) {
  1908. Headers headers = {{"Dummy", "Dummy"}};
  1909. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1910. EXPECT_EQ(100ull, val);
  1911. }
  1912. TEST(GetHeaderValueTest, RegularValue) {
  1913. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1914. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1915. EXPECT_STREQ("text/html", val);
  1916. }
  1917. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1918. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1919. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1920. EXPECT_STREQ("text/html", val);
  1921. }
  1922. TEST(GetHeaderValueTest, SetContent) {
  1923. Response res;
  1924. res.set_content("html", "text/html");
  1925. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1926. res.set_content("text", "text/plain");
  1927. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1928. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1929. }
  1930. TEST(GetHeaderValueTest, RegularValueInt) {
  1931. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1932. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1933. EXPECT_EQ(100ull, val);
  1934. }
  1935. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1936. Headers headers = {{"Content-Length", "x"}};
  1937. auto is_invalid_value = false;
  1938. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1939. is_invalid_value);
  1940. EXPECT_EQ(0ull, val);
  1941. EXPECT_TRUE(is_invalid_value);
  1942. }
  1943. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1944. // An all-digit value that overflows size_t must be reported as invalid, not
  1945. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1946. // a large length to a small one on 32-bit builds, leaving the framing length
  1947. // wrong while is_invalid_value stayed false.
  1948. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1949. auto is_invalid_value = false;
  1950. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1951. is_invalid_value);
  1952. EXPECT_TRUE(is_invalid_value);
  1953. // A well-formed length is unaffected.
  1954. Headers ok = {{"Content-Length", "1234"}};
  1955. is_invalid_value = false;
  1956. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1957. is_invalid_value);
  1958. EXPECT_EQ(1234ull, val);
  1959. EXPECT_FALSE(is_invalid_value);
  1960. }
  1961. TEST(GetHeaderValueTest, Range) {
  1962. {
  1963. Headers headers = {make_range_header({{1, -1}})};
  1964. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1965. EXPECT_STREQ("bytes=1-", val);
  1966. }
  1967. {
  1968. Headers headers = {make_range_header({{-1, 1}})};
  1969. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1970. EXPECT_STREQ("bytes=-1", val);
  1971. }
  1972. {
  1973. Headers headers = {make_range_header({{1, 10}})};
  1974. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1975. EXPECT_STREQ("bytes=1-10", val);
  1976. }
  1977. {
  1978. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1979. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1980. EXPECT_STREQ("bytes=1-10, 100-", val);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1984. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1985. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1986. }
  1987. {
  1988. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1989. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1990. EXPECT_STREQ("bytes=0-0, -1", val);
  1991. }
  1992. }
  1993. TEST(BearerTokenAuthTest, SchemeValidation) {
  1994. // A value shorter than "Bearer " must not throw from the fixed-length
  1995. // substr, and a non-Bearer scheme must not be reported as a token.
  1996. struct {
  1997. const char *value;
  1998. const char *expected;
  1999. } cases[] = {
  2000. {"x", ""},
  2001. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  2002. {"Bearer abc123", "abc123"},
  2003. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  2004. {"Bearer abc123", "abc123"}, // 1*SP after the scheme
  2005. };
  2006. for (const auto &c : cases) {
  2007. Request req;
  2008. req.set_header("Authorization", c.value);
  2009. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  2010. }
  2011. }
  2012. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  2013. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  2014. // to depend on the standard library (libstdc++ handed back duplicates in
  2015. // reverse insertion order, libc++ in insertion order).
  2016. Request req;
  2017. req.set_header("Accept-Encoding", "gzip");
  2018. req.set_header("Accept-Encoding", "deflate");
  2019. req.set_header("Accept-Encoding", "br");
  2020. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  2021. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  2022. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  2023. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  2024. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  2025. }
  2026. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  2027. Request req;
  2028. req.set_header("X-Test", "only");
  2029. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  2030. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  2031. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  2032. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  2033. }
  2034. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  2035. Request req;
  2036. req.set_header("X-First", "1");
  2037. req.set_header("X-Test", "2");
  2038. req.params.emplace("first", "1");
  2039. req.params.emplace("test", "2");
  2040. req.form.fields.emplace("first", FormField{"first", "1", {}});
  2041. req.form.fields.emplace("test", FormField{"test", "2", {}});
  2042. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  2043. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  2044. // The second one is negative when read as a signed value
  2045. const auto max_id = (std::numeric_limits<size_t>::max)();
  2046. for (auto id : {max_id / 2, max_id}) {
  2047. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2048. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2049. EXPECT_EQ("", req.get_param_value("test", id));
  2050. EXPECT_EQ("", req.form.get_field("test", id));
  2051. EXPECT_EQ("", req.form.get_file("test", id).content);
  2052. }
  2053. }
  2054. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2055. Headers headers;
  2056. headers.emplace("Host", "example.com");
  2057. headers.emplace("Accept-Encoding", "gzip");
  2058. headers.emplace("User-Agent", "test");
  2059. headers.emplace("Accept-Encoding", "deflate");
  2060. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2061. "Accept-Encoding=deflate ",
  2062. entries_to_string(headers));
  2063. }
  2064. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2065. Headers headers = {{"Content-Type", "text/html"},
  2066. {"CONTENT-TYPE", "text/xml"}};
  2067. EXPECT_EQ(2U, headers.count("content-type"));
  2068. auto it = headers.find("content-type");
  2069. ASSERT_TRUE(it != headers.end());
  2070. EXPECT_EQ("text/html", it->second);
  2071. }
  2072. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2073. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2074. // drop only those fields and leave everything positioned between them.
  2075. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2076. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2077. auto rng = headers.equal_range("a");
  2078. headers.erase(rng.first, rng.second);
  2079. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2080. }
  2081. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2082. Headers headers = {
  2083. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2084. EXPECT_EQ(3U, headers.erase("A"));
  2085. EXPECT_EQ(0U, headers.count("A"));
  2086. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2087. }
  2088. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2089. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2090. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2091. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2092. }
  2093. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2094. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2095. headers.emplace_front("Host", "example.com");
  2096. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2097. entries_to_string(headers));
  2098. }
  2099. TEST(ParseHeaderValueTest, Range) {
  2100. {
  2101. Ranges ranges;
  2102. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2103. EXPECT_TRUE(ret);
  2104. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2105. }
  2106. {
  2107. Ranges ranges;
  2108. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2109. EXPECT_TRUE(ret);
  2110. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2111. }
  2112. {
  2113. Ranges ranges;
  2114. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2115. EXPECT_TRUE(ret);
  2116. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2117. }
  2118. {
  2119. Ranges ranges;
  2120. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2121. EXPECT_FALSE(ret);
  2122. }
  2123. {
  2124. Ranges ranges;
  2125. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2126. EXPECT_TRUE(ret);
  2127. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2128. }
  2129. {
  2130. Ranges ranges;
  2131. auto ret =
  2132. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2133. EXPECT_TRUE(ret);
  2134. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2135. }
  2136. {
  2137. Ranges ranges;
  2138. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2139. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2140. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2141. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2142. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2143. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2144. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2145. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2146. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2147. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2148. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2149. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2150. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2151. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2152. EXPECT_FALSE(
  2153. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2154. EXPECT_TRUE(ranges.empty());
  2155. }
  2156. {
  2157. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2158. // remainder of the representation, so it stays accepted.
  2159. Ranges ranges;
  2160. auto ret =
  2161. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2162. EXPECT_TRUE(ret);
  2163. ASSERT_EQ(1u, ranges.size());
  2164. EXPECT_EQ(0, ranges[0].first);
  2165. EXPECT_EQ(-1, ranges[0].second);
  2166. }
  2167. // RFC 9110 14.1: range unit names are case-insensitive.
  2168. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2169. Ranges ranges;
  2170. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2171. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2172. }
  2173. }
  2174. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2175. Request req;
  2176. req.set_header("Accept-Encoding", "gzip");
  2177. Response res;
  2178. res.set_header("Content-Type", "text/plain");
  2179. auto ret = detail::encoding_type(req, res);
  2180. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2181. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2182. #else
  2183. EXPECT_TRUE(ret == detail::EncodingType::None);
  2184. #endif
  2185. }
  2186. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2187. Request req;
  2188. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2189. Response res;
  2190. res.set_header("Content-Type", "text/plain");
  2191. auto ret = detail::encoding_type(req, res);
  2192. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2193. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2194. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2195. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2196. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2197. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2198. #else
  2199. EXPECT_TRUE(ret == detail::EncodingType::None);
  2200. #endif
  2201. }
  2202. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2203. Request req;
  2204. req.set_header("Accept-Encoding",
  2205. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2206. Response res;
  2207. res.set_header("Content-Type", "text/plain");
  2208. auto ret = detail::encoding_type(req, res);
  2209. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2210. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2211. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2212. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2213. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2214. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2215. #else
  2216. EXPECT_TRUE(ret == detail::EncodingType::None);
  2217. #endif
  2218. }
  2219. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2220. // All supported encodings rejected with q=0 should return None
  2221. Request req;
  2222. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2223. Response res;
  2224. res.set_header("Content-Type", "text/plain");
  2225. auto ret = detail::encoding_type(req, res);
  2226. EXPECT_TRUE(ret == detail::EncodingType::None);
  2227. }
  2228. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2229. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2230. Request req;
  2231. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2232. Response res;
  2233. res.set_header("Content-Type", "text/plain");
  2234. auto ret = detail::encoding_type(req, res);
  2235. EXPECT_TRUE(ret == detail::EncodingType::None);
  2236. }
  2237. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2238. Request req;
  2239. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2240. Response res;
  2241. res.set_header("Content-Type", "text/plain");
  2242. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2243. }
  2244. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2245. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2246. Request req;
  2247. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2248. Response res;
  2249. res.set_header("Content-Type", "text/plain");
  2250. auto ret = detail::encoding_type(req, res);
  2251. EXPECT_TRUE(ret == detail::EncodingType::None);
  2252. }
  2253. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2254. // RFC 7231: Accept-Encoding values are case-insensitive
  2255. Request req;
  2256. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2257. Response res;
  2258. res.set_header("Content-Type", "text/plain");
  2259. auto ret = detail::encoding_type(req, res);
  2260. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2261. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2262. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2263. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2264. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2265. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2266. #else
  2267. EXPECT_TRUE(ret == detail::EncodingType::None);
  2268. #endif
  2269. }
  2270. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2271. // q value should determine priority, not hardcoded order
  2272. Request req;
  2273. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2274. Response res;
  2275. res.set_header("Content-Type", "text/plain");
  2276. auto ret = detail::encoding_type(req, res);
  2277. // gzip has highest q=1.0, so it should be selected even though
  2278. // br and zstd are also supported
  2279. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2280. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2281. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2282. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2283. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2284. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2285. #else
  2286. EXPECT_TRUE(ret == detail::EncodingType::None);
  2287. #endif
  2288. }
  2289. TEST(BufferStreamTest, read) {
  2290. detail::BufferStream strm1;
  2291. Stream &strm = strm1;
  2292. EXPECT_EQ(5, strm.write("hello"));
  2293. char buf[512];
  2294. EXPECT_EQ(2, strm.read(buf, 2));
  2295. EXPECT_EQ('h', buf[0]);
  2296. EXPECT_EQ('e', buf[1]);
  2297. EXPECT_EQ(2, strm.read(buf, 2));
  2298. EXPECT_EQ('l', buf[0]);
  2299. EXPECT_EQ('l', buf[1]);
  2300. EXPECT_EQ(1, strm.read(buf, 1));
  2301. EXPECT_EQ('o', buf[0]);
  2302. EXPECT_EQ(0, strm.read(buf, 1));
  2303. }
  2304. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2305. auto host = "www.httpwatch.com";
  2306. auto ip = hosted_at(host);
  2307. EXPECT_EQ("23.96.13.243", ip);
  2308. std::vector<std::string> addrs;
  2309. hosted_at(host, addrs);
  2310. EXPECT_EQ(1u, addrs.size());
  2311. }
  2312. #if 0 // It depends on each test environment...
  2313. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2314. auto host = "www.youtube.com";
  2315. std::vector<std::string> addrs;
  2316. hosted_at(host, addrs);
  2317. EXPECT_EQ(20u, addrs.size());
  2318. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2319. EXPECT_TRUE(it != addrs.end());
  2320. }
  2321. #endif
  2322. class ChunkedEncodingTest : public ::testing::Test {
  2323. protected:
  2324. ChunkedEncodingTest()
  2325. : cli_(HOST, PORT)
  2326. #ifdef CPPHTTPLIB_SSL_ENABLED
  2327. ,
  2328. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2329. #endif
  2330. {
  2331. cli_.set_connection_timeout(2);
  2332. #ifdef CPPHTTPLIB_SSL_ENABLED
  2333. cli_.enable_server_certificate_verification(false);
  2334. #endif
  2335. }
  2336. virtual void SetUp() {
  2337. read_file("./image.jpg", image_data_);
  2338. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2339. res.set_content("Hello World!", "text/plain");
  2340. });
  2341. svr_.Get(
  2342. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2343. res.set_chunked_content_provider(
  2344. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2345. size_t remaining = image_data_.size() - offset;
  2346. if (remaining == 0) {
  2347. sink.done();
  2348. } else {
  2349. constexpr size_t CHUNK_SIZE = 1024;
  2350. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2351. sink.write(&image_data_[offset], send_size);
  2352. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2353. }
  2354. return true;
  2355. });
  2356. });
  2357. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2358. svr_.wait_until_ready();
  2359. }
  2360. virtual void TearDown() {
  2361. svr_.stop();
  2362. if (!request_threads_.empty()) {
  2363. std::this_thread::sleep_for(std::chrono::seconds(1));
  2364. for (auto &t : request_threads_) {
  2365. t.join();
  2366. }
  2367. }
  2368. t_.join();
  2369. }
  2370. #ifdef CPPHTTPLIB_SSL_ENABLED
  2371. SSLClient cli_;
  2372. SSLServer svr_;
  2373. #else
  2374. Client cli_;
  2375. Server svr_;
  2376. #endif
  2377. thread t_;
  2378. std::vector<thread> request_threads_;
  2379. std::string image_data_;
  2380. };
  2381. TEST_F(ChunkedEncodingTest, NormalGet) {
  2382. auto res = cli_.Get("/chunked");
  2383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2384. std::string out;
  2385. read_file("./image.jpg", out);
  2386. EXPECT_EQ(StatusCode::OK_200, res->status);
  2387. EXPECT_EQ(out, res->body);
  2388. }
  2389. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2390. std::string body;
  2391. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2392. body.append(data, data_length);
  2393. return true;
  2394. });
  2395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2396. std::string out;
  2397. read_file("./image.jpg", out);
  2398. EXPECT_EQ(StatusCode::OK_200, res->status);
  2399. EXPECT_EQ(out, body);
  2400. }
  2401. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2402. std::string body;
  2403. auto res = cli_.Get(
  2404. "/chunked",
  2405. [&](const Response &response) {
  2406. EXPECT_EQ(StatusCode::OK_200, response.status);
  2407. return true;
  2408. },
  2409. [&](const char *data, size_t data_length) {
  2410. body.append(data, data_length);
  2411. return true;
  2412. });
  2413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2414. std::string out;
  2415. read_file("./image.jpg", out);
  2416. EXPECT_EQ(StatusCode::OK_200, res->status);
  2417. EXPECT_EQ(out, body);
  2418. }
  2419. TEST(RangeTest, FromHTTPBin_Online) {
  2420. auto host = "httpbingo.org";
  2421. auto path = std::string{"/range/32"};
  2422. #ifdef CPPHTTPLIB_SSL_ENABLED
  2423. auto port = 443;
  2424. SSLClient cli(host, port);
  2425. #else
  2426. auto port = 80;
  2427. Client cli(host, port);
  2428. #endif
  2429. cli.set_connection_timeout(5);
  2430. {
  2431. auto res = retry_service_failures([&] { return cli.Get(path); });
  2432. SKIP_ON_SERVICE_FAILURE(res);
  2433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2434. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2435. EXPECT_EQ(StatusCode::OK_200, res->status);
  2436. }
  2437. {
  2438. Headers headers = {make_range_header({{1, -1}})};
  2439. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2440. SKIP_ON_SERVICE_FAILURE(res);
  2441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2442. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2443. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2444. }
  2445. {
  2446. Headers headers = {make_range_header({{1, 10}})};
  2447. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2448. SKIP_ON_SERVICE_FAILURE(res);
  2449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2450. EXPECT_EQ("bcdefghijk", res->body);
  2451. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2452. }
  2453. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2454. // entire resource, while the original httpbin returned 200. Both are
  2455. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2456. {
  2457. Headers headers = {make_range_header({{0, 31}})};
  2458. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2459. SKIP_ON_SERVICE_FAILURE(res);
  2460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2461. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2462. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2463. res->status == StatusCode::PartialContent_206);
  2464. }
  2465. {
  2466. Headers headers = {make_range_header({{0, -1}})};
  2467. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2468. SKIP_ON_SERVICE_FAILURE(res);
  2469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2470. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2471. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2472. res->status == StatusCode::PartialContent_206);
  2473. }
  2474. // go-httpbin returns 206 with clamped range for over-range requests,
  2475. // while the original httpbin returned 416. Both behaviors are observed
  2476. // in real servers, so we only verify the request succeeds.
  2477. {
  2478. Headers headers = {make_range_header({{0, 32}})};
  2479. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2480. SKIP_ON_SERVICE_FAILURE(res);
  2481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2482. }
  2483. }
  2484. TEST(RangeTest, IgnoredForPost) {
  2485. Server svr;
  2486. svr.Post("/", [](const Request &, Response &res) {
  2487. res.set_content("abcdefg", "text/plain");
  2488. });
  2489. auto port = svr.bind_to_any_port(HOST);
  2490. ASSERT_GT(port, 0);
  2491. thread t = thread([&] { svr.listen_after_bind(); });
  2492. auto se = detail::scope_exit([&] {
  2493. svr.stop();
  2494. t.join();
  2495. ASSERT_FALSE(svr.is_running());
  2496. });
  2497. svr.wait_until_ready();
  2498. Client cli(HOST, port);
  2499. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2500. auto res = cli.Post("/", Headers{{"Range", range}});
  2501. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2502. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2503. EXPECT_EQ("abcdefg", res->body) << range;
  2504. }
  2505. }
  2506. TEST(RangeTest, IgnoredForUnknownUnit) {
  2507. Server svr;
  2508. svr.Get("/", [](const Request &, Response &res) {
  2509. res.set_content("abcdefg", "text/plain");
  2510. });
  2511. auto port = svr.bind_to_any_port(HOST);
  2512. ASSERT_GT(port, 0);
  2513. thread t = thread([&] { svr.listen_after_bind(); });
  2514. auto se = detail::scope_exit([&] {
  2515. svr.stop();
  2516. t.join();
  2517. ASSERT_FALSE(svr.is_running());
  2518. });
  2519. svr.wait_until_ready();
  2520. Client cli(HOST, port);
  2521. for (auto range : {"items=1-2", "none=x"}) {
  2522. auto res = cli.Get("/", Headers{{"Range", range}});
  2523. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2524. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2525. EXPECT_EQ("abcdefg", res->body) << range;
  2526. }
  2527. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2528. ASSERT_TRUE(res) << to_string(res.error());
  2529. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2530. }
  2531. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2532. auto host = "unresolvableaddress.local";
  2533. auto path = std::string{"/"};
  2534. #ifdef CPPHTTPLIB_SSL_ENABLED
  2535. auto port = 443;
  2536. SSLClient cli(host, port);
  2537. #else
  2538. auto port = 80;
  2539. Client cli(host, port);
  2540. #endif
  2541. cli.set_connection_timeout(1);
  2542. {
  2543. auto res = cli.Get(path);
  2544. ASSERT_FALSE(res);
  2545. }
  2546. std::this_thread::sleep_for(std::chrono::seconds(8));
  2547. }
  2548. #if defined(__linux__) && defined(__GLIBC__) && \
  2549. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2550. // Forward declaration: in split builds split.py strips `inline` and moves the
  2551. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2552. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2553. // against the symbol in both header-only and split builds.
  2554. namespace httplib {
  2555. namespace detail {
  2556. int getaddrinfo_with_timeout(const char *node, const char *service,
  2557. const struct addrinfo *hints,
  2558. struct addrinfo **res, time_t timeout_sec);
  2559. } // namespace detail
  2560. } // namespace httplib
  2561. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2562. //
  2563. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2564. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2565. // gai_suspend() call hits the connection timeout the function calls
  2566. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2567. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2568. // still alive and still references the now-destroyed stack frame.
  2569. //
  2570. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2571. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2572. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2573. // and runs them in a container.
  2574. namespace {
  2575. bool should_run_issue_2431_tests() {
  2576. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2577. return v && *v && std::string(v) != "0";
  2578. }
  2579. std::string unique_unresolvable_host(int n) {
  2580. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2581. // glibc still asks the configured nameserver — which is exactly the path
  2582. // we want to exercise. A unique label per call avoids the resolver cache.
  2583. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2584. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2585. std::to_string(n) + ".invalid";
  2586. }
  2587. } // namespace
  2588. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2589. if (!should_run_issue_2431_tests()) {
  2590. GTEST_SKIP()
  2591. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2592. }
  2593. for (int i = 0; i < 8; ++i) {
  2594. struct addrinfo hints;
  2595. memset(&hints, 0, sizeof(hints));
  2596. hints.ai_family = AF_UNSPEC;
  2597. hints.ai_socktype = SOCK_STREAM;
  2598. auto host = unique_unresolvable_host(i);
  2599. struct addrinfo *result = nullptr;
  2600. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2601. &result, /*timeout_sec=*/1);
  2602. if (rc == 0 && result) { freeaddrinfo(result); }
  2603. }
  2604. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2605. // stack region they still believe holds their gaicb.
  2606. std::this_thread::sleep_for(std::chrono::seconds(3));
  2607. }
  2608. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2609. if (!should_run_issue_2431_tests()) {
  2610. GTEST_SKIP()
  2611. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2612. }
  2613. std::atomic<bool> stop{false};
  2614. std::vector<std::thread> threads;
  2615. for (int t = 0; t < 8; ++t) {
  2616. threads.emplace_back([t, &stop] {
  2617. int i = 0;
  2618. while (!stop.load(std::memory_order_relaxed)) {
  2619. struct addrinfo hints;
  2620. memset(&hints, 0, sizeof(hints));
  2621. hints.ai_family = AF_UNSPEC;
  2622. hints.ai_socktype = SOCK_STREAM;
  2623. auto host = unique_unresolvable_host(t * 100000 + i++);
  2624. struct addrinfo *result = nullptr;
  2625. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2626. &result, /*timeout_sec=*/1);
  2627. if (rc == 0 && result) { freeaddrinfo(result); }
  2628. }
  2629. });
  2630. }
  2631. std::this_thread::sleep_for(std::chrono::seconds(8));
  2632. stop.store(true, std::memory_order_relaxed);
  2633. for (auto &th : threads) {
  2634. th.join();
  2635. }
  2636. std::this_thread::sleep_for(std::chrono::seconds(3));
  2637. }
  2638. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2639. if (!should_run_issue_2431_tests()) {
  2640. GTEST_SKIP()
  2641. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2642. }
  2643. std::atomic<bool> stop{false};
  2644. std::vector<std::thread> threads;
  2645. for (int t = 0; t < 8; ++t) {
  2646. threads.emplace_back([t, &stop] {
  2647. int i = 0;
  2648. while (!stop.load(std::memory_order_relaxed)) {
  2649. auto host = unique_unresolvable_host(t * 100000 + i++);
  2650. Client cli(host, 80);
  2651. cli.set_connection_timeout(1, 0);
  2652. cli.set_read_timeout(1, 0);
  2653. cli.set_write_timeout(1, 0);
  2654. (void)cli.Get("/");
  2655. }
  2656. });
  2657. }
  2658. std::this_thread::sleep_for(std::chrono::seconds(8));
  2659. stop.store(true, std::memory_order_relaxed);
  2660. for (auto &th : threads) {
  2661. th.join();
  2662. }
  2663. std::this_thread::sleep_for(std::chrono::seconds(3));
  2664. }
  2665. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2666. TEST(ConnectionErrorTest, InvalidHost) {
  2667. auto host = "-abcde.com";
  2668. #ifdef CPPHTTPLIB_SSL_ENABLED
  2669. auto port = 443;
  2670. SSLClient cli(host, port);
  2671. #else
  2672. auto port = 80;
  2673. Client cli(host, port);
  2674. #endif
  2675. cli.set_connection_timeout(std::chrono::seconds(2));
  2676. auto res = cli.Get("/");
  2677. ASSERT_TRUE(!res);
  2678. EXPECT_EQ(Error::Connection, res.error());
  2679. }
  2680. TEST(ConnectionErrorTest, InvalidHost2) {
  2681. auto host = "httpcan.org/";
  2682. #ifdef CPPHTTPLIB_SSL_ENABLED
  2683. SSLClient cli(host);
  2684. #else
  2685. Client cli(host);
  2686. #endif
  2687. cli.set_connection_timeout(std::chrono::seconds(2));
  2688. auto res = cli.Get("/");
  2689. ASSERT_TRUE(!res);
  2690. EXPECT_EQ(Error::Connection, res.error());
  2691. }
  2692. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2693. auto host = "httpcan.org/";
  2694. #ifdef CPPHTTPLIB_SSL_ENABLED
  2695. SSLClient cli(host);
  2696. #else
  2697. Client cli(host);
  2698. #endif
  2699. cli.set_connection_timeout(std::chrono::seconds(2));
  2700. auto res = cli.Get("/");
  2701. ASSERT_TRUE(!res);
  2702. stringstream s;
  2703. s << "error code: " << res.error();
  2704. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2705. }
  2706. TEST(ConnectionErrorTest, InvalidPort) {
  2707. auto host = "localhost";
  2708. auto port = 44380;
  2709. #ifdef CPPHTTPLIB_SSL_ENABLED
  2710. SSLClient cli(host, port);
  2711. #else
  2712. Client cli(host, port);
  2713. #endif
  2714. cli.set_connection_timeout(std::chrono::seconds(2));
  2715. auto res = cli.Get("/");
  2716. ASSERT_TRUE(!res);
  2717. EXPECT_TRUE(Error::Connection == res.error() ||
  2718. Error::ConnectionTimeout == res.error());
  2719. }
  2720. TEST(ConnectionErrorTest, Timeout_Online) {
  2721. auto host = "google.com";
  2722. #ifdef CPPHTTPLIB_SSL_ENABLED
  2723. auto port = 44380;
  2724. SSLClient cli(host, port);
  2725. #else
  2726. auto port = 8080;
  2727. Client cli(host, port);
  2728. #endif
  2729. cli.set_connection_timeout(std::chrono::seconds(2));
  2730. // only probe one address type so that the error reason
  2731. // correlates to the timed-out IPv4, not the unsupported
  2732. // IPv6 connection attempt
  2733. cli.set_address_family(AF_INET);
  2734. auto res = cli.Get("/");
  2735. ASSERT_TRUE(!res);
  2736. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2737. }
  2738. TEST(CancelTest, NoCancel_Online) {
  2739. auto host = "httpbingo.org";
  2740. auto path = std::string{"/range/32"};
  2741. #ifdef CPPHTTPLIB_SSL_ENABLED
  2742. auto port = 443;
  2743. SSLClient cli(host, port);
  2744. #else
  2745. auto port = 80;
  2746. Client cli(host, port);
  2747. #endif
  2748. cli.set_connection_timeout(std::chrono::seconds(5));
  2749. auto res = retry_service_failures(
  2750. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
  2751. SKIP_ON_SERVICE_FAILURE(res);
  2752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2753. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2754. EXPECT_EQ(StatusCode::OK_200, res->status);
  2755. }
  2756. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2757. // Use /bytes with a large payload so that the DownloadProgress callback
  2758. // (which only fires for Content-Length responses) is invoked before the
  2759. // entire body is received, giving cancellation a chance to fire.
  2760. auto host = "httpbingo.org";
  2761. auto path = std::string{"/bytes/524288"};
  2762. #ifdef CPPHTTPLIB_SSL_ENABLED
  2763. auto port = 443;
  2764. SSLClient cli(host, port);
  2765. #else
  2766. auto port = 80;
  2767. Client cli(host, port);
  2768. #endif
  2769. auto res = retry_service_failures(
  2770. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
  2771. SKIP_ON_SERVICE_FAILURE(res);
  2772. cli.set_connection_timeout(std::chrono::seconds(5));
  2773. ASSERT_TRUE(!res);
  2774. EXPECT_EQ(Error::Canceled, res.error());
  2775. }
  2776. TEST(CancelTest, WithCancelLargePayload_Online) {
  2777. auto host = "httpbingo.org";
  2778. auto path = std::string{"/bytes/524288"};
  2779. #ifdef CPPHTTPLIB_SSL_ENABLED
  2780. auto port = 443;
  2781. SSLClient cli(host, port);
  2782. #else
  2783. auto port = 80;
  2784. Client cli(host, port);
  2785. #endif
  2786. cli.set_connection_timeout(std::chrono::seconds(5));
  2787. auto res = retry_service_failures([&] {
  2788. auto count = 0;
  2789. return cli.Get(path,
  2790. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2791. });
  2792. SKIP_ON_SERVICE_FAILURE(res);
  2793. ASSERT_TRUE(!res);
  2794. EXPECT_EQ(Error::Canceled, res.error());
  2795. }
  2796. TEST(CancelTest, NoCancelPost) {
  2797. Server svr;
  2798. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2799. res.set_content("Hello World!", "text/plain");
  2800. });
  2801. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2802. auto se = detail::scope_exit([&] {
  2803. svr.stop();
  2804. thread.join();
  2805. ASSERT_FALSE(svr.is_running());
  2806. });
  2807. svr.wait_until_ready();
  2808. Client cli(HOST, PORT);
  2809. cli.set_connection_timeout(std::chrono::seconds(5));
  2810. auto res =
  2811. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2812. "application/json", [](uint64_t, uint64_t) { return true; });
  2813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2814. EXPECT_EQ("Hello World!", res->body);
  2815. EXPECT_EQ(StatusCode::OK_200, res->status);
  2816. }
  2817. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2818. Server svr;
  2819. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2820. res.set_content("Hello World!", "text/plain");
  2821. });
  2822. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2823. auto se = detail::scope_exit([&] {
  2824. svr.stop();
  2825. thread.join();
  2826. ASSERT_FALSE(svr.is_running());
  2827. });
  2828. svr.wait_until_ready();
  2829. Client cli(HOST, PORT);
  2830. cli.set_connection_timeout(std::chrono::seconds(5));
  2831. auto res =
  2832. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2833. "application/json", [](uint64_t, uint64_t) { return false; });
  2834. ASSERT_TRUE(!res);
  2835. EXPECT_EQ(Error::Canceled, res.error());
  2836. }
  2837. TEST(CancelTest, WithCancelLargePayloadPost) {
  2838. Server svr;
  2839. svr.set_payload_max_length(200 * 1024 * 1024);
  2840. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2841. res.set_content(LARGE_DATA, "text/plain");
  2842. });
  2843. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2844. auto se = detail::scope_exit([&] {
  2845. svr.stop();
  2846. thread.join();
  2847. ASSERT_FALSE(svr.is_running());
  2848. });
  2849. svr.wait_until_ready();
  2850. Client cli(HOST, PORT);
  2851. cli.set_payload_max_length(200 * 1024 * 1024);
  2852. cli.set_connection_timeout(std::chrono::seconds(5));
  2853. auto res =
  2854. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2855. "application/json", [](uint64_t, uint64_t) { return false; });
  2856. ASSERT_TRUE(!res);
  2857. EXPECT_EQ(Error::Canceled, res.error());
  2858. }
  2859. TEST(CancelTest, NoCancelPut) {
  2860. Server svr;
  2861. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2862. res.set_content("Hello World!", "text/plain");
  2863. });
  2864. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2865. auto se = detail::scope_exit([&] {
  2866. svr.stop();
  2867. thread.join();
  2868. ASSERT_FALSE(svr.is_running());
  2869. });
  2870. svr.wait_until_ready();
  2871. Client cli(HOST, PORT);
  2872. cli.set_connection_timeout(std::chrono::seconds(5));
  2873. auto res =
  2874. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2875. "application/json", [](uint64_t, uint64_t) { return true; });
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ("Hello World!", res->body);
  2878. EXPECT_EQ(StatusCode::OK_200, res->status);
  2879. }
  2880. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2881. Server svr;
  2882. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2883. res.set_content("Hello World!", "text/plain");
  2884. });
  2885. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2886. auto se = detail::scope_exit([&] {
  2887. svr.stop();
  2888. thread.join();
  2889. ASSERT_FALSE(svr.is_running());
  2890. });
  2891. svr.wait_until_ready();
  2892. Client cli(HOST, PORT);
  2893. cli.set_connection_timeout(std::chrono::seconds(5));
  2894. auto res =
  2895. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2896. "application/json", [](uint64_t, uint64_t) { return false; });
  2897. ASSERT_TRUE(!res);
  2898. EXPECT_EQ(Error::Canceled, res.error());
  2899. }
  2900. TEST(CancelTest, WithCancelLargePayloadPut) {
  2901. Server svr;
  2902. svr.set_payload_max_length(200 * 1024 * 1024);
  2903. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2904. res.set_content(LARGE_DATA, "text/plain");
  2905. });
  2906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2907. auto se = detail::scope_exit([&] {
  2908. svr.stop();
  2909. thread.join();
  2910. ASSERT_FALSE(svr.is_running());
  2911. });
  2912. svr.wait_until_ready();
  2913. Client cli(HOST, PORT);
  2914. cli.set_payload_max_length(200 * 1024 * 1024);
  2915. cli.set_connection_timeout(std::chrono::seconds(5));
  2916. auto res =
  2917. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2918. "application/json", [](uint64_t, uint64_t) { return false; });
  2919. ASSERT_TRUE(!res);
  2920. EXPECT_EQ(Error::Canceled, res.error());
  2921. }
  2922. TEST(CancelTest, NoCancelPatch) {
  2923. Server svr;
  2924. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2925. res.set_content("Hello World!", "text/plain");
  2926. });
  2927. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2928. auto se = detail::scope_exit([&] {
  2929. svr.stop();
  2930. thread.join();
  2931. ASSERT_FALSE(svr.is_running());
  2932. });
  2933. svr.wait_until_ready();
  2934. Client cli(HOST, PORT);
  2935. cli.set_connection_timeout(std::chrono::seconds(5));
  2936. auto res =
  2937. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2938. "application/json", [](uint64_t, uint64_t) { return true; });
  2939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2940. EXPECT_EQ("Hello World!", res->body);
  2941. EXPECT_EQ(StatusCode::OK_200, res->status);
  2942. }
  2943. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2944. Server svr;
  2945. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2946. res.set_content("Hello World!", "text/plain");
  2947. });
  2948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2949. auto se = detail::scope_exit([&] {
  2950. svr.stop();
  2951. thread.join();
  2952. ASSERT_FALSE(svr.is_running());
  2953. });
  2954. svr.wait_until_ready();
  2955. Client cli(HOST, PORT);
  2956. cli.set_connection_timeout(std::chrono::seconds(5));
  2957. auto res =
  2958. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2959. "application/json", [](uint64_t, uint64_t) { return false; });
  2960. ASSERT_TRUE(!res);
  2961. EXPECT_EQ(Error::Canceled, res.error());
  2962. }
  2963. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2964. Server svr;
  2965. svr.set_payload_max_length(200 * 1024 * 1024);
  2966. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2967. res.set_content(LARGE_DATA, "text/plain");
  2968. });
  2969. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2970. auto se = detail::scope_exit([&] {
  2971. svr.stop();
  2972. thread.join();
  2973. ASSERT_FALSE(svr.is_running());
  2974. });
  2975. svr.wait_until_ready();
  2976. Client cli(HOST, PORT);
  2977. cli.set_payload_max_length(200 * 1024 * 1024);
  2978. cli.set_connection_timeout(std::chrono::seconds(5));
  2979. auto res =
  2980. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2981. "application/json", [](uint64_t, uint64_t) { return false; });
  2982. ASSERT_TRUE(!res);
  2983. EXPECT_EQ(Error::Canceled, res.error());
  2984. }
  2985. TEST(CancelTest, NoCancelDelete) {
  2986. Server svr;
  2987. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2988. res.set_content("Hello World!", "text/plain");
  2989. });
  2990. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2991. auto se = detail::scope_exit([&] {
  2992. svr.stop();
  2993. thread.join();
  2994. ASSERT_FALSE(svr.is_running());
  2995. });
  2996. svr.wait_until_ready();
  2997. Client cli(HOST, PORT);
  2998. cli.set_connection_timeout(std::chrono::seconds(5));
  2999. auto res =
  3000. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3001. "application/json", [](uint64_t, uint64_t) { return true; });
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. EXPECT_EQ("Hello World!", res->body);
  3004. EXPECT_EQ(StatusCode::OK_200, res->status);
  3005. }
  3006. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  3007. Server svr;
  3008. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3009. res.set_content("Hello World!", "text/plain");
  3010. });
  3011. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3012. auto se = detail::scope_exit([&] {
  3013. svr.stop();
  3014. thread.join();
  3015. ASSERT_FALSE(svr.is_running());
  3016. });
  3017. svr.wait_until_ready();
  3018. Client cli(HOST, PORT);
  3019. cli.set_connection_timeout(std::chrono::seconds(5));
  3020. auto res =
  3021. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3022. "application/json", [](uint64_t, uint64_t) { return false; });
  3023. ASSERT_TRUE(!res);
  3024. EXPECT_EQ(Error::Canceled, res.error());
  3025. }
  3026. TEST(CancelTest, WithCancelLargePayloadDelete) {
  3027. Server svr;
  3028. svr.set_payload_max_length(200 * 1024 * 1024);
  3029. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3030. res.set_content(LARGE_DATA, "text/plain");
  3031. });
  3032. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3033. auto se = detail::scope_exit([&] {
  3034. svr.stop();
  3035. thread.join();
  3036. ASSERT_FALSE(svr.is_running());
  3037. });
  3038. svr.wait_until_ready();
  3039. Client cli(HOST, PORT);
  3040. cli.set_payload_max_length(200 * 1024 * 1024);
  3041. cli.set_connection_timeout(std::chrono::seconds(5));
  3042. auto res =
  3043. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3044. "application/json", [](uint64_t, uint64_t) { return false; });
  3045. ASSERT_TRUE(!res);
  3046. EXPECT_EQ(Error::Canceled, res.error());
  3047. }
  3048. // One stop() from another thread ends a request that waits for the response
  3049. TEST(ClientStopTest, StopEndsWaitForResponse) {
  3050. Server svr;
  3051. std::atomic<bool> received{false};
  3052. std::atomic<bool> done{false};
  3053. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  3054. received.store(true);
  3055. while (!done.load()) {
  3056. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3057. }
  3058. res.set_content("Hello World!", "text/plain");
  3059. });
  3060. auto port = svr.bind_to_any_port(HOST);
  3061. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3062. Client cli(HOST, port);
  3063. cli.set_read_timeout(std::chrono::seconds(30));
  3064. std::future<Result> request;
  3065. auto se = detail::scope_exit([&] {
  3066. done.store(true);
  3067. svr.stop();
  3068. thread.join();
  3069. ASSERT_FALSE(svr.is_running());
  3070. });
  3071. svr.wait_until_ready();
  3072. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3073. for (int i = 0; i < 500 && !received.load(); ++i) {
  3074. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3075. }
  3076. ASSERT_TRUE(received.load());
  3077. // Let the client block in the wait for the response
  3078. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3079. auto start = std::chrono::steady_clock::now();
  3080. cli.stop();
  3081. ASSERT_EQ(std::future_status::ready,
  3082. request.wait_for(std::chrono::seconds(5)));
  3083. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3084. auto res = request.get();
  3085. ASSERT_TRUE(!res);
  3086. EXPECT_EQ(Error::Read, res.error());
  3087. }
  3088. // A listener whose backlog completes the TCP connections of clients, and that
  3089. // never answers them
  3090. struct SilentListener {
  3091. socket_t sock = INVALID_SOCKET;
  3092. sockaddr_in addr{};
  3093. int port = 0;
  3094. explicit SilentListener(int backlog = 1) {
  3095. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3096. addr.sin_family = AF_INET;
  3097. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3098. socklen_t len = sizeof(addr);
  3099. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3100. ::listen(sock, backlog) != 0 ||
  3101. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3102. detail::close_socket(sock);
  3103. sock = INVALID_SOCKET;
  3104. }
  3105. port = ntohs(addr.sin_port);
  3106. }
  3107. ~SilentListener() { detail::close_socket(sock); }
  3108. // The next connection, whose reads give up after 5 seconds
  3109. socket_t accept() const {
  3110. auto peer = ::accept(sock, nullptr, nullptr);
  3111. if (peer != INVALID_SOCKET) {
  3112. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3113. }
  3114. return peer;
  3115. }
  3116. };
  3117. static bool receives_a_byte(socket_t peer) {
  3118. char c = 0;
  3119. return detail::read_socket(peer, &c, 1, 0) == 1;
  3120. }
  3121. // Runs op, stops cli once the listener receives the first byte op sends, and
  3122. // expects op to end with error soon after
  3123. template <typename ClientType, typename Op>
  3124. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3125. Op op, Error error = Error::Canceled) {
  3126. auto ended = std::async(std::launch::async, op);
  3127. auto peer = listener.accept();
  3128. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3129. ASSERT_NE(INVALID_SOCKET, peer);
  3130. ASSERT_TRUE(receives_a_byte(peer));
  3131. cli.stop();
  3132. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3133. EXPECT_EQ(error, ended.get());
  3134. }
  3135. // Stops itself from another thread as the connection opens, the last moment a
  3136. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3137. // waits for the connection fails the test instead of hanging it.
  3138. class StoppedAsConnectedClient : public ClientImpl {
  3139. public:
  3140. using ClientImpl::ClientImpl;
  3141. protected:
  3142. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3143. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3144. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3145. stopper_.wait_for(std::chrono::seconds(1));
  3146. return true;
  3147. }
  3148. private:
  3149. std::future<void> stopper_;
  3150. };
  3151. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3152. SilentListener listener;
  3153. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3154. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3155. cli.set_read_timeout(std::chrono::seconds(3));
  3156. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3157. auto peer = listener.accept();
  3158. EXPECT_FALSE(receives_a_byte(peer));
  3159. detail::close_socket(peer);
  3160. auto handle = cli.open_stream("GET", "/");
  3161. EXPECT_FALSE(handle.is_valid());
  3162. EXPECT_EQ(Error::Canceled, handle.error);
  3163. peer = listener.accept();
  3164. EXPECT_FALSE(receives_a_byte(peer));
  3165. detail::close_socket(peer);
  3166. }
  3167. #ifdef __linux__
  3168. // A connect that a listener with a full backlog never completes
  3169. TEST(ClientStopTest, StopEndsAConnect) {
  3170. SilentListener listener(0);
  3171. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3172. std::vector<socket_t> backlog;
  3173. auto close_backlog = detail::scope_exit([&] {
  3174. for (auto sock : backlog) {
  3175. detail::close_socket(sock);
  3176. }
  3177. });
  3178. for (int i = 0; i < 8; i++) {
  3179. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3180. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3181. sizeof(listener.addr));
  3182. backlog.push_back(sock);
  3183. }
  3184. Client cli("127.0.0.1", listener.port);
  3185. cli.set_connection_timeout(std::chrono::seconds(3));
  3186. auto ended =
  3187. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3188. // A stop() before the request starts does not apply to it, so it repeats
  3189. auto status = std::future_status::timeout;
  3190. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3191. cli.stop();
  3192. status = ended.wait_for(std::chrono::milliseconds(10));
  3193. }
  3194. EXPECT_EQ(std::future_status::ready, status);
  3195. EXPECT_EQ(Error::Canceled, ended.get());
  3196. }
  3197. #endif
  3198. // The stream holds the socket while it waits for the head, out of the reach
  3199. // of shutdown()
  3200. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3201. SilentListener listener;
  3202. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3203. Client cli("127.0.0.1", listener.port);
  3204. cli.set_read_timeout(std::chrono::seconds(3));
  3205. expect_stop_ends(
  3206. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3207. Error::Read);
  3208. }
  3209. #ifdef CPPHTTPLIB_SSL_ENABLED
  3210. // A server that never answers the ClientHello
  3211. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3212. SilentListener listener;
  3213. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3214. SSLClient cli("127.0.0.1", listener.port);
  3215. cli.enable_server_certificate_verification(false);
  3216. cli.set_connection_timeout(std::chrono::seconds(3));
  3217. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3218. expect_stop_ends(cli, listener,
  3219. [&] { return cli.open_stream("GET", "/").error; });
  3220. }
  3221. // A proxy that takes the CONNECT and never answers it
  3222. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3223. SilentListener listener;
  3224. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3225. SSLClient cli("example.com", 443);
  3226. cli.set_proxy("127.0.0.1", listener.port);
  3227. cli.set_read_timeout(std::chrono::seconds(3));
  3228. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3229. }
  3230. #endif
  3231. // A read timeout past what the clock reaches waits for the response
  3232. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3233. SilentListener listener;
  3234. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3235. Client cli("127.0.0.1", listener.port);
  3236. cli.set_read_timeout(
  3237. static_cast<time_t>((std::min)(static_cast<long long>(
  3238. (std::numeric_limits<time_t>::max)()),
  3239. 10000000000LL)),
  3240. 0);
  3241. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3242. auto peer = listener.accept();
  3243. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3244. ASSERT_NE(INVALID_SOCKET, peer);
  3245. ASSERT_TRUE(receives_a_byte(peer));
  3246. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3247. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3248. "Connection: close\r\n\r\nok";
  3249. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3250. auto result = res.get();
  3251. ASSERT_TRUE(result);
  3252. EXPECT_EQ("ok", result->body);
  3253. }
  3254. static std::string remove_whitespace(const std::string &input) {
  3255. std::string output;
  3256. output.reserve(input.size());
  3257. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3258. [](unsigned char c) { return !std::isspace(c); });
  3259. return output;
  3260. }
  3261. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3262. auto host = "httpbingo.org";
  3263. auto path = std::string{"/basic-auth/hello/world"};
  3264. #ifdef CPPHTTPLIB_SSL_ENABLED
  3265. auto port = 443;
  3266. SSLClient cli(host, port);
  3267. #else
  3268. auto port = 80;
  3269. Client cli(host, port);
  3270. #endif
  3271. {
  3272. auto res = retry_service_failures([&] { return cli.Get(path); });
  3273. SKIP_ON_SERVICE_FAILURE(res);
  3274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3275. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3276. }
  3277. {
  3278. auto res = retry_service_failures([&] {
  3279. return cli.Get(
  3280. path, Headers{make_basic_authentication_header("hello", "world")});
  3281. });
  3282. SKIP_ON_SERVICE_FAILURE(res);
  3283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3284. auto body = remove_whitespace(res->body);
  3285. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3286. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3287. EXPECT_EQ(StatusCode::OK_200, res->status);
  3288. }
  3289. {
  3290. cli.set_basic_auth("hello", "world");
  3291. auto res = retry_service_failures([&] { return cli.Get(path); });
  3292. SKIP_ON_SERVICE_FAILURE(res);
  3293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3294. auto body = remove_whitespace(res->body);
  3295. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3296. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3297. EXPECT_EQ(StatusCode::OK_200, res->status);
  3298. }
  3299. {
  3300. cli.set_basic_auth("hello", "bad");
  3301. auto res = retry_service_failures([&] { return cli.Get(path); });
  3302. SKIP_ON_SERVICE_FAILURE(res);
  3303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3304. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3305. }
  3306. {
  3307. cli.set_basic_auth("bad", "world");
  3308. auto res = retry_service_failures([&] { return cli.Get(path); });
  3309. SKIP_ON_SERVICE_FAILURE(res);
  3310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3311. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3312. }
  3313. }
  3314. #ifdef CPPHTTPLIB_SSL_ENABLED
  3315. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3316. auto host = "httpbingo.org";
  3317. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3318. auto paths = std::vector<std::string>{
  3319. "/digest-auth/auth/hello/world/MD5",
  3320. "/digest-auth/auth/hello/world/SHA-256",
  3321. };
  3322. auto port = 443;
  3323. SSLClient cli(host, port);
  3324. {
  3325. auto res = retry_service_failures([&] { return cli.Get(unauth_path); });
  3326. SKIP_ON_SERVICE_FAILURE(res);
  3327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3328. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3329. }
  3330. {
  3331. cli.set_digest_auth("hello", "world");
  3332. for (const auto &path : paths) {
  3333. auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
  3334. SKIP_ON_SERVICE_FAILURE(res);
  3335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3336. auto body = remove_whitespace(res->body);
  3337. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3338. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3339. EXPECT_EQ(StatusCode::OK_200, res->status);
  3340. }
  3341. cli.set_digest_auth("hello", "bad");
  3342. for (const auto &path : paths) {
  3343. auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
  3344. SKIP_ON_SERVICE_FAILURE(res);
  3345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3346. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3347. }
  3348. }
  3349. }
  3350. // Runs one 401 -> Digest-retry round trip with the given WWW-Authenticate
  3351. // field lines (get_combined_header_value() joins them in receipt order) and
  3352. // returns the Authorization header of the retry.
  3353. static std::string
  3354. get_digest_retry_authorization(const std::vector<std::string> &challenges) {
  3355. std::atomic<int> hits{0};
  3356. std::string authorization;
  3357. Server svr;
  3358. svr.Get("/x", [&](const Request &req, Response &res) {
  3359. if (++hits == 1) {
  3360. res.status = StatusCode::Unauthorized_401;
  3361. for (const auto &challenge : challenges) {
  3362. res.set_header("WWW-Authenticate", challenge);
  3363. }
  3364. } else {
  3365. authorization = req.get_header_value("Authorization");
  3366. res.set_content("ok", "text/plain");
  3367. }
  3368. });
  3369. auto port = svr.bind_to_any_port(HOST);
  3370. std::thread t([&]() { svr.listen_after_bind(); });
  3371. auto se = detail::scope_exit([&] {
  3372. svr.stop();
  3373. t.join();
  3374. });
  3375. svr.wait_until_ready();
  3376. Client cli(HOST, port);
  3377. cli.set_digest_auth("hello", "world");
  3378. auto res = cli.Get("/x");
  3379. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  3380. EXPECT_EQ(2, hits.load());
  3381. return authorization;
  3382. }
  3383. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3384. // comma-separated list of challenges, and each challenge may itself carry a
  3385. // comma-separated auth-param list, so a server can legally offer Basic
  3386. // before Digest, either as two field lines or packed into one. Checks that
  3387. // the retry carries a well-formed Digest Authorization header naming
  3388. // expected_realm.
  3389. static void
  3390. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3391. const std::string &expected_realm) {
  3392. auto authorization = get_digest_retry_authorization(challenges);
  3393. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3394. EXPECT_NE(std::string::npos,
  3395. authorization.find("realm=\"" + expected_realm + "\""));
  3396. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3397. }
  3398. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3399. static const char *kDigestChallenge =
  3400. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3401. "algorithm=MD5";
  3402. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3403. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3404. "testrealm");
  3405. }
  3406. // Same challenge list with the schemes in the opposite order, to make sure
  3407. // the fix above didn't just special-case "Basic first".
  3408. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3409. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3410. "testrealm");
  3411. }
  3412. // A comma inside a quoted auth-param value must not be mistaken for the
  3413. // separator between two challenges (or two auth-params).
  3414. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3415. run_digest_challenge_list_test(
  3416. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3417. "algorithm=MD5"},
  3418. "test,realm");
  3419. }
  3420. // RFC 9110 11.6.1: 1*SP separates the scheme from its first auth-param.
  3421. TEST(DigestAuthTest, SeveralSpacesAfterScheme) {
  3422. auto authorization =
  3423. get_digest_retry_authorization({"Digest realm=\"r\", nonce=\"n\""});
  3424. EXPECT_NE(std::string::npos, authorization.find("nonce=\"n\""));
  3425. }
  3426. // RFC 9110 11.2: auth-param names are matched case-insensitively.
  3427. TEST(DigestAuthTest, ParamNamesAreCaseInsensitive) {
  3428. auto authorization = get_digest_retry_authorization(
  3429. {"Digest Realm=\"testrealm\", QOP=\"auth\", Nonce=\"abc123\", "
  3430. "Algorithm=SHA-256, OPAQUE=\"op\""});
  3431. EXPECT_NE(std::string::npos, authorization.find("realm=\"testrealm\""));
  3432. EXPECT_NE(std::string::npos, authorization.find("nonce=\"abc123\""));
  3433. EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
  3434. EXPECT_NE(std::string::npos, authorization.find("qop=auth"));
  3435. EXPECT_NE(std::string::npos, authorization.find("opaque=\"op\""));
  3436. }
  3437. // The algorithm is matched case-insensitively and sent back as the server
  3438. // wrote it (RFC 7616 3.4).
  3439. TEST(DigestAuthTest, AlgorithmValueIsCaseInsensitive) {
  3440. auto authorization = get_digest_retry_authorization(
  3441. {"Digest realm=\"r\", nonce=\"n\", qop=\"auth\", algorithm=sha-256"});
  3442. EXPECT_NE(std::string::npos, authorization.find("algorithm=sha-256"));
  3443. const std::string prefix = "response=\"";
  3444. auto b = authorization.find(prefix);
  3445. ASSERT_NE(std::string::npos, b);
  3446. b += prefix.size();
  3447. EXPECT_EQ(64u, authorization.find('"', b) - b); // SHA-256, not MD5
  3448. }
  3449. // qop options are matched case-insensitively.
  3450. TEST(DigestAuthTest, QopValueIsCaseInsensitive) {
  3451. auto authorization = get_digest_retry_authorization(
  3452. {"Digest realm=\"r\", nonce=\"n\", qop=\"AUTH\""});
  3453. EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
  3454. }
  3455. // auth-int hashes req.body, which is empty when a content provider streams the
  3456. // body, so it is chosen only when the server offers no auth.
  3457. TEST(DigestAuthTest, PrefersQopAuthOverAuthInt) {
  3458. auto authorization = get_digest_retry_authorization(
  3459. {"Digest realm=\"r\", nonce=\"n\", qop=\"auth-int, auth\""});
  3460. EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
  3461. authorization = get_digest_retry_authorization(
  3462. {"Digest realm=\"r\", nonce=\"n\", qop=\"Auth-Int\""});
  3463. EXPECT_NE(std::string::npos, authorization.find("qop=auth-int,"));
  3464. }
  3465. // RFC 7616 3.7: the client uses the first Digest challenge it can answer.
  3466. TEST(DigestAuthTest, SkipsUnanswerableDigestChallenges) {
  3467. auto authorization = get_digest_retry_authorization(
  3468. {"Digest realm=\"r\", nonce=\"n1\", algorithm=SHA-512-256, "
  3469. "Digest realm=\"r\", nonce=\"n2\", algorithm=SHA-256"});
  3470. EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
  3471. EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
  3472. authorization = get_digest_retry_authorization(
  3473. {"Digest realm=\"r\", qop=\"auth\", Digest realm=\"r\", nonce=\"n2\""});
  3474. EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
  3475. }
  3476. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3477. // the params and leaves out the fragment.
  3478. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3479. Server svr;
  3480. std::string uri, target;
  3481. svr.Get("/a b", [&](const Request &req, Response &res) {
  3482. auto auth = req.get_header_value("Authorization");
  3483. if (auth.empty()) {
  3484. res.status = StatusCode::Unauthorized_401;
  3485. res.set_header("WWW-Authenticate",
  3486. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3487. return;
  3488. }
  3489. auto b = auth.find("uri=\"") + 5;
  3490. uri = auth.substr(b, auth.find('"', b) - b);
  3491. target = req.target;
  3492. });
  3493. auto port = svr.bind_to_any_port(HOST);
  3494. std::thread t([&]() { svr.listen_after_bind(); });
  3495. auto se = detail::scope_exit([&] {
  3496. svr.stop();
  3497. t.join();
  3498. });
  3499. svr.wait_until_ready();
  3500. Client cli(HOST, port);
  3501. cli.set_digest_auth("hello", "world");
  3502. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3504. EXPECT_EQ("/a%20b?x=1", target);
  3505. EXPECT_EQ(target, uri);
  3506. }
  3507. // A Digest challenge the client can't answer (realm or nonce missing, or no
  3508. // algorithm or qop option it implements) must leave the 401 as it is, without
  3509. // a retry.
  3510. static void
  3511. run_unanswerable_digest_challenge_test(const std::string &challenge) {
  3512. std::atomic<int> hits{0};
  3513. Server svr;
  3514. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3515. ++hits;
  3516. res.status = StatusCode::Unauthorized_401;
  3517. res.set_header("WWW-Authenticate", challenge);
  3518. });
  3519. auto port = svr.bind_to_any_port(HOST);
  3520. std::thread t([&]() { svr.listen_after_bind(); });
  3521. auto se = detail::scope_exit([&] {
  3522. svr.stop();
  3523. t.join();
  3524. });
  3525. svr.wait_until_ready();
  3526. Client cli(HOST, port);
  3527. cli.set_digest_auth("hello", "world");
  3528. auto res = cli.Get("/x");
  3529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3530. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3531. EXPECT_EQ(1, hits.load());
  3532. }
  3533. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3534. run_unanswerable_digest_challenge_test("Digest qop=\"auth\"");
  3535. }
  3536. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3537. run_unanswerable_digest_challenge_test("Digest realm=\"r\", qop=\"auth\"");
  3538. }
  3539. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3540. run_unanswerable_digest_challenge_test("Digest nonce=\"n\", qop=\"auth\"");
  3541. }
  3542. // RFC 7616 3.3: a challenge with an algorithm the client doesn't implement is
  3543. // ignored. The last value isn't a token and would otherwise inject auth-params
  3544. // into the Authorization header.
  3545. TEST(DigestAuthTest, UnsupportedAlgorithmIsIgnored) {
  3546. for (auto algorithm :
  3547. {"SHA-512-256", "MD5-sess", "\"MD5, injected=\\\"y\\\"\""}) {
  3548. SCOPED_TRACE(algorithm);
  3549. run_unanswerable_digest_challenge_test(
  3550. std::string("Digest realm=\"r\", nonce=\"n\", qop=\"auth\", "
  3551. "algorithm=") +
  3552. algorithm);
  3553. }
  3554. }
  3555. // RFC 7616 3.3: qop options the client doesn't implement are ignored, and a
  3556. // challenge that offers no other can't be answered.
  3557. TEST(DigestAuthTest, UnsupportedQopIsIgnored) {
  3558. run_unanswerable_digest_challenge_test(
  3559. "Digest realm=\"r\", nonce=\"n\", qop=\"auth-conf\"");
  3560. }
  3561. // A hostile server can put a '"' in realm/nonce/opaque in its challenge.
  3562. // parse_www_authenticate() de-escapes quoted-pairs when storing the values, so
  3563. // the header builder has to re-escape them; otherwise the value breaks out of
  3564. // its quoted-string and injects extra auth-params into the Authorization.
  3565. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3566. // On the wire the quotes embedded in the value are backslash-escaped.
  3567. auto authorization = get_digest_retry_authorization(
  3568. {"Digest realm=\"testrealm\", nonce=\"n\\\"; injected=\\\"x\", "
  3569. "qop=\"auth\""});
  3570. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3571. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3572. // inside its quoted-string rather than starting an "injected" auth-param.
  3573. EXPECT_NE(std::string::npos,
  3574. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3575. }
  3576. #endif
  3577. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3578. auto host = "google.com";
  3579. auto another_host = "example.com";
  3580. auto wrong_ip = "0.0.0.0";
  3581. #ifdef CPPHTTPLIB_SSL_ENABLED
  3582. SSLClient cli(host);
  3583. #else
  3584. Client cli(host);
  3585. #endif
  3586. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3587. auto res = cli.Get("/");
  3588. // Any status: Google may redirect or rate-limit CI runners.
  3589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3590. }
  3591. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3592. auto host = "google.com";
  3593. auto wrong_ip = "0.0.0.0";
  3594. #ifdef CPPHTTPLIB_SSL_ENABLED
  3595. SSLClient cli(host);
  3596. #else
  3597. Client cli(host);
  3598. #endif
  3599. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3600. auto res = cli.Get("/");
  3601. ASSERT_TRUE(!res);
  3602. EXPECT_EQ(Error::Connection, res.error());
  3603. }
  3604. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3605. // A mapped value that is not an IP literal must be resolved. "localhost"
  3606. // resolves from the hosts file, so this test needs no external DNS.
  3607. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3608. auto host = "target.invalid";
  3609. Server svr;
  3610. std::string received_host;
  3611. svr.Get("/hi", [&](const Request &req, Response &res) {
  3612. received_host = req.get_header_value("Host");
  3613. res.set_content("Hello World!", "text/plain");
  3614. });
  3615. auto port = svr.bind_to_any_port(HOST);
  3616. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3617. auto se = detail::scope_exit([&] {
  3618. svr.stop();
  3619. thread.join();
  3620. ASSERT_FALSE(svr.is_running());
  3621. });
  3622. svr.wait_until_ready();
  3623. Client cli(host, port);
  3624. cli.set_direct_hostname_addr_map({{host, HOST}});
  3625. auto res = cli.Get("/hi");
  3626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3627. EXPECT_EQ(StatusCode::OK_200, res->status);
  3628. // The mapping only redirects the connection; the identity stays host_.
  3629. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3630. }
  3631. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3632. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3633. auto host = "target.invalid";
  3634. Server svr;
  3635. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3636. res.set_content("Hello World!", "text/plain");
  3637. });
  3638. auto port = svr.bind_to_any_port("127.0.0.1");
  3639. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3640. auto se = detail::scope_exit([&] {
  3641. svr.stop();
  3642. thread.join();
  3643. ASSERT_FALSE(svr.is_running());
  3644. });
  3645. svr.wait_until_ready();
  3646. Client cli(host, port);
  3647. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3648. auto res = cli.Get("/hi");
  3649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3650. EXPECT_EQ(StatusCode::OK_200, res->status);
  3651. }
  3652. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3653. // An empty mapped value must leave host_ as the connection target. Without
  3654. // that guard the empty value would become the host argument, getaddrinfo
  3655. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3656. // loopback - silently connecting somewhere the caller never asked for.
  3657. // The server listens on loopback, so such a fallback would succeed and is
  3658. // therefore observable as a failure of this test.
  3659. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3660. Server svr;
  3661. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3662. res.set_content("Hello World!", "text/plain");
  3663. });
  3664. auto port = svr.bind_to_any_port(HOST);
  3665. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3666. auto se = detail::scope_exit([&] {
  3667. svr.stop();
  3668. thread.join();
  3669. ASSERT_FALSE(svr.is_running());
  3670. });
  3671. svr.wait_until_ready();
  3672. Client cli(blackhole, port);
  3673. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3674. cli.set_connection_timeout(1);
  3675. auto res = cli.Get("/hi");
  3676. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3677. }
  3678. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3679. auto host = "target.invalid";
  3680. Server svr;
  3681. std::string received_host;
  3682. svr.Get("/hi", [&](const Request &req, Response &res) {
  3683. received_host = req.get_header_value("Host");
  3684. res.set_content("Hello World!", "text/plain");
  3685. });
  3686. auto port = svr.bind_to_any_port("127.0.0.1");
  3687. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3688. auto se = detail::scope_exit([&] {
  3689. svr.stop();
  3690. thread.join();
  3691. ASSERT_FALSE(svr.is_running());
  3692. });
  3693. svr.wait_until_ready();
  3694. Client cli(host, port);
  3695. #pragma GCC diagnostic push
  3696. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3697. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3698. #pragma GCC diagnostic pop
  3699. auto res = cli.Get("/hi");
  3700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3701. EXPECT_EQ(StatusCode::OK_200, res->status);
  3702. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3703. }
  3704. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3705. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3706. Server svr;
  3707. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3708. res.set_content("Hello World!", "text/plain");
  3709. });
  3710. auto port = svr.bind_to_any_port("127.0.0.1");
  3711. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3712. auto se = detail::scope_exit([&] {
  3713. svr.stop();
  3714. thread.join();
  3715. ASSERT_FALSE(svr.is_running());
  3716. });
  3717. svr.wait_until_ready();
  3718. Client cli("127.0.0.1", port);
  3719. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3720. cli.set_connection_timeout(1);
  3721. auto res = cli.Get("/hi");
  3722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3723. EXPECT_EQ(StatusCode::OK_200, res->status);
  3724. }
  3725. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3726. auto host = "httpbingo.org";
  3727. auto path = std::string{"/absolute-redirect/3"};
  3728. #ifdef CPPHTTPLIB_SSL_ENABLED
  3729. SSLClient cli(host);
  3730. #else
  3731. Client cli(host);
  3732. #endif
  3733. cli.set_follow_location(true);
  3734. auto res = retry_service_failures([&] { return cli.Get(path); });
  3735. SKIP_ON_SERVICE_FAILURE(res);
  3736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3737. EXPECT_EQ(StatusCode::OK_200, res->status);
  3738. }
  3739. TEST(RedirectTest, Redirect_Online) {
  3740. auto host = "httpbingo.org";
  3741. auto path = std::string{"/redirect/3"};
  3742. #ifdef CPPHTTPLIB_SSL_ENABLED
  3743. SSLClient cli(host);
  3744. #else
  3745. Client cli(host);
  3746. #endif
  3747. cli.set_follow_location(true);
  3748. auto res = retry_service_failures([&] { return cli.Get(path); });
  3749. SKIP_ON_SERVICE_FAILURE(res);
  3750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3751. EXPECT_EQ(StatusCode::OK_200, res->status);
  3752. }
  3753. TEST(RelativeRedirectTest, Redirect_Online) {
  3754. auto host = "httpbingo.org";
  3755. auto path = std::string{"/relative-redirect/3"};
  3756. #ifdef CPPHTTPLIB_SSL_ENABLED
  3757. SSLClient cli(host);
  3758. #else
  3759. Client cli(host);
  3760. #endif
  3761. cli.set_follow_location(true);
  3762. auto res = retry_service_failures([&] { return cli.Get(path); });
  3763. SKIP_ON_SERVICE_FAILURE(res);
  3764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3765. EXPECT_EQ(StatusCode::OK_200, res->status);
  3766. }
  3767. TEST(TooManyRedirectTest, Redirect_Online) {
  3768. auto host = "httpbingo.org";
  3769. auto path = std::string{"/redirect/21"};
  3770. #ifdef CPPHTTPLIB_SSL_ENABLED
  3771. SSLClient cli(host);
  3772. #else
  3773. Client cli(host);
  3774. #endif
  3775. cli.set_follow_location(true);
  3776. auto res = retry_service_failures([&] { return cli.Get(path); });
  3777. SKIP_ON_SERVICE_FAILURE(res);
  3778. ASSERT_TRUE(!res);
  3779. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3780. }
  3781. #ifdef CPPHTTPLIB_SSL_ENABLED
  3782. TEST(YahooRedirectTest, Redirect_Online) {
  3783. Client cli("yahoo.com");
  3784. auto res = cli.Get("/");
  3785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3786. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3787. cli.set_follow_location(true);
  3788. res = cli.Get("/");
  3789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3790. EXPECT_EQ(StatusCode::OK_200, res->status);
  3791. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3792. }
  3793. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3794. #define REDIR_HOST "httpbingo.org"
  3795. #define REDIR_PATH "/redirect-to"
  3796. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3797. SSLClient cli(REDIR_HOST);
  3798. cli.set_follow_location(true);
  3799. auto res = retry_service_failures([&] {
  3800. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3801. });
  3802. SKIP_ON_SERVICE_FAILURE(res);
  3803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3804. EXPECT_EQ(StatusCode::OK_200, res->status);
  3805. }
  3806. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3807. SSLClient cli(REDIR_HOST);
  3808. cli.set_follow_location(true);
  3809. Params params;
  3810. params.emplace("url", "http://example.com");
  3811. params.emplace("status_code", "302");
  3812. auto res = retry_service_failures(
  3813. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  3814. SKIP_ON_SERVICE_FAILURE(res);
  3815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3816. EXPECT_EQ(StatusCode::OK_200, res->status);
  3817. }
  3818. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3819. SSLClient cli(REDIR_HOST);
  3820. cli.set_follow_location(true);
  3821. Params params;
  3822. params.emplace("url", "http://example.com");
  3823. auto res = retry_service_failures([&] {
  3824. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3825. });
  3826. SKIP_ON_SERVICE_FAILURE(res);
  3827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3828. EXPECT_EQ(StatusCode::OK_200, res->status);
  3829. }
  3830. TEST(UrlWithSpace, Redirect_Online) {
  3831. SSLClient cli("edge.forgecdn.net");
  3832. cli.set_follow_location(true);
  3833. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3835. EXPECT_EQ(StatusCode::OK_200, res->status);
  3836. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3837. }
  3838. #endif
  3839. #if !defined(_WIN32) && !defined(_WIN64)
  3840. TEST(ReceiveSignals, Signal) {
  3841. auto setupSignalHandlers = []() {
  3842. struct sigaction act;
  3843. sigemptyset(&act.sa_mask);
  3844. act.sa_flags = SA_SIGINFO;
  3845. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3846. switch (sig) {
  3847. case SIGINT:
  3848. default: break;
  3849. }
  3850. };
  3851. ::sigaction(SIGINT, &act, nullptr);
  3852. };
  3853. Server svr;
  3854. int port = 0;
  3855. auto thread = std::thread([&]() {
  3856. setupSignalHandlers();
  3857. port = svr.bind_to_any_port(HOST);
  3858. svr.listen_after_bind();
  3859. });
  3860. auto se = detail::scope_exit([&] {
  3861. svr.stop();
  3862. thread.join();
  3863. ASSERT_FALSE(svr.is_running());
  3864. });
  3865. svr.wait_until_ready();
  3866. ASSERT_TRUE(svr.is_running());
  3867. pthread_kill(thread.native_handle(), SIGINT);
  3868. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3869. ASSERT_TRUE(svr.is_running());
  3870. }
  3871. #endif
  3872. TEST(RedirectToDifferentPort, Redirect) {
  3873. Server svr1;
  3874. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3875. res.set_content("Hello World!", "text/plain");
  3876. });
  3877. int svr1_port = 0;
  3878. auto thread1 = std::thread([&]() {
  3879. svr1_port = svr1.bind_to_any_port(HOST);
  3880. svr1.listen_after_bind();
  3881. });
  3882. Server svr2;
  3883. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3884. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3885. });
  3886. int svr2_port = 0;
  3887. auto thread2 = std::thread([&]() {
  3888. svr2_port = svr2.bind_to_any_port(HOST);
  3889. svr2.listen_after_bind();
  3890. });
  3891. auto se = detail::scope_exit([&] {
  3892. svr2.stop();
  3893. thread2.join();
  3894. svr1.stop();
  3895. thread1.join();
  3896. ASSERT_FALSE(svr2.is_running());
  3897. ASSERT_FALSE(svr1.is_running());
  3898. });
  3899. svr1.wait_until_ready();
  3900. svr2.wait_until_ready();
  3901. Client cli("localhost", svr2_port);
  3902. cli.set_follow_location(true);
  3903. auto res = cli.Get("/2");
  3904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3905. EXPECT_EQ(StatusCode::OK_200, res->status);
  3906. EXPECT_EQ("Hello World!", res->body);
  3907. }
  3908. // GET /redir on one server redirects to /target on another port, so the
  3909. // client follows it with a new client.
  3910. static Result
  3911. GetThroughRedirectToDifferentPort(Server::Handler target,
  3912. const std::function<void(Client &)> &setup,
  3913. const Headers &headers = Headers()) {
  3914. Server target_svr;
  3915. target_svr.Get("/target", target);
  3916. int target_port = 0;
  3917. auto target_thread = std::thread([&]() {
  3918. target_port = target_svr.bind_to_any_port(HOST);
  3919. target_svr.listen_after_bind();
  3920. });
  3921. Server origin_svr;
  3922. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3923. res.set_redirect(
  3924. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3925. });
  3926. int origin_port = 0;
  3927. auto origin_thread = std::thread([&]() {
  3928. origin_port = origin_svr.bind_to_any_port(HOST);
  3929. origin_svr.listen_after_bind();
  3930. });
  3931. auto se = detail::scope_exit([&] {
  3932. origin_svr.stop();
  3933. origin_thread.join();
  3934. target_svr.stop();
  3935. target_thread.join();
  3936. });
  3937. target_svr.wait_until_ready();
  3938. origin_svr.wait_until_ready();
  3939. Client cli("localhost", origin_port);
  3940. cli.set_follow_location(true);
  3941. setup(cli);
  3942. return cli.Get("/redir", headers);
  3943. }
  3944. static void
  3945. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3946. std::string captured_authorization;
  3947. auto result = GetThroughRedirectToDifferentPort(
  3948. [&](const Request &req, Response &res) {
  3949. captured_authorization = req.get_header_value("Authorization");
  3950. res.set_content("OK", "text/plain");
  3951. },
  3952. set_auth);
  3953. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3954. EXPECT_EQ(StatusCode::OK_200, result->status);
  3955. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3956. EXPECT_TRUE(captured_authorization.empty());
  3957. }
  3958. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3959. TestDoNotForwardCredentialsOnRedirect(
  3960. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3961. }
  3962. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3963. TestDoNotForwardCredentialsOnRedirect(
  3964. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3965. }
  3966. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3967. std::string captured_cookie;
  3968. auto result = GetThroughRedirectToDifferentPort(
  3969. [&](const Request &req, Response &res) {
  3970. captured_cookie = req.get_header_value("Cookie");
  3971. res.set_content("OK", "text/plain");
  3972. },
  3973. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3974. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3975. EXPECT_EQ(StatusCode::OK_200, result->status);
  3976. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3977. EXPECT_TRUE(captured_cookie.empty());
  3978. }
  3979. TEST(RedirectToSamePort, ForwardCookie) {
  3980. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3981. // header so that ordinary session flows keep working.
  3982. Server svr;
  3983. std::string captured_cookie;
  3984. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3985. res.set_redirect("/target", 302);
  3986. });
  3987. svr.Get("/target", [&](const Request &req, Response &res) {
  3988. captured_cookie = req.get_header_value("Cookie");
  3989. res.set_content("OK", "text/plain");
  3990. });
  3991. auto port = svr.bind_to_any_port(HOST);
  3992. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3993. auto se = detail::scope_exit([&] {
  3994. svr.stop();
  3995. thread.join();
  3996. ASSERT_FALSE(svr.is_running());
  3997. });
  3998. svr.wait_until_ready();
  3999. Client cli(HOST, port);
  4000. cli.set_follow_location(true);
  4001. Headers headers = {{"Cookie", "session_id=SECRET"}};
  4002. auto res = cli.Get("/redir", headers);
  4003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4004. EXPECT_EQ(StatusCode::OK_200, res->status);
  4005. EXPECT_EQ("session_id=SECRET", captured_cookie);
  4006. }
  4007. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  4008. // The Location alone names the next target, on any origin.
  4009. Server target_svr;
  4010. std::string cross_target;
  4011. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  4012. cross_target = req.target;
  4013. res.set_content("OK", "text/plain");
  4014. });
  4015. auto target_port = target_svr.bind_to_any_port(HOST);
  4016. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  4017. Server origin_svr;
  4018. std::string same_target;
  4019. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  4020. res.set_redirect(
  4021. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  4022. });
  4023. origin_svr.Get("/same", [&](const Request &, Response &res) {
  4024. res.set_redirect("/landing", 302);
  4025. });
  4026. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  4027. same_target = req.target;
  4028. res.set_content("OK", "text/plain");
  4029. });
  4030. auto origin_port = origin_svr.bind_to_any_port(HOST);
  4031. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  4032. auto se = detail::scope_exit([&] {
  4033. origin_svr.stop();
  4034. origin_thread.join();
  4035. target_svr.stop();
  4036. target_thread.join();
  4037. });
  4038. target_svr.wait_until_ready();
  4039. origin_svr.wait_until_ready();
  4040. Client cli("localhost", origin_port);
  4041. cli.set_follow_location(true);
  4042. Request req;
  4043. req.method = "GET";
  4044. req.params = {{"api_key", "SECRET"}};
  4045. req.path = "/cross";
  4046. auto res = cli.send(req);
  4047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4048. EXPECT_EQ("/landing", cross_target);
  4049. req.path = "/same";
  4050. res = cli.send(req);
  4051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4052. EXPECT_EQ("/landing", same_target);
  4053. }
  4054. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  4055. std::string authorization;
  4056. std::string trace_id;
  4057. auto result = GetThroughRedirectToDifferentPort(
  4058. [&](const Request &req, Response &res) {
  4059. authorization = req.get_header_value("Authorization");
  4060. trace_id = req.get_header_value("X-Trace-Id");
  4061. res.set_content("OK", "text/plain");
  4062. },
  4063. [](Client &cli) {
  4064. cli.set_default_headers(
  4065. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  4066. });
  4067. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4068. EXPECT_EQ(StatusCode::OK_200, result->status);
  4069. // Like a header given with the request, a default one goes along unless it
  4070. // carries credentials (RFC 9110 15.4).
  4071. EXPECT_TRUE(authorization.empty());
  4072. EXPECT_EQ("42", trace_id);
  4073. }
  4074. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  4075. auto result = GetThroughRedirectToDifferentPort(
  4076. [](const Request &, Response &res) {
  4077. res.set_content(std::string(2048, 'x'), "text/plain");
  4078. },
  4079. [](Client &cli) { cli.set_payload_max_length(1024); });
  4080. EXPECT_FALSE(result);
  4081. }
  4082. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  4083. auto result = GetThroughRedirectToDifferentPort(
  4084. [](const Request &req, Response &res) {
  4085. // Answer after a second, or once the client gives up.
  4086. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  4087. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4088. }
  4089. res.set_content("late", "text/plain");
  4090. },
  4091. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  4092. ASSERT_FALSE(result);
  4093. EXPECT_EQ(Error::Read, result.error());
  4094. }
  4095. #ifdef CPPHTTPLIB_SSL_ENABLED
  4096. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  4097. auto result = GetThroughRedirectToDifferentPort(
  4098. [](const Request &, Response &res) {
  4099. res.status = StatusCode::Unauthorized_401;
  4100. res.set_header("WWW-Authenticate",
  4101. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  4102. },
  4103. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  4104. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4105. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  4106. }
  4107. #endif
  4108. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  4109. Server svr;
  4110. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4111. // Port number that overflows int — should not crash
  4112. res.set_redirect("http://localhost:99999999999999999999/target");
  4113. });
  4114. auto port = svr.bind_to_any_port(HOST);
  4115. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4116. auto se = detail::scope_exit([&] {
  4117. svr.stop();
  4118. thread.join();
  4119. ASSERT_FALSE(svr.is_running());
  4120. });
  4121. svr.wait_until_ready();
  4122. Client cli(HOST, port);
  4123. cli.set_follow_location(true);
  4124. auto res = cli.Get("/redir");
  4125. // Should fail gracefully, not crash (no valid response due to bad port)
  4126. EXPECT_FALSE(res);
  4127. }
  4128. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  4129. Server svr;
  4130. auto port = svr.bind_to_any_port(HOST);
  4131. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4132. // The server's own port followed by junk must not be followed
  4133. res.set_redirect("http://" + std::string(HOST) + ":" +
  4134. std::to_string(port) + "junk/target");
  4135. });
  4136. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4137. res.set_content("target", "text/plain");
  4138. });
  4139. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4140. auto se = detail::scope_exit([&] {
  4141. svr.stop();
  4142. thread.join();
  4143. ASSERT_FALSE(svr.is_running());
  4144. });
  4145. svr.wait_until_ready();
  4146. Client cli(HOST, port);
  4147. cli.set_follow_location(true);
  4148. auto res = cli.Get("/redir");
  4149. EXPECT_FALSE(res);
  4150. }
  4151. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4152. Server target_svr;
  4153. std::atomic<int> target_hits{0};
  4154. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4155. target_hits++;
  4156. res.set_content("target", "text/plain");
  4157. });
  4158. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4159. res.set_content("target", "text/plain");
  4160. });
  4161. int target_port = 0;
  4162. auto target_thread = std::thread([&]() {
  4163. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4164. target_svr.listen_after_bind();
  4165. });
  4166. Server origin_svr;
  4167. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4168. res.set_redirect(req.get_param_value("to"));
  4169. });
  4170. int origin_port = 0;
  4171. auto origin_thread = std::thread([&]() {
  4172. origin_port = origin_svr.bind_to_any_port(HOST);
  4173. origin_svr.listen_after_bind();
  4174. });
  4175. auto se = detail::scope_exit([&] {
  4176. origin_svr.stop();
  4177. origin_thread.join();
  4178. target_svr.stop();
  4179. target_thread.join();
  4180. ASSERT_FALSE(origin_svr.is_running());
  4181. ASSERT_FALSE(target_svr.is_running());
  4182. });
  4183. target_svr.wait_until_ready();
  4184. origin_svr.wait_until_ready();
  4185. auto port = std::to_string(target_port);
  4186. for (const auto &to :
  4187. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4188. Client cli(HOST, origin_port);
  4189. cli.set_follow_location(true);
  4190. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4191. EXPECT_FALSE(res) << to;
  4192. }
  4193. EXPECT_EQ(0, target_hits);
  4194. Client cli(HOST, origin_port);
  4195. cli.set_follow_location(true);
  4196. auto res = cli.Get("/redir?to=" +
  4197. encode_query_component("//127.0.0.1:" + port + "/target"));
  4198. ASSERT_TRUE(res) << to_string(res.error());
  4199. EXPECT_EQ(StatusCode::OK_200, res->status);
  4200. EXPECT_EQ("target", res->body);
  4201. }
  4202. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4203. Server svr;
  4204. std::atomic<bool> followed{false};
  4205. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4206. res.status = StatusCode::NotModified_304;
  4207. res.set_header("Location", "/target");
  4208. });
  4209. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4210. res.status = StatusCode::UseProxy_305;
  4211. res.set_header("Location", "/target");
  4212. });
  4213. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4214. followed = true;
  4215. res.set_content("target", "text/plain");
  4216. });
  4217. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4218. auto se = detail::scope_exit([&] {
  4219. svr.stop();
  4220. th.join();
  4221. ASSERT_FALSE(svr.is_running());
  4222. });
  4223. svr.wait_until_ready();
  4224. Client cli("localhost", PORT);
  4225. cli.set_follow_location(true);
  4226. auto res = cli.Get("/304");
  4227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4228. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4229. res = cli.Get("/305");
  4230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4231. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4232. EXPECT_FALSE(followed);
  4233. }
  4234. TEST(RedirectFromPageWithContent, Redirect) {
  4235. Server svr;
  4236. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4237. res.set_content("___", "text/plain");
  4238. res.set_redirect("/2");
  4239. });
  4240. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4241. res.set_content("Hello World!", "text/plain");
  4242. });
  4243. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4244. auto se = detail::scope_exit([&] {
  4245. svr.stop();
  4246. th.join();
  4247. ASSERT_FALSE(svr.is_running());
  4248. });
  4249. svr.wait_until_ready();
  4250. {
  4251. Client cli("localhost", PORT);
  4252. cli.set_follow_location(true);
  4253. std::string body;
  4254. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4255. body.append(data, data_length);
  4256. return true;
  4257. });
  4258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4259. EXPECT_EQ(StatusCode::OK_200, res->status);
  4260. EXPECT_EQ("Hello World!", body);
  4261. }
  4262. {
  4263. Client cli("localhost", PORT);
  4264. std::string body;
  4265. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4266. body.append(data, data_length);
  4267. return true;
  4268. });
  4269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4270. EXPECT_EQ(StatusCode::Found_302, res->status);
  4271. EXPECT_EQ("___", body);
  4272. }
  4273. }
  4274. // A server can close the connection after a request with "Connection: close"
  4275. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4276. // redirected request must go out on a new connection.
  4277. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4278. #ifndef _WIN32
  4279. signal(SIGPIPE, SIG_IGN);
  4280. #endif
  4281. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4282. default_socket_options(srv);
  4283. sockaddr_in addr{};
  4284. addr.sin_family = AF_INET;
  4285. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4286. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4287. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4288. ASSERT_EQ(0, ::listen(srv, 2));
  4289. auto send_text = [](socket_t sock, const std::string &text) {
  4290. ::send(sock,
  4291. #ifdef _WIN32
  4292. static_cast<const char *>(text.c_str()),
  4293. static_cast<int>(text.size()),
  4294. #else
  4295. text.c_str(), text.size(),
  4296. #endif
  4297. 0);
  4298. };
  4299. auto reused = false;
  4300. auto server_thread = std::thread([&] {
  4301. char buf[4096];
  4302. auto first = ::accept(srv, nullptr, nullptr);
  4303. if (first == INVALID_SOCKET) { return; }
  4304. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4305. ::recv(first, buf, sizeof(buf), 0);
  4306. send_text(
  4307. first,
  4308. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4309. auto next = first;
  4310. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4311. reused = true;
  4312. } else {
  4313. detail::close_socket(first);
  4314. next = ::accept(srv, nullptr, nullptr);
  4315. if (next == INVALID_SOCKET) { return; }
  4316. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4317. ::recv(next, buf, sizeof(buf), 0);
  4318. }
  4319. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4320. "Connection: close\r\n\r\nok");
  4321. detail::close_socket(next);
  4322. });
  4323. Client cli("127.0.0.1", PORT + 2);
  4324. cli.set_follow_location(true);
  4325. cli.set_read_timeout(5, 0);
  4326. auto res = cli.Get("/1");
  4327. server_thread.join();
  4328. detail::close_socket(srv);
  4329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4330. EXPECT_EQ(StatusCode::OK_200, res->status);
  4331. EXPECT_EQ("ok", res->body);
  4332. EXPECT_FALSE(reused);
  4333. }
  4334. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4335. Server svr;
  4336. auto port_str = std::to_string(PORT);
  4337. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4338. auto expected_host = "[::1]:" + port_str;
  4339. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4340. res.set_content("___", "text/plain");
  4341. // res.set_redirect("/2");
  4342. res.set_redirect(redirect_url);
  4343. });
  4344. svr.Get("/2", [&](const Request &req, Response &res) {
  4345. auto host_header = req.headers.find("Host");
  4346. ASSERT_TRUE(host_header != req.headers.end());
  4347. EXPECT_EQ(expected_host, host_header->second);
  4348. res.set_content("Hello World!", "text/plain");
  4349. });
  4350. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4351. auto se = detail::scope_exit([&] {
  4352. svr.stop();
  4353. th.join();
  4354. ASSERT_FALSE(svr.is_running());
  4355. });
  4356. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4357. // actually starts anything, so the condition !svr.is_running() will
  4358. // always remain true, and the loop never stops.
  4359. // This basically counts how many milliseconds have passed since the
  4360. // call to svr.listen(), and if after 5 seconds nothing started yet
  4361. // aborts the test.
  4362. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4363. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4364. ASSERT_LT(milliseconds, 5000U);
  4365. }
  4366. {
  4367. Client cli("::1", PORT);
  4368. cli.set_follow_location(true);
  4369. std::string body;
  4370. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4371. body.append(data, data_length);
  4372. return true;
  4373. });
  4374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4375. EXPECT_EQ(StatusCode::OK_200, res->status);
  4376. EXPECT_EQ("Hello World!", body);
  4377. }
  4378. {
  4379. Client cli("::1", PORT);
  4380. std::string body;
  4381. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4382. body.append(data, data_length);
  4383. return true;
  4384. });
  4385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4386. EXPECT_EQ(StatusCode::Found_302, res->status);
  4387. EXPECT_EQ("___", body);
  4388. }
  4389. }
  4390. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4391. Server svr;
  4392. svr.Get("/foo", [](const Request &req, Response &res) {
  4393. auto a = req.params.find("a");
  4394. if (a != req.params.end()) {
  4395. res.set_content((*a).second, "text/plain");
  4396. res.status = StatusCode::OK_200;
  4397. } else {
  4398. res.status = StatusCode::BadRequest_400;
  4399. }
  4400. });
  4401. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4402. auto se = detail::scope_exit([&] {
  4403. svr.stop();
  4404. thread.join();
  4405. ASSERT_FALSE(svr.is_running());
  4406. });
  4407. svr.wait_until_ready();
  4408. {
  4409. Client cli(HOST, PORT);
  4410. cli.set_path_encode(false);
  4411. auto res = cli.Get("/foo?a=explicitly+encoded");
  4412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4413. EXPECT_EQ(StatusCode::OK_200, res->status);
  4414. // This expects it back with a space, as the `+` won't have been
  4415. // url-encoded, and server-side the params get decoded turning `+`
  4416. // into spaces.
  4417. EXPECT_EQ("explicitly encoded", res->body);
  4418. }
  4419. }
  4420. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4421. // When path encoding is disabled the client must transmit the supplied
  4422. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4423. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4424. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4425. // than a space (0x20). Assert on the raw wire target to catch this.
  4426. Server svr;
  4427. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4428. svr.Get("/foo", [&](const Request &req, Response &res) {
  4429. EXPECT_EQ(expected_target, req.target);
  4430. res.status = StatusCode::OK_200;
  4431. });
  4432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4433. auto se = detail::scope_exit([&] {
  4434. svr.stop();
  4435. thread.join();
  4436. ASSERT_FALSE(svr.is_running());
  4437. });
  4438. svr.wait_until_ready();
  4439. {
  4440. Client cli(HOST, PORT);
  4441. cli.set_path_encode(false);
  4442. auto res = cli.Get(expected_target.c_str());
  4443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4444. EXPECT_EQ(StatusCode::OK_200, res->status);
  4445. }
  4446. }
  4447. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4448. // `open_stream()` used to skip the path encoding that the buffered send
  4449. // path applies, so the same `path` produced different bytes in the request
  4450. // line depending on which API was used. Assert the two agree.
  4451. Server svr;
  4452. std::string target;
  4453. svr.Get(".*", [&](const Request &req, Response &res) {
  4454. target = req.target;
  4455. res.status = StatusCode::OK_200;
  4456. });
  4457. auto port = svr.bind_to_any_port(HOST);
  4458. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4459. auto se = detail::scope_exit([&] {
  4460. svr.stop();
  4461. thread.join();
  4462. ASSERT_FALSE(svr.is_running());
  4463. });
  4464. svr.wait_until_ready();
  4465. struct {
  4466. const char *path;
  4467. const char *expected;
  4468. } cases[] = {
  4469. {"/a b?x=1", "/a%20b?x=1"},
  4470. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4471. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4472. };
  4473. for (const auto &c : cases) {
  4474. Client cli(HOST, port);
  4475. target.clear();
  4476. auto res = cli.Get(c.path);
  4477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4478. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4479. auto buffered_target = target;
  4480. target.clear();
  4481. auto handle = cli.open_stream("GET", c.path);
  4482. EXPECT_TRUE(handle.is_valid())
  4483. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4484. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4485. }
  4486. }
  4487. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4488. // The `set_path_encode(false)` contract — transmit the supplied target
  4489. // verbatim — must hold for the streaming API too.
  4490. Server svr;
  4491. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4492. std::string target;
  4493. svr.Get("/foo", [&](const Request &req, Response &res) {
  4494. target = req.target;
  4495. res.status = StatusCode::OK_200;
  4496. });
  4497. auto port = svr.bind_to_any_port(HOST);
  4498. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4499. auto se = detail::scope_exit([&] {
  4500. svr.stop();
  4501. thread.join();
  4502. ASSERT_FALSE(svr.is_running());
  4503. });
  4504. svr.wait_until_ready();
  4505. {
  4506. Client cli(HOST, port);
  4507. cli.set_path_encode(false);
  4508. auto handle = cli.open_stream("GET", expected_target);
  4509. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4510. EXPECT_EQ(expected_target, target);
  4511. }
  4512. }
  4513. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4514. // With path encoding enabled a CR/LF in the target is percent-encoded
  4515. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4516. // write_request_line still backstops `set_path_encode(false)`, which is
  4517. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4518. Server svr;
  4519. // Captured before routing: the decoded path contains a newline, which a
  4520. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4521. std::string target;
  4522. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4523. target = req.target;
  4524. res.status = StatusCode::OK_200;
  4525. return Server::HandlerResponse::Handled;
  4526. });
  4527. auto port = svr.bind_to_any_port(HOST);
  4528. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4529. auto se = detail::scope_exit([&] {
  4530. svr.stop();
  4531. thread.join();
  4532. ASSERT_FALSE(svr.is_running());
  4533. });
  4534. svr.wait_until_ready();
  4535. {
  4536. Client cli(HOST, port);
  4537. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4538. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4539. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4540. }
  4541. }
  4542. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4543. // Every control character is percent-encoded, not just CR/LF, so the target
  4544. // passes the request-target check in write_request_line.
  4545. Server svr;
  4546. std::string target;
  4547. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4548. target = req.target;
  4549. res.status = StatusCode::OK_200;
  4550. return Server::HandlerResponse::Handled;
  4551. });
  4552. auto port = svr.bind_to_any_port(HOST);
  4553. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4554. auto se = detail::scope_exit([&] {
  4555. svr.stop();
  4556. thread.join();
  4557. ASSERT_FALSE(svr.is_running());
  4558. });
  4559. svr.wait_until_ready();
  4560. {
  4561. Client cli(HOST, port);
  4562. auto res = cli.Get("/a\tb\x1b\x7f");
  4563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4564. EXPECT_EQ("/a%09b%1B%7F", target);
  4565. }
  4566. }
  4567. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4568. // Nothing may reach the wire: a raw CR/LF target would split the request
  4569. // line and inject headers.
  4570. Server svr;
  4571. // Pre-routing so that "not called" means nothing reached the server at all,
  4572. // rather than merely failing to match a handler pattern.
  4573. auto handler_called = false;
  4574. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4575. handler_called = true;
  4576. res.status = StatusCode::OK_200;
  4577. return Server::HandlerResponse::Handled;
  4578. });
  4579. auto port = svr.bind_to_any_port(HOST);
  4580. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4581. auto se = detail::scope_exit([&] {
  4582. svr.stop();
  4583. thread.join();
  4584. ASSERT_FALSE(svr.is_running());
  4585. });
  4586. svr.wait_until_ready();
  4587. {
  4588. Client cli(HOST, port);
  4589. cli.set_path_encode(false);
  4590. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4591. EXPECT_FALSE(handle.is_valid());
  4592. EXPECT_EQ(Error::Write, handle.error);
  4593. EXPECT_FALSE(handler_called);
  4594. }
  4595. }
  4596. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4597. // Which of the two branches runs is decided by whether the query component
  4598. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4599. // an empty query and must still fall back to building one from
  4600. // `req.params`, while a non-empty query must win over `req.params`.
  4601. Server svr;
  4602. std::string target;
  4603. svr.Get("/foo", [&](const Request &req, Response &res) {
  4604. target = req.target;
  4605. res.status = StatusCode::OK_200;
  4606. });
  4607. auto port = svr.bind_to_any_port(HOST);
  4608. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4609. auto se = detail::scope_exit([&] {
  4610. svr.stop();
  4611. thread.join();
  4612. ASSERT_FALSE(svr.is_running());
  4613. });
  4614. svr.wait_until_ready();
  4615. {
  4616. // Trailing `?` -> empty query component -> `req.params` is used.
  4617. Client cli(HOST, port);
  4618. Request req;
  4619. req.method = "GET";
  4620. req.path = "/foo?";
  4621. req.params.emplace("a", "1");
  4622. target.clear();
  4623. auto res = cli.send(req);
  4624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4625. EXPECT_EQ("/foo?a=1", target);
  4626. }
  4627. {
  4628. // Non-empty query in `req.path` -> `req.params` is not appended.
  4629. Client cli(HOST, port);
  4630. Request req;
  4631. req.method = "GET";
  4632. req.path = "/foo?b=2";
  4633. req.params.emplace("a", "1");
  4634. target.clear();
  4635. auto res = cli.send(req);
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ("/foo?b=2", target);
  4638. }
  4639. }
  4640. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4641. Server svr;
  4642. svr.Get("/", [](const Request &req, Response &) {
  4643. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4644. });
  4645. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4646. auto se = detail::scope_exit([&] {
  4647. svr.stop();
  4648. thread.join();
  4649. ASSERT_FALSE(svr.is_running());
  4650. });
  4651. svr.wait_until_ready();
  4652. {
  4653. Client cli(HOST, PORT);
  4654. cli.set_path_encode(false);
  4655. auto res = cli.Get("/?something=%0A");
  4656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4657. EXPECT_EQ(StatusCode::OK_200, res->status);
  4658. }
  4659. }
  4660. TEST(BindServerTest, BindDualStack) {
  4661. Server svr;
  4662. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4663. res.set_content("Hello World!", "text/plain");
  4664. });
  4665. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4666. auto se = detail::scope_exit([&] {
  4667. svr.stop();
  4668. thread.join();
  4669. ASSERT_FALSE(svr.is_running());
  4670. });
  4671. svr.wait_until_ready();
  4672. {
  4673. Client cli("127.0.0.1", PORT);
  4674. auto res = cli.Get("/1");
  4675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4676. EXPECT_EQ(StatusCode::OK_200, res->status);
  4677. EXPECT_EQ("Hello World!", res->body);
  4678. }
  4679. {
  4680. Client cli("::1", PORT);
  4681. auto res = cli.Get("/1");
  4682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4683. EXPECT_EQ(StatusCode::OK_200, res->status);
  4684. EXPECT_EQ("Hello World!", res->body);
  4685. }
  4686. }
  4687. TEST(BindServerTest, BindAndListenSeparately) {
  4688. Server svr;
  4689. int port = svr.bind_to_any_port("0.0.0.0");
  4690. ASSERT_TRUE(svr.is_valid());
  4691. ASSERT_TRUE(port > 0);
  4692. svr.stop();
  4693. }
  4694. // Reports whether anything is still listening on a loopback port. A plain
  4695. // connect() is used instead of a Client request because a socket left bound by
  4696. // mistake accepts the connection into its backlog and never answers, which
  4697. // would hang the test instead of failing it.
  4698. static bool is_loopback_port_accepting(int port) {
  4699. sockaddr_in addr{};
  4700. addr.sin_family = AF_INET;
  4701. addr.sin_port = htons(static_cast<uint16_t>(port));
  4702. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4703. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4704. EXPECT_NE(sock, INVALID_SOCKET);
  4705. if (sock == INVALID_SOCKET) { return false; }
  4706. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4707. static_cast<socklen_t>(sizeof(addr)));
  4708. detail::close_socket(sock);
  4709. return ret == 0;
  4710. }
  4711. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4712. Server svr;
  4713. auto port = svr.bind_to_any_port("127.0.0.1");
  4714. ASSERT_TRUE(port > 0);
  4715. svr.stop();
  4716. // bind_to_any_port() already called listen(2), so until stop() closed the
  4717. // descriptor the port kept accepting connections into the backlog. ASSERT
  4718. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4719. // below blocks forever in the accept loop.
  4720. ASSERT_FALSE(is_loopback_port_accepting(port));
  4721. // Nothing is left to accept on, so listen_after_bind() must report failure
  4722. // instead of returning success without ever serving.
  4723. EXPECT_FALSE(svr.listen_after_bind());
  4724. // The failed listen marks the server decommissioned, so a waiter returns
  4725. // instead of spinning forever.
  4726. svr.wait_until_ready();
  4727. }
  4728. #ifdef CPPHTTPLIB_SSL_ENABLED
  4729. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4730. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4731. CLIENT_CA_CERT_DIR);
  4732. int port = svr.bind_to_any_port("0.0.0.0");
  4733. ASSERT_TRUE(svr.is_valid());
  4734. ASSERT_TRUE(port > 0);
  4735. svr.stop();
  4736. }
  4737. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4738. // or a rejected CustomRoute() registration would not stop the server binding.
  4739. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4740. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4741. CLIENT_CA_CERT_DIR);
  4742. ASSERT_TRUE(svr.is_valid());
  4743. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4744. EXPECT_FALSE(svr.is_valid());
  4745. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4746. }
  4747. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4748. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4749. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4750. int port = svr.bind_to_any_port("0.0.0.0");
  4751. ASSERT_TRUE(svr.is_valid());
  4752. ASSERT_TRUE(port > 0);
  4753. svr.stop();
  4754. }
  4755. TEST(BindServerTest, UpdateCertsPem) {
  4756. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4757. int port = svr.bind_to_any_port("0.0.0.0");
  4758. ASSERT_TRUE(svr.is_valid());
  4759. ASSERT_TRUE(port > 0);
  4760. // Read PEM files
  4761. std::string cert_pem, key_pem, ca_pem;
  4762. read_file(SERVER_CERT_FILE, cert_pem);
  4763. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4764. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4765. // Update server certificates using PEM API
  4766. ASSERT_TRUE(
  4767. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4768. ASSERT_TRUE(svr.is_valid());
  4769. svr.stop();
  4770. }
  4771. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4772. // Start server with client CA (enables client auth)
  4773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4774. ASSERT_TRUE(svr.is_valid());
  4775. bool handler_called = false;
  4776. svr.Get("/test", [&](const Request &req, Response &res) {
  4777. handler_called = true;
  4778. // Verify client certificate is present
  4779. auto cert = req.peer_cert();
  4780. EXPECT_TRUE(static_cast<bool>(cert));
  4781. res.set_content("ok", "text/plain");
  4782. });
  4783. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4784. auto se = detail::scope_exit([&] {
  4785. svr.stop();
  4786. t.join();
  4787. ASSERT_FALSE(svr.is_running());
  4788. });
  4789. svr.wait_until_ready();
  4790. // Read PEM files
  4791. std::string cert_pem, key_pem, ca_pem;
  4792. read_file(SERVER_CERT_FILE, cert_pem);
  4793. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4794. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4795. // Update server certificates and client CA using PEM API while server running
  4796. ASSERT_TRUE(
  4797. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4798. // Connect with client certificate
  4799. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4800. cli.enable_server_certificate_verification(false);
  4801. cli.set_connection_timeout(30);
  4802. auto res = cli.Get("/test");
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. ASSERT_EQ(StatusCode::OK_200, res->status);
  4805. ASSERT_TRUE(handler_called);
  4806. EXPECT_EQ("ok", res->body);
  4807. }
  4808. // Puts a CA that did not sign the client's certificate in the old one's place.
  4809. static bool replace_client_ca(SSLServer &svr) {
  4810. std::string cert_pem, key_pem, ca_pem;
  4811. read_file(SERVER_CERT_FILE, cert_pem);
  4812. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4813. read_file(SERVER_CERT2_FILE, ca_pem);
  4814. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4815. ca_pem.c_str());
  4816. }
  4817. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4819. ASSERT_TRUE(svr.is_valid());
  4820. svr.Get("/test", [](const Request &, Response &res) {
  4821. res.set_content("ok", "text/plain");
  4822. });
  4823. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4824. auto se = detail::scope_exit([&] {
  4825. svr.stop();
  4826. t.join();
  4827. ASSERT_FALSE(svr.is_running());
  4828. });
  4829. svr.wait_until_ready();
  4830. auto get = [] {
  4831. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4832. cli.enable_server_certificate_verification(false);
  4833. return cli.Get("/test");
  4834. };
  4835. ASSERT_TRUE(get());
  4836. ASSERT_TRUE(replace_client_ca(svr));
  4837. EXPECT_FALSE(get());
  4838. }
  4839. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4840. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4841. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4842. ASSERT_TRUE(svr.is_valid());
  4843. tls::set_verify_callback(svr.tls_context(),
  4844. [](const tls::VerifyContext &) -> bool {
  4845. throw std::runtime_error("verify");
  4846. });
  4847. svr.Get("/test", [](const Request &, Response &res) {
  4848. res.set_content("ok", "text/plain");
  4849. });
  4850. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4851. auto se = detail::scope_exit([&] {
  4852. svr.stop();
  4853. t.join();
  4854. ASSERT_FALSE(svr.is_running());
  4855. });
  4856. svr.wait_until_ready();
  4857. auto get = [] {
  4858. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4859. cli.enable_server_certificate_verification(false);
  4860. return cli.Get("/test");
  4861. };
  4862. EXPECT_FALSE(get());
  4863. // The handshake is over, so an update does not wait for it.
  4864. std::string cert_pem, key_pem;
  4865. read_file(SERVER_CERT_FILE, cert_pem);
  4866. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4867. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4868. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4869. return v.preverify_ok;
  4870. });
  4871. auto res = get();
  4872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4873. EXPECT_EQ("ok", res->body);
  4874. }
  4875. #endif
  4876. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4877. // Sends each request over a new connection with a client certificate,
  4878. // resuming the session of the one before when there is one.
  4879. class ResumingClient {
  4880. public:
  4881. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4882. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4883. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4884. SSL_FILETYPE_PEM);
  4885. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4886. // callback, not through SSL_get1_session().
  4887. SSL_CTX_set_app_data(ctx_, this);
  4888. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4889. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4890. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4891. auto self = static_cast<ResumingClient *>(
  4892. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4893. SSL_SESSION_free(self->session_);
  4894. self->session_ = session;
  4895. return 1; // Keeps the reference
  4896. });
  4897. }
  4898. ~ResumingClient() {
  4899. SSL_SESSION_free(session_);
  4900. SSL_CTX_free(ctx_);
  4901. }
  4902. // Tells whether the request was answered.
  4903. bool get() {
  4904. auto error = Error::Success;
  4905. auto sock = detail::create_client_socket(
  4906. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4907. /*connection_timeout_sec=*/5, 0,
  4908. /*read_timeout_sec=*/5, 0,
  4909. /*write_timeout_sec=*/5, 0, std::string(), error);
  4910. if (sock == INVALID_SOCKET) { return false; }
  4911. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4912. auto ssl = SSL_new(ctx_);
  4913. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4914. SSL_set_fd(ssl, static_cast<int>(sock));
  4915. if (session_) { SSL_set_session(ssl, session_); }
  4916. if (SSL_connect(ssl) != 1) { return false; }
  4917. reused_ = SSL_session_reused(ssl) == 1;
  4918. // Reading the response also takes in a TLS 1.3 session ticket.
  4919. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4920. "Connection: close\r\n\r\n";
  4921. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4922. std::string res;
  4923. char buf[256];
  4924. int n;
  4925. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4926. res.append(buf, static_cast<size_t>(n));
  4927. }
  4928. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4929. SSL_shutdown(ssl);
  4930. return res.find("200 OK") != std::string::npos;
  4931. }
  4932. // Whether the last connection resumed a session
  4933. bool reused() const { return reused_; }
  4934. private:
  4935. SSL_CTX *ctx_;
  4936. SSL_SESSION *session_ = nullptr;
  4937. bool reused_ = false;
  4938. };
  4939. // A client that resumes its session gets through, but not once the client CA
  4940. // has changed, as a resumed session does not show the certificate again.
  4941. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4942. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4943. ASSERT_TRUE(svr.is_valid());
  4944. svr.Get("/test", [](const Request &, Response &res) {
  4945. res.set_content("ok", "text/plain");
  4946. });
  4947. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4948. auto se = detail::scope_exit([&] {
  4949. svr.stop();
  4950. t.join();
  4951. ASSERT_FALSE(svr.is_running());
  4952. });
  4953. svr.wait_until_ready();
  4954. ResumingClient cli;
  4955. ASSERT_TRUE(cli.get());
  4956. ASSERT_TRUE(cli.get());
  4957. EXPECT_TRUE(cli.reused());
  4958. ASSERT_TRUE(replace_client_ca(svr));
  4959. EXPECT_FALSE(cli.get());
  4960. }
  4961. // A resumed session does not show the certificate again, so the server does
  4962. // not resume one with a verify callback to run on it.
  4963. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4964. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4965. ASSERT_TRUE(svr.is_valid());
  4966. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4967. return v.preverify_ok;
  4968. });
  4969. svr.Get("/test", [](const Request &, Response &res) {
  4970. res.set_content("ok", "text/plain");
  4971. });
  4972. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4973. auto se = detail::scope_exit([&] {
  4974. svr.stop();
  4975. t.join();
  4976. ASSERT_FALSE(svr.is_running());
  4977. });
  4978. svr.wait_until_ready();
  4979. ResumingClient cli;
  4980. ASSERT_TRUE(cli.get());
  4981. ASSERT_TRUE(cli.get());
  4982. EXPECT_FALSE(cli.reused());
  4983. }
  4984. #endif
  4985. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4986. // wolfSSL shares its session cache between contexts, so a resumed session
  4987. // could carry a client certificate checked against another server's CA, or
  4988. // against a client CA since replaced.
  4989. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4990. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4991. ASSERT_TRUE(svr.is_valid());
  4992. // Trusts a CA that did not sign the client's certificate.
  4993. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4994. ASSERT_TRUE(other.is_valid());
  4995. for (auto s : {&svr, &other}) {
  4996. s->Get("/test", [](const Request &, Response &res) {
  4997. res.set_content("ok", "text/plain");
  4998. });
  4999. }
  5000. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5001. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  5002. auto se = detail::scope_exit([&] {
  5003. other.stop();
  5004. svr.stop();
  5005. t2.join();
  5006. t.join();
  5007. });
  5008. svr.wait_until_ready();
  5009. other.wait_until_ready();
  5010. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  5011. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  5012. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  5013. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  5014. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  5015. ASSERT_EQ(WOLFSSL_SUCCESS,
  5016. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  5017. WOLFSSL_FILETYPE_PEM));
  5018. WOLFSSL_SESSION *session = nullptr;
  5019. auto session_se = detail::scope_exit([&] {
  5020. if (session) { wolfSSL_SESSION_free(session); }
  5021. });
  5022. // A request over a new connection, resuming `session` when there is one and
  5023. // keeping the connection's own in its place. Tells whether it was answered.
  5024. auto get = [&](int port) {
  5025. auto error = Error::Success;
  5026. auto sock = detail::create_client_socket(
  5027. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  5028. /*connection_timeout_sec=*/5, 0,
  5029. /*read_timeout_sec=*/5, 0,
  5030. /*write_timeout_sec=*/5, 0, std::string(), error);
  5031. if (sock == INVALID_SOCKET) { return false; }
  5032. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  5033. auto ssl = wolfSSL_new(ctx);
  5034. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  5035. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  5036. if (session) { wolfSSL_set_session(ssl, session); }
  5037. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  5038. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  5039. "Connection: close\r\n\r\n";
  5040. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  5041. std::string res;
  5042. char buf[256];
  5043. int n;
  5044. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  5045. res.append(buf, static_cast<size_t>(n));
  5046. }
  5047. wolfSSL_shutdown(ssl);
  5048. if (session) { wolfSSL_SESSION_free(session); }
  5049. session = wolfSSL_get1_session(ssl);
  5050. return res.find("200 OK") != std::string::npos;
  5051. };
  5052. ASSERT_TRUE(get(PORT));
  5053. EXPECT_FALSE(get(PORT + 1));
  5054. ASSERT_TRUE(get(PORT));
  5055. ASSERT_TRUE(replace_client_ca(svr));
  5056. EXPECT_FALSE(get(PORT));
  5057. }
  5058. #endif
  5059. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  5060. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5061. ASSERT_TRUE(svr.is_valid());
  5062. // Keep-alive parking would wait for the ClientHello without a handshake.
  5063. svr.set_keep_alive_parking(false);
  5064. svr.Get("/test", [](const Request &, Response &res) {
  5065. res.set_content("ok", "text/plain");
  5066. });
  5067. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5068. auto se = detail::scope_exit([&] {
  5069. svr.stop();
  5070. t.join();
  5071. ASSERT_FALSE(svr.is_running());
  5072. });
  5073. svr.wait_until_ready();
  5074. // A connection that sends no ClientHello keeps its handshake in progress,
  5075. // once the server has had a moment to start it.
  5076. auto error = Error::Success;
  5077. auto sock = detail::create_client_socket(
  5078. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5079. /*connection_timeout_sec=*/5, 0,
  5080. /*read_timeout_sec=*/5, 0,
  5081. /*write_timeout_sec=*/5, 0, std::string(), error);
  5082. ASSERT_NE(INVALID_SOCKET, sock);
  5083. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5084. std::string cert_pem, key_pem;
  5085. read_file(SERVER_CERT_FILE, cert_pem);
  5086. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  5087. auto update = std::async(std::launch::async, [&]() {
  5088. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  5089. });
  5090. EXPECT_EQ(std::future_status::timeout,
  5091. update.wait_for(std::chrono::milliseconds(200)));
  5092. detail::close_socket(sock);
  5093. EXPECT_TRUE(update.get());
  5094. SSLClient cli(HOST, PORT);
  5095. cli.enable_server_certificate_verification(false);
  5096. auto res = cli.Get("/test");
  5097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5098. EXPECT_EQ(StatusCode::OK_200, res->status);
  5099. }
  5100. TEST(SSLClientServerTest, StopDoesNotWaitForHandshakeInProgress) {
  5101. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5102. ASSERT_TRUE(svr.is_valid());
  5103. // Keep-alive parking would wait for the ClientHello without a handshake.
  5104. svr.set_keep_alive_parking(false);
  5105. svr.set_read_timeout(10, 0);
  5106. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5107. auto se = detail::scope_exit([&] {
  5108. svr.stop();
  5109. if (t.joinable()) { t.join(); }
  5110. });
  5111. svr.wait_until_ready();
  5112. // A connection that sends no ClientHello keeps its handshake in progress,
  5113. // once the server has had a moment to start it.
  5114. auto error = Error::Success;
  5115. auto sock = detail::create_client_socket(
  5116. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5117. /*connection_timeout_sec=*/5, 0,
  5118. /*read_timeout_sec=*/5, 0,
  5119. /*write_timeout_sec=*/5, 0, std::string(), error);
  5120. ASSERT_NE(INVALID_SOCKET, sock);
  5121. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  5122. auto start = std::chrono::steady_clock::now();
  5123. svr.stop();
  5124. t.join();
  5125. auto elapsed = std::chrono::steady_clock::now() - start;
  5126. detail::close_socket(sock);
  5127. EXPECT_LT(elapsed, std::chrono::seconds(3));
  5128. }
  5129. #endif
  5130. TEST(ErrorHandlerTest, ContentLength) {
  5131. Server svr;
  5132. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5133. res.status = StatusCode::OK_200;
  5134. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5135. "text/html"); // <= Content-Length still 13
  5136. });
  5137. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5138. res.set_content("Hello World!\n", "text/plain");
  5139. res.status = 524;
  5140. });
  5141. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5142. auto se = detail::scope_exit([&] {
  5143. svr.stop();
  5144. thread.join();
  5145. ASSERT_FALSE(svr.is_running());
  5146. });
  5147. svr.wait_until_ready();
  5148. {
  5149. Client cli(HOST, PORT);
  5150. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5152. EXPECT_EQ(StatusCode::OK_200, res->status);
  5153. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5154. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5155. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5156. }
  5157. }
  5158. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5159. TEST(ExceptionTest, WithoutExceptionHandler) {
  5160. Server svr;
  5161. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5162. throw std::runtime_error("exception...");
  5163. });
  5164. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5165. throw std::runtime_error("exception\r\n...");
  5166. });
  5167. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5168. auto se = detail::scope_exit([&] {
  5169. svr.stop();
  5170. listen_thread.join();
  5171. ASSERT_FALSE(svr.is_running());
  5172. });
  5173. svr.wait_until_ready();
  5174. Client cli("localhost", PORT);
  5175. {
  5176. auto res = cli.Get("/exception");
  5177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5178. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5179. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5180. }
  5181. {
  5182. auto res = cli.Get("/unknown");
  5183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5184. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5185. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5186. }
  5187. }
  5188. TEST(ExceptionTest, WithExceptionHandler) {
  5189. Server svr;
  5190. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5191. std::exception_ptr ep) {
  5192. EXPECT_FALSE(ep == nullptr);
  5193. try {
  5194. std::rethrow_exception(ep);
  5195. } catch (std::exception &e) {
  5196. EXPECT_EQ("abc", std::string(e.what()));
  5197. } catch (...) {}
  5198. res.status = StatusCode::InternalServerError_500;
  5199. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5200. "text/html"); // <= Content-Length still 13 at this point
  5201. });
  5202. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5203. res.set_content("Hello World!\n", "text/plain");
  5204. throw std::runtime_error("abc");
  5205. });
  5206. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5207. auto se = detail::scope_exit([&] {
  5208. svr.stop();
  5209. thread.join();
  5210. ASSERT_FALSE(svr.is_running());
  5211. });
  5212. svr.wait_until_ready();
  5213. for (size_t i = 0; i < 10; i++) {
  5214. Client cli(HOST, PORT);
  5215. for (size_t j = 0; j < 100; j++) {
  5216. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5218. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5219. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5220. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5221. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5222. }
  5223. cli.set_keep_alive(true);
  5224. for (size_t j = 0; j < 100; j++) {
  5225. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5227. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5228. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5229. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5230. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5231. }
  5232. }
  5233. }
  5234. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5235. Server svr;
  5236. svr.set_exception_handler(
  5237. [](const Request &, Response &res, std::exception_ptr) {
  5238. res.set_content("oops", "text/plain");
  5239. });
  5240. svr.Get("/throw", [](const Request &, Response &) {
  5241. throw std::runtime_error("throw");
  5242. });
  5243. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5244. res.status = StatusCode::Created_201;
  5245. throw std::runtime_error("created-then-throw");
  5246. });
  5247. auto port = svr.bind_to_any_port(HOST);
  5248. ASSERT_GT(port, 0);
  5249. thread t = thread([&] { svr.listen_after_bind(); });
  5250. auto se = detail::scope_exit([&] {
  5251. svr.stop();
  5252. t.join();
  5253. ASSERT_FALSE(svr.is_running());
  5254. });
  5255. svr.wait_until_ready();
  5256. Client cli(HOST, port);
  5257. for (auto path : {"/throw", "/created-then-throw"}) {
  5258. auto res = cli.Get(path);
  5259. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5260. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5261. }
  5262. }
  5263. TEST(ExceptionTest, AndErrorHandler) {
  5264. Server svr;
  5265. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5266. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5267. });
  5268. svr.set_exception_handler(
  5269. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5270. EXPECT_FALSE(ep == nullptr);
  5271. try {
  5272. std::rethrow_exception(ep);
  5273. } catch (std::exception &e) {
  5274. res.set_content(e.what(), "text/html");
  5275. } catch (...) {}
  5276. res.status = StatusCode::InternalServerError_500;
  5277. });
  5278. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5279. throw std::runtime_error("EXCEPTION");
  5280. });
  5281. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5282. res.set_content("ERROR", "text/html");
  5283. res.status = StatusCode::InternalServerError_500;
  5284. });
  5285. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5286. auto se = detail::scope_exit([&] {
  5287. svr.stop();
  5288. thread.join();
  5289. ASSERT_FALSE(svr.is_running());
  5290. });
  5291. svr.wait_until_ready();
  5292. Client cli(HOST, PORT);
  5293. {
  5294. auto res = cli.Get("/exception");
  5295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5296. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5297. EXPECT_EQ("EXCEPTION", res->body);
  5298. }
  5299. {
  5300. auto res = cli.Get("/error");
  5301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5302. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5303. EXPECT_EQ("ERROR", res->body);
  5304. }
  5305. {
  5306. auto res = cli.Get("/invalid");
  5307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5309. EXPECT_EQ("NOT_FOUND", res->body);
  5310. }
  5311. }
  5312. #endif
  5313. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5314. // An exception from a user callback outside process_request()'s try/catch
  5315. // used to unwind into the task queue - which does not catch - and terminate
  5316. // the process. Each test below runs the server on a single worker thread: a
  5317. // guard that catches the exception but still loses the thread would otherwise
  5318. // be hidden by a spare worker serving the follow-up request. Note that a
  5319. // regression here aborts the whole test binary rather than failing one test.
  5320. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5321. Server svr;
  5322. svr.new_task_queue = [] { return new ThreadPool(1); };
  5323. std::atomic<int> reported{0};
  5324. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5325. if (err == Error::UserCallbackException) { reported++; }
  5326. });
  5327. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5328. res.set_content_provider(
  5329. 1024, "text/plain",
  5330. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5331. sink.write("hello", 5);
  5332. throw std::runtime_error("from the content provider");
  5333. });
  5334. });
  5335. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5336. res.set_content("ok", "text/plain");
  5337. });
  5338. auto port = svr.bind_to_any_port(HOST);
  5339. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5340. auto se = detail::scope_exit([&] {
  5341. svr.stop();
  5342. listen_thread.join();
  5343. ASSERT_FALSE(svr.is_running());
  5344. });
  5345. svr.wait_until_ready();
  5346. {
  5347. Client cli(HOST, port);
  5348. cli.set_read_timeout(5, 0);
  5349. EXPECT_FALSE(cli.Get("/throw"));
  5350. }
  5351. EXPECT_TRUE(svr.is_running());
  5352. EXPECT_EQ(1, reported.load());
  5353. // A request on a fresh connection is still served.
  5354. {
  5355. Client cli(HOST, port);
  5356. auto res = cli.Get("/ok");
  5357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5358. EXPECT_EQ(StatusCode::OK_200, res->status);
  5359. EXPECT_EQ("ok", res->body);
  5360. }
  5361. }
  5362. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5363. Server svr;
  5364. svr.new_task_queue = [] { return new ThreadPool(1); };
  5365. std::atomic<bool> should_throw{true};
  5366. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5367. res.set_content("hi", "text/plain");
  5368. });
  5369. svr.set_post_routing_handler(
  5370. [&](const Request & /*req*/, Response & /*res*/) {
  5371. if (should_throw) {
  5372. throw std::runtime_error("from the post-routing handler");
  5373. }
  5374. });
  5375. auto port = svr.bind_to_any_port(HOST);
  5376. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5377. auto se = detail::scope_exit([&] {
  5378. svr.stop();
  5379. listen_thread.join();
  5380. ASSERT_FALSE(svr.is_running());
  5381. });
  5382. svr.wait_until_ready();
  5383. {
  5384. Client cli(HOST, port);
  5385. cli.set_read_timeout(5, 0);
  5386. EXPECT_FALSE(cli.Get("/hi"));
  5387. }
  5388. EXPECT_TRUE(svr.is_running());
  5389. should_throw = false;
  5390. {
  5391. Client cli(HOST, port);
  5392. auto res = cli.Get("/hi");
  5393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5394. EXPECT_EQ(StatusCode::OK_200, res->status);
  5395. EXPECT_EQ("hi", res->body);
  5396. }
  5397. }
  5398. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5399. // The guard reports the caught exception through the error logger, which is
  5400. // a user callback too. A logger that throws has to be contained as well, or
  5401. // the process would terminate from inside the catch.
  5402. Server svr;
  5403. svr.new_task_queue = [] { return new ThreadPool(1); };
  5404. std::atomic<int> reported{0};
  5405. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5406. if (err == Error::UserCallbackException) {
  5407. reported++;
  5408. throw std::runtime_error("from the error logger");
  5409. }
  5410. });
  5411. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5412. res.set_content_provider(
  5413. 1024, "text/plain",
  5414. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5415. sink.write("hello", 5);
  5416. throw std::runtime_error("from the content provider");
  5417. });
  5418. });
  5419. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5420. res.set_content("ok", "text/plain");
  5421. });
  5422. auto port = svr.bind_to_any_port(HOST);
  5423. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5424. auto se = detail::scope_exit([&] {
  5425. svr.stop();
  5426. listen_thread.join();
  5427. ASSERT_FALSE(svr.is_running());
  5428. });
  5429. svr.wait_until_ready();
  5430. {
  5431. Client cli(HOST, port);
  5432. cli.set_read_timeout(5, 0);
  5433. EXPECT_FALSE(cli.Get("/throw"));
  5434. }
  5435. EXPECT_TRUE(svr.is_running());
  5436. EXPECT_EQ(1, reported.load());
  5437. {
  5438. Client cli(HOST, port);
  5439. auto res = cli.Get("/ok");
  5440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5441. EXPECT_EQ(StatusCode::OK_200, res->status);
  5442. EXPECT_EQ("ok", res->body);
  5443. }
  5444. }
  5445. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5446. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5447. // so the exception unwinds through the ws::WebSocket object on its way to
  5448. // the guard. None of the HTTP cases above cross that.
  5449. Server svr;
  5450. svr.new_task_queue = [] { return new ThreadPool(1); };
  5451. std::atomic<int> reported{0};
  5452. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5453. if (err == Error::UserCallbackException) { reported++; }
  5454. });
  5455. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5456. throw std::runtime_error("from the WebSocket handler");
  5457. });
  5458. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5459. res.set_content("ok", "text/plain");
  5460. });
  5461. auto port = svr.bind_to_any_port(HOST);
  5462. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5463. auto se = detail::scope_exit([&] {
  5464. svr.stop();
  5465. listen_thread.join();
  5466. ASSERT_FALSE(svr.is_running());
  5467. });
  5468. svr.wait_until_ready();
  5469. {
  5470. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5471. "/ws");
  5472. auto res = client.connect();
  5473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5474. // The server dropped the connection instead of dying.
  5475. std::string msg;
  5476. EXPECT_FALSE(client.read(msg));
  5477. client.close();
  5478. }
  5479. EXPECT_TRUE(svr.is_running());
  5480. EXPECT_EQ(1, reported.load());
  5481. {
  5482. Client cli(HOST, port);
  5483. auto res = cli.Get("/ok");
  5484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5485. EXPECT_EQ(StatusCode::OK_200, res->status);
  5486. EXPECT_EQ("ok", res->body);
  5487. }
  5488. }
  5489. #ifdef CPPHTTPLIB_SSL_ENABLED
  5490. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5491. // SSLServer::process_and_close_socket() is a separate overload with its own
  5492. // guard, so it is exercised on its own.
  5493. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5494. ASSERT_TRUE(svr.is_valid());
  5495. svr.new_task_queue = [] { return new ThreadPool(1); };
  5496. std::atomic<int> reported{0};
  5497. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5498. if (err == Error::UserCallbackException) { reported++; }
  5499. });
  5500. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5501. res.set_content_provider(
  5502. 1024, "text/plain",
  5503. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5504. sink.write("hello", 5);
  5505. throw std::runtime_error("from the content provider");
  5506. });
  5507. });
  5508. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5509. res.set_content("ok", "text/plain");
  5510. });
  5511. auto port = svr.bind_to_any_port(HOST);
  5512. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5513. auto se = detail::scope_exit([&] {
  5514. svr.stop();
  5515. listen_thread.join();
  5516. ASSERT_FALSE(svr.is_running());
  5517. });
  5518. svr.wait_until_ready();
  5519. {
  5520. SSLClient cli(HOST, port);
  5521. cli.enable_server_certificate_verification(false);
  5522. cli.set_read_timeout(5, 0);
  5523. EXPECT_FALSE(cli.Get("/throw"));
  5524. }
  5525. EXPECT_TRUE(svr.is_running());
  5526. EXPECT_EQ(1, reported.load());
  5527. {
  5528. SSLClient cli(HOST, port);
  5529. cli.enable_server_certificate_verification(false);
  5530. auto res = cli.Get("/ok");
  5531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5532. EXPECT_EQ(StatusCode::OK_200, res->status);
  5533. EXPECT_EQ("ok", res->body);
  5534. }
  5535. }
  5536. #endif
  5537. #endif
  5538. TEST(NoContentTest, ContentLength) {
  5539. Server svr;
  5540. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5541. res.status = StatusCode::NoContent_204;
  5542. });
  5543. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5544. auto se = detail::scope_exit([&] {
  5545. svr.stop();
  5546. thread.join();
  5547. ASSERT_FALSE(svr.is_running());
  5548. });
  5549. svr.wait_until_ready();
  5550. {
  5551. Client cli(HOST, PORT);
  5552. auto res = cli.Get("/hi");
  5553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5554. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5555. // RFC 9110 8.6: none in a 204 response
  5556. EXPECT_FALSE(res->has_header("Content-Length"));
  5557. }
  5558. }
  5559. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5560. Server svr;
  5561. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5562. res.set_header("Content-Length", "5");
  5563. res.set_content("hello world", "text/plain");
  5564. });
  5565. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5566. // A body that reads as the last chunk, were it taken as chunked
  5567. res.set_header("Transfer-Encoding", "chunked");
  5568. res.set_content("0\r\n\r\n", "text/plain");
  5569. });
  5570. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5571. res.set_header("Content-Length", "2");
  5572. res.set_content_provider(5, "text/plain",
  5573. [](size_t offset, size_t length, DataSink &sink) {
  5574. sink.write(&"hello"[offset], length);
  5575. return true;
  5576. });
  5577. });
  5578. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5579. res.set_header("Content-Length", "1234");
  5580. });
  5581. thread t = thread([&] { svr.listen(HOST, PORT); });
  5582. auto se = detail::scope_exit([&] {
  5583. svr.stop();
  5584. t.join();
  5585. ASSERT_FALSE(svr.is_running());
  5586. });
  5587. svr.wait_until_ready();
  5588. Client cli(HOST, PORT);
  5589. cli.set_read_timeout(1, 0);
  5590. auto expect_body = [&](const Result &res, const std::string &body) {
  5591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5592. EXPECT_EQ(body, res->body);
  5593. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5594. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5595. };
  5596. Headers identity{{"Accept-Encoding", ""}};
  5597. expect_body(cli.Get("/body", identity), "hello world");
  5598. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5599. expect_body(cli.Get("/body",
  5600. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5601. "he");
  5602. expect_body(cli.Get("/provider", identity), "hello");
  5603. expect_body(cli.Get("/empty", identity), "");
  5604. // A HEAD response may give the length of the body a GET would get.
  5605. auto res = cli.Head("/empty");
  5606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5607. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5608. }
  5609. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5610. Server svr;
  5611. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5612. res.set_content("short", "text/plain");
  5613. });
  5614. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5615. res.body += " with a footer";
  5616. res.set_header("Transfer-Encoding", "chunked");
  5617. });
  5618. thread t = thread([&] { svr.listen(HOST, PORT); });
  5619. auto se = detail::scope_exit([&] {
  5620. svr.stop();
  5621. t.join();
  5622. ASSERT_FALSE(svr.is_running());
  5623. });
  5624. svr.wait_until_ready();
  5625. Client cli(HOST, PORT);
  5626. cli.set_read_timeout(1, 0);
  5627. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5629. EXPECT_EQ("short with a footer", res->body);
  5630. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5631. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5632. }
  5633. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5634. Server svr;
  5635. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5636. res.set_header("Content-Length", "3");
  5637. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5638. sink.write("abc", 3);
  5639. sink.done();
  5640. return true;
  5641. });
  5642. });
  5643. thread t = thread([&] { svr.listen(HOST, PORT); });
  5644. auto se = detail::scope_exit([&] {
  5645. svr.stop();
  5646. t.join();
  5647. ASSERT_FALSE(svr.is_running());
  5648. });
  5649. svr.wait_until_ready();
  5650. Client cli(HOST, PORT);
  5651. cli.set_keep_alive(true);
  5652. auto res = cli.Get("/");
  5653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5654. EXPECT_EQ("abc", res->body);
  5655. EXPECT_FALSE(res->has_header("Content-Length"));
  5656. EXPECT_EQ("close", res->get_header_value("Connection"));
  5657. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5658. // No body to delimit
  5659. auto head = cli.Head("/");
  5660. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5661. EXPECT_FALSE(head->has_header("Connection"));
  5662. }
  5663. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5664. #ifdef CPPHTTPLIB_SSL_ENABLED
  5665. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5666. ASSERT_TRUE(svr.is_valid());
  5667. #else
  5668. Server svr;
  5669. #endif
  5670. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5671. if (req.path == "/routing_handler") {
  5672. res.set_header("PRE_ROUTING", "on");
  5673. res.set_content("Routing Handler", "text/plain");
  5674. return httplib::Server::HandlerResponse::Handled;
  5675. }
  5676. return httplib::Server::HandlerResponse::Unhandled;
  5677. });
  5678. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5679. res.set_content("Error", "text/html");
  5680. });
  5681. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5682. if (req.path == "/routing_handler") {
  5683. res.set_header("POST_ROUTING", "on");
  5684. }
  5685. });
  5686. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5687. res.set_content("Hello World!\n", "text/plain");
  5688. });
  5689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5690. auto se = detail::scope_exit([&] {
  5691. svr.stop();
  5692. thread.join();
  5693. ASSERT_FALSE(svr.is_running());
  5694. });
  5695. svr.wait_until_ready();
  5696. {
  5697. #ifdef CPPHTTPLIB_SSL_ENABLED
  5698. SSLClient cli(HOST, PORT);
  5699. cli.enable_server_certificate_verification(false);
  5700. #else
  5701. Client cli(HOST, PORT);
  5702. #endif
  5703. auto res = cli.Get("/routing_handler");
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. EXPECT_EQ(StatusCode::OK_200, res->status);
  5706. EXPECT_EQ("Routing Handler", res->body);
  5707. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5708. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5709. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5710. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5711. }
  5712. {
  5713. #ifdef CPPHTTPLIB_SSL_ENABLED
  5714. SSLClient cli(HOST, PORT);
  5715. cli.enable_server_certificate_verification(false);
  5716. #else
  5717. Client cli(HOST, PORT);
  5718. #endif
  5719. auto res = cli.Get("/hi");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. EXPECT_EQ(StatusCode::OK_200, res->status);
  5722. EXPECT_EQ("Hello World!\n", res->body);
  5723. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5724. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5725. }
  5726. {
  5727. #ifdef CPPHTTPLIB_SSL_ENABLED
  5728. SSLClient cli(HOST, PORT);
  5729. cli.enable_server_certificate_verification(false);
  5730. #else
  5731. Client cli(HOST, PORT);
  5732. #endif
  5733. auto res = cli.Get("/aaa");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5736. EXPECT_EQ("Error", res->body);
  5737. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5738. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5739. }
  5740. }
  5741. TEST(RequestHandlerTest, PreRequestHandler) {
  5742. auto route_path = "/user/:user";
  5743. Server svr;
  5744. svr.Get("/hi", [](const Request &, Response &res) {
  5745. res.set_content("hi", "text/plain");
  5746. });
  5747. svr.Get(route_path, [](const Request &req, Response &res) {
  5748. res.set_content(req.path_params.at("user"), "text/plain");
  5749. });
  5750. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5751. if (req.matched_route == route_path) {
  5752. auto user = req.path_params.at("user");
  5753. if (user != "john") {
  5754. res.status = StatusCode::Forbidden_403;
  5755. res.set_content("error", "text/html");
  5756. return Server::HandlerResponse::Handled;
  5757. }
  5758. }
  5759. return Server::HandlerResponse::Unhandled;
  5760. });
  5761. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5762. auto se = detail::scope_exit([&] {
  5763. svr.stop();
  5764. thread.join();
  5765. ASSERT_FALSE(svr.is_running());
  5766. });
  5767. svr.wait_until_ready();
  5768. Client cli(HOST, PORT);
  5769. {
  5770. auto res = cli.Get("/hi");
  5771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5772. EXPECT_EQ(StatusCode::OK_200, res->status);
  5773. EXPECT_EQ("hi", res->body);
  5774. }
  5775. {
  5776. auto res = cli.Get("/user/john");
  5777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5778. EXPECT_EQ(StatusCode::OK_200, res->status);
  5779. EXPECT_EQ("john", res->body);
  5780. }
  5781. {
  5782. auto res = cli.Get("/user/invalid-user");
  5783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5784. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5785. EXPECT_EQ("error", res->body);
  5786. }
  5787. }
  5788. // The pre-request handler must run before the request body is read, so a
  5789. // rejected request never forces the server to buffer a (potentially large)
  5790. // body. Here the posted body is larger than the payload limit: if the body
  5791. // were read first the server would answer 413, but because the pre-request
  5792. // handler runs first it answers 403 and the body is never read.
  5793. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5794. Server svr;
  5795. svr.set_payload_max_length(8);
  5796. auto handler_ran = false;
  5797. svr.Post("/reject", [&](const Request &req, Response &res) {
  5798. handler_ran = true;
  5799. res.set_content(req.body, "text/plain");
  5800. });
  5801. svr.Post("/accept", [](const Request &req, Response &res) {
  5802. res.set_content(req.body, "text/plain");
  5803. });
  5804. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5805. if (req.matched_route == "/reject") {
  5806. res.status = StatusCode::Forbidden_403;
  5807. res.set_content("denied", "text/plain");
  5808. return Server::HandlerResponse::Handled;
  5809. }
  5810. return Server::HandlerResponse::Unhandled;
  5811. });
  5812. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5813. auto se = detail::scope_exit([&] {
  5814. svr.stop();
  5815. thread.join();
  5816. ASSERT_FALSE(svr.is_running());
  5817. });
  5818. svr.wait_until_ready();
  5819. Client cli(HOST, PORT);
  5820. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5821. // rejects with 403 before the body is read, so 413 is never reached.
  5822. {
  5823. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5825. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5826. EXPECT_EQ("denied", res->body);
  5827. EXPECT_FALSE(handler_ran);
  5828. }
  5829. // An approved route still reads the body and enforces the payload limit.
  5830. {
  5831. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5834. }
  5835. }
  5836. TEST(UserDataTest, BasicOperations) {
  5837. httplib::UserData ud;
  5838. // Initially empty
  5839. EXPECT_FALSE(ud.has("key"));
  5840. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5841. // set and get
  5842. ud.set("key", 42);
  5843. EXPECT_TRUE(ud.has("key"));
  5844. auto *p = ud.get<int>("key");
  5845. ASSERT_NE(nullptr, p);
  5846. EXPECT_EQ(42, *p);
  5847. // Type mismatch → nullptr
  5848. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5849. // Overwrite with different type
  5850. ud.set("key", std::string("hello"));
  5851. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5852. auto *s = ud.get<std::string>("key");
  5853. ASSERT_NE(nullptr, s);
  5854. EXPECT_EQ("hello", *s);
  5855. // erase
  5856. ud.erase("key");
  5857. EXPECT_FALSE(ud.has("key"));
  5858. // clear
  5859. ud.set("a", 1);
  5860. ud.set("b", 2);
  5861. ud.clear();
  5862. EXPECT_FALSE(ud.has("a"));
  5863. EXPECT_FALSE(ud.has("b"));
  5864. }
  5865. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5866. struct AuthCtx {
  5867. std::string user_id;
  5868. };
  5869. Server svr;
  5870. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5871. res.user_data.set("auth", AuthCtx{"alice"});
  5872. return Server::HandlerResponse::Unhandled;
  5873. });
  5874. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5875. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5876. ASSERT_NE(nullptr, ctx);
  5877. res.set_content("Hello " + ctx->user_id, "text/plain");
  5878. });
  5879. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5880. auto se = detail::scope_exit([&] {
  5881. svr.stop();
  5882. thread.join();
  5883. ASSERT_FALSE(svr.is_running());
  5884. });
  5885. svr.wait_until_ready();
  5886. Client cli(HOST, PORT);
  5887. auto res = cli.Get("/me");
  5888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5889. EXPECT_EQ(StatusCode::OK_200, res->status);
  5890. EXPECT_EQ("Hello alice", res->body);
  5891. }
  5892. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5893. struct RoleCtx {
  5894. std::string role;
  5895. };
  5896. Server svr;
  5897. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5898. res.user_data.set("role", RoleCtx{"admin"});
  5899. return Server::HandlerResponse::Unhandled;
  5900. });
  5901. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5902. auto *ctx = res.user_data.get<RoleCtx>("role");
  5903. ASSERT_NE(nullptr, ctx);
  5904. res.set_content(ctx->role, "text/plain");
  5905. });
  5906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5907. auto se = detail::scope_exit([&] {
  5908. svr.stop();
  5909. thread.join();
  5910. ASSERT_FALSE(svr.is_running());
  5911. });
  5912. svr.wait_until_ready();
  5913. Client cli(HOST, PORT);
  5914. auto res = cli.Get("/role");
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::OK_200, res->status);
  5917. EXPECT_EQ("admin", res->body);
  5918. }
  5919. TEST(InvalidFormatTest, StatusCode) {
  5920. Server svr;
  5921. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5922. res.set_content("Hello World!\n", "text/plain");
  5923. res.status = 9999; // Status should be a three-digit code...
  5924. });
  5925. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5926. auto se = detail::scope_exit([&] {
  5927. svr.stop();
  5928. thread.join();
  5929. ASSERT_FALSE(svr.is_running());
  5930. });
  5931. svr.wait_until_ready();
  5932. {
  5933. Client cli(HOST, PORT);
  5934. auto res = cli.Get("/hi");
  5935. ASSERT_FALSE(res);
  5936. }
  5937. }
  5938. TEST(URLFragmentTest, WithFragment) {
  5939. Server svr;
  5940. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5941. EXPECT_TRUE(req.target == "/hi");
  5942. });
  5943. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5944. auto se = detail::scope_exit([&] {
  5945. svr.stop();
  5946. thread.join();
  5947. ASSERT_FALSE(svr.is_running());
  5948. });
  5949. svr.wait_until_ready();
  5950. {
  5951. Client cli(HOST, PORT);
  5952. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5953. EXPECT_TRUE(res);
  5954. EXPECT_EQ(StatusCode::OK_200, res->status);
  5955. res = cli.Get("/hi%23key1=val1=key2=val2");
  5956. EXPECT_TRUE(res);
  5957. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5958. }
  5959. }
  5960. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5961. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5962. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5963. Server svr;
  5964. std::vector<std::string> targets;
  5965. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5966. targets.push_back(req.target);
  5967. });
  5968. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5969. auto se = detail::scope_exit([&] {
  5970. svr.stop();
  5971. thread.join();
  5972. ASSERT_FALSE(svr.is_running());
  5973. });
  5974. svr.wait_until_ready();
  5975. Client cli(HOST, PORT);
  5976. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5977. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5978. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5979. // A '?' after the '#' belongs to the fragment, not to the query.
  5980. Request req;
  5981. req.method = "GET";
  5982. req.path = "/hi#f?x=1";
  5983. req.params.emplace("a", "1");
  5984. Response res;
  5985. auto error = Error::Success;
  5986. EXPECT_TRUE(cli.send(req, res, error));
  5987. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5988. "/hi?a=1"}),
  5989. targets);
  5990. }
  5991. TEST(HeaderWriter, SetHeaderWriter) {
  5992. Server svr;
  5993. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5994. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5995. return detail::write_headers(strm, hdrs);
  5996. });
  5997. svr.Get("/hi", [](const Request &req, Response &res) {
  5998. auto it = req.headers.find("CustomClientHeader");
  5999. EXPECT_TRUE(it != req.headers.end());
  6000. EXPECT_EQ(it->second, "CustomClientValue");
  6001. res.set_content("Hello World!\n", "text/plain");
  6002. });
  6003. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  6004. auto se = detail::scope_exit([&] {
  6005. svr.stop();
  6006. thread.join();
  6007. ASSERT_FALSE(svr.is_running());
  6008. });
  6009. svr.wait_until_ready();
  6010. {
  6011. Client cli(HOST, PORT);
  6012. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  6013. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  6014. return detail::write_headers(strm, hdrs);
  6015. });
  6016. auto res = cli.Get("/hi");
  6017. EXPECT_TRUE(res);
  6018. EXPECT_EQ(StatusCode::OK_200, res->status);
  6019. auto it = res->headers.find("CustomServerHeader");
  6020. EXPECT_TRUE(it != res->headers.end());
  6021. EXPECT_EQ(it->second, "CustomServerValue");
  6022. }
  6023. }
  6024. class ServerTest : public ::testing::Test {
  6025. protected:
  6026. ServerTest()
  6027. : cli_(HOST, PORT)
  6028. #ifdef CPPHTTPLIB_SSL_ENABLED
  6029. ,
  6030. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6031. #endif
  6032. {
  6033. #ifdef CPPHTTPLIB_SSL_ENABLED
  6034. cli_.enable_server_certificate_verification(false);
  6035. #endif
  6036. // Allow LARGE_DATA (100MB) responses
  6037. cli_.set_payload_max_length(200 * 1024 * 1024);
  6038. }
  6039. virtual void SetUp() {
  6040. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  6041. svr_.set_payload_max_length(200 * 1024 * 1024);
  6042. svr_.set_mount_point("/", "./www");
  6043. svr_.set_mount_point("/mount", "./www2");
  6044. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  6045. svr_.Get("/hi",
  6046. [&](const Request & /*req*/, Response &res) {
  6047. res.set_content("Hello World!", "text/plain");
  6048. })
  6049. .Get("/file_content",
  6050. [&](const Request & /*req*/, Response &res) {
  6051. res.set_file_content("./www/dir/test.html");
  6052. })
  6053. .Get("/file_content_with_content_type",
  6054. [&](const Request & /*req*/, Response &res) {
  6055. res.set_file_content("./www/file", "text/plain");
  6056. })
  6057. .Get("/invalid_file_content",
  6058. [&](const Request & /*req*/, Response &res) {
  6059. res.set_file_content("./www/dir/invalid_file_path");
  6060. })
  6061. .Get("/http_response_splitting",
  6062. [&](const Request & /*req*/, Response &res) {
  6063. res.set_header("a", "1\r\nSet-Cookie: a=1");
  6064. EXPECT_EQ(0U, res.headers.size());
  6065. EXPECT_FALSE(res.has_header("a"));
  6066. res.set_header("a", "1\nSet-Cookie: a=1");
  6067. EXPECT_EQ(0U, res.headers.size());
  6068. EXPECT_FALSE(res.has_header("a"));
  6069. res.set_header("a", "1\rSet-Cookie: a=1");
  6070. EXPECT_EQ(0U, res.headers.size());
  6071. EXPECT_FALSE(res.has_header("a"));
  6072. res.set_header("a\r\nb", "0");
  6073. EXPECT_EQ(0U, res.headers.size());
  6074. EXPECT_FALSE(res.has_header("a"));
  6075. res.set_header("a\rb", "0");
  6076. EXPECT_EQ(0U, res.headers.size());
  6077. EXPECT_FALSE(res.has_header("a"));
  6078. res.set_header("a\nb", "0");
  6079. EXPECT_EQ(0U, res.headers.size());
  6080. EXPECT_FALSE(res.has_header("a"));
  6081. res.set_redirect("1\r\nSet-Cookie: a=1");
  6082. EXPECT_EQ(0U, res.headers.size());
  6083. EXPECT_FALSE(res.has_header("Location"));
  6084. })
  6085. .Get("/slow",
  6086. [&](const Request & /*req*/, Response &res) {
  6087. std::this_thread::sleep_for(std::chrono::seconds(4));
  6088. res.set_content("slow", "text/plain");
  6089. })
  6090. #if 0
  6091. .Post("/slowpost",
  6092. [&](const Request & /*req*/, Response &res) {
  6093. std::this_thread::sleep_for(std::chrono::seconds(2));
  6094. res.set_content("slow", "text/plain");
  6095. })
  6096. #endif
  6097. .Get("/remote_addr",
  6098. [&](const Request &req, Response &res) {
  6099. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  6100. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  6101. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6102. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  6103. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  6104. #endif
  6105. res.set_content(req.remote_addr, "text/plain");
  6106. })
  6107. .Get("/local_addr",
  6108. [&](const Request &req, Response &res) {
  6109. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  6110. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  6111. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6112. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  6113. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  6114. #endif
  6115. auto local_addr = req.local_addr;
  6116. auto local_port = std::to_string(req.local_port);
  6117. res.set_content(local_addr.append(":").append(local_port),
  6118. "text/plain");
  6119. })
  6120. .Get("/endwith%",
  6121. [&](const Request & /*req*/, Response &res) {
  6122. res.set_content("Hello World!", "text/plain");
  6123. })
  6124. .Get("/a\\+\\+b",
  6125. [&](const Request &req, Response &res) {
  6126. ASSERT_TRUE(req.has_param("a +b"));
  6127. auto val = req.get_param_value("a +b");
  6128. res.set_content(val, "text/plain");
  6129. })
  6130. .Get("/", [&](const Request & /*req*/,
  6131. Response &res) { res.set_redirect("/hi"); })
  6132. .Post("/1",
  6133. [](const Request & /*req*/, Response &res) {
  6134. res.set_redirect("/2", StatusCode::SeeOther_303);
  6135. })
  6136. .Get("/2",
  6137. [](const Request & /*req*/, Response &res) {
  6138. res.set_content("redirected.", "text/plain");
  6139. res.status = StatusCode::OK_200;
  6140. })
  6141. .Post("/person",
  6142. [&](const Request &req, Response &res) {
  6143. if (req.has_param("name") && req.has_param("note")) {
  6144. persons_[req.get_param_value("name")] =
  6145. req.get_param_value("note");
  6146. } else {
  6147. res.status = StatusCode::BadRequest_400;
  6148. }
  6149. })
  6150. .Put("/person",
  6151. [&](const Request &req, Response &res) {
  6152. if (req.has_param("name") && req.has_param("note")) {
  6153. persons_[req.get_param_value("name")] =
  6154. req.get_param_value("note");
  6155. } else {
  6156. res.status = StatusCode::BadRequest_400;
  6157. }
  6158. })
  6159. .Get("/person/(.*)",
  6160. [&](const Request &req, Response &res) {
  6161. string name = req.matches[1];
  6162. if (persons_.find(name) != persons_.end()) {
  6163. auto note = persons_[name];
  6164. res.set_content(note, "text/plain");
  6165. } else {
  6166. res.status = StatusCode::NotFound_404;
  6167. }
  6168. })
  6169. .Delete("/person",
  6170. [&](const Request &req, Response &res) {
  6171. if (req.has_param("name")) {
  6172. string name = req.get_param_value("name");
  6173. if (persons_.find(name) != persons_.end()) {
  6174. persons_.erase(name);
  6175. res.set_content("DELETED", "text/plain");
  6176. } else {
  6177. res.status = StatusCode::NotFound_404;
  6178. }
  6179. } else {
  6180. res.status = StatusCode::BadRequest_400;
  6181. }
  6182. })
  6183. .Post("/x-www-form-urlencoded-json",
  6184. [&](const Request &req, Response &res) {
  6185. auto json = req.get_param_value("json");
  6186. ASSERT_EQ(JSON_DATA, json);
  6187. res.set_content(json, "appliation/json");
  6188. res.status = StatusCode::OK_200;
  6189. })
  6190. .Get("/streamed-chunked",
  6191. [&](const Request & /*req*/, Response &res) {
  6192. res.set_chunked_content_provider(
  6193. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6194. sink.os << "123";
  6195. sink.os << "456";
  6196. sink.os << "789";
  6197. sink.done();
  6198. return true;
  6199. });
  6200. })
  6201. .Get("/streamed-chunked-with-prohibited-trailer",
  6202. [&](const Request & /*req*/, Response &res) {
  6203. auto i = new int(0);
  6204. // Declare both a prohibited trailer (Content-Length) and an
  6205. // allowed one
  6206. res.set_header("Trailer", "Content-Length, X-Allowed");
  6207. res.set_chunked_content_provider(
  6208. "text/plain",
  6209. [i](size_t /*offset*/, DataSink &sink) {
  6210. switch (*i) {
  6211. case 0: sink.os << "123"; break;
  6212. case 1: sink.os << "456"; break;
  6213. case 2: sink.os << "789"; break;
  6214. case 3: {
  6215. sink.done_with_trailer(
  6216. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6217. } break;
  6218. }
  6219. (*i)++;
  6220. return true;
  6221. },
  6222. [i](bool success) {
  6223. EXPECT_TRUE(success);
  6224. delete i;
  6225. });
  6226. })
  6227. .Get("/streamed-chunked2",
  6228. [&](const Request & /*req*/, Response &res) {
  6229. auto i = new int(0);
  6230. res.set_chunked_content_provider(
  6231. "text/plain",
  6232. [i](size_t /*offset*/, DataSink &sink) {
  6233. switch (*i) {
  6234. case 0: sink.os << "123"; break;
  6235. case 1: sink.os << "456"; break;
  6236. case 2: sink.os << "789"; break;
  6237. case 3: sink.done(); break;
  6238. }
  6239. (*i)++;
  6240. return true;
  6241. },
  6242. [i](bool success) {
  6243. EXPECT_TRUE(success);
  6244. delete i;
  6245. });
  6246. })
  6247. .Get("/streamed-chunked-with-trailer",
  6248. [&](const Request & /*req*/, Response &res) {
  6249. auto i = new int(0);
  6250. res.set_header("Trailer", "Dummy1, Dummy2");
  6251. res.set_chunked_content_provider(
  6252. "text/plain",
  6253. [i](size_t /*offset*/, DataSink &sink) {
  6254. switch (*i) {
  6255. case 0: sink.os << "123"; break;
  6256. case 1: sink.os << "456"; break;
  6257. case 2: sink.os << "789"; break;
  6258. case 3: {
  6259. sink.done_with_trailer(
  6260. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6261. } break;
  6262. }
  6263. (*i)++;
  6264. return true;
  6265. },
  6266. [i](bool success) {
  6267. EXPECT_TRUE(success);
  6268. delete i;
  6269. });
  6270. })
  6271. .Get("/streamed",
  6272. [&](const Request & /*req*/, Response &res) {
  6273. res.set_content_provider(
  6274. 6, "text/plain",
  6275. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6276. sink.os << (offset < 3 ? "a" : "b");
  6277. return true;
  6278. });
  6279. })
  6280. .Get("/streamed-without-length",
  6281. [&](const Request & /*req*/, Response &res) {
  6282. auto data = new std::string("abcdefg");
  6283. res.set_content_provider(
  6284. "text/plain",
  6285. [data](size_t offset, DataSink &sink) {
  6286. if (offset < data->size()) {
  6287. sink.os << data->substr(offset);
  6288. }
  6289. sink.done();
  6290. return true;
  6291. },
  6292. [data](bool success) {
  6293. EXPECT_TRUE(success);
  6294. delete data;
  6295. });
  6296. })
  6297. .Get("/streamed-with-range",
  6298. [&](const Request &req, Response &res) {
  6299. auto data = new std::string("abcdefg");
  6300. // An explicit status keeps the server from picking the 206 it
  6301. // would otherwise choose for a ranged request, so the response
  6302. // is not a partial representation.
  6303. auto status = req.get_param_value("status");
  6304. if (status == "200") {
  6305. res.status = StatusCode::OK_200;
  6306. } else if (status == "403") {
  6307. res.status = StatusCode::Forbidden_403;
  6308. }
  6309. res.set_content_provider(
  6310. data->size(), "text/plain",
  6311. [data](size_t offset, size_t length, DataSink &sink) {
  6312. size_t DATA_CHUNK_SIZE = 4;
  6313. const auto &d = *data;
  6314. auto out_len =
  6315. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6316. auto ret =
  6317. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6318. EXPECT_TRUE(ret);
  6319. return true;
  6320. },
  6321. [data, &req](bool success) {
  6322. EXPECT_EQ(success, !req.has_param("error"));
  6323. delete data;
  6324. });
  6325. })
  6326. .Get("/streamed-cancel",
  6327. [&](const Request & /*req*/, Response &res) {
  6328. res.set_content_provider(
  6329. size_t(-1), "text/plain",
  6330. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6331. sink.os << "data_chunk";
  6332. return true;
  6333. });
  6334. })
  6335. .Get("/regex-with-delimiter",
  6336. [&](const Request &req, Response & /*res*/) {
  6337. ASSERT_TRUE(req.has_param("key"));
  6338. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6339. })
  6340. .Get("/with-range",
  6341. [&](const Request & /*req*/, Response &res) {
  6342. res.set_content("abcdefg", "text/plain");
  6343. })
  6344. .Get("/test-start-time",
  6345. [&](const Request &req, Response & /*res*/) {
  6346. EXPECT_NE(req.start_time_,
  6347. std::chrono::steady_clock::time_point::min());
  6348. })
  6349. .Get("/with-range-customized-response",
  6350. [&](const Request & /*req*/, Response &res) {
  6351. res.status = StatusCode::BadRequest_400;
  6352. res.set_content(JSON_DATA, "application/json");
  6353. })
  6354. .Post("/chunked",
  6355. [&](const Request &req, Response & /*res*/) {
  6356. EXPECT_EQ(req.body, "dechunked post body");
  6357. })
  6358. .Post("/large-chunked",
  6359. [&](const Request &req, Response & /*res*/) {
  6360. std::string expected(6 * 30 * 1024u, 'a');
  6361. EXPECT_EQ(req.body, expected);
  6362. })
  6363. .Post("/multipart",
  6364. [&](const Request &req, Response & /*res*/) {
  6365. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6366. req.form.get_field_count("text2") +
  6367. req.form.get_field_count("file3") +
  6368. req.form.get_field_count("file4"));
  6369. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6370. req.form.get_file_count("file2"));
  6371. ASSERT_TRUE(!req.form.has_file("???"));
  6372. ASSERT_TRUE(!req.form.has_field("???"));
  6373. ASSERT_TRUE(req.body.empty());
  6374. {
  6375. const auto &text = req.form.get_field("text1");
  6376. EXPECT_EQ("text default", text);
  6377. }
  6378. {
  6379. const auto &text = req.form.get_field("text2");
  6380. EXPECT_EQ("aωb", text);
  6381. }
  6382. {
  6383. const auto &file = req.form.get_file("file1");
  6384. EXPECT_EQ("hello.txt", file.filename);
  6385. EXPECT_EQ("text/plain", file.content_type);
  6386. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6387. }
  6388. {
  6389. const auto &file = req.form.get_file("file2");
  6390. EXPECT_EQ("world.json", file.filename);
  6391. EXPECT_EQ("application/json", file.content_type);
  6392. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6393. }
  6394. {
  6395. const auto &text = req.form.get_field("file3");
  6396. EXPECT_EQ(0u, text.size());
  6397. }
  6398. {
  6399. const auto &text = req.form.get_field("file4");
  6400. EXPECT_EQ(0u, text.size());
  6401. }
  6402. })
  6403. .Post("/multipart/multi_file_values",
  6404. [&](const Request &req, Response & /*res*/) {
  6405. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6406. req.form.get_field_count("multi_text1"));
  6407. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6408. ASSERT_TRUE(!req.form.has_file("???"));
  6409. ASSERT_TRUE(!req.form.has_field("???"));
  6410. ASSERT_TRUE(req.body.empty());
  6411. {
  6412. const auto &text = req.form.get_field("text");
  6413. EXPECT_EQ("default text", text);
  6414. }
  6415. {
  6416. const auto &text1_values = req.form.get_fields("multi_text1");
  6417. EXPECT_EQ(2u, text1_values.size());
  6418. EXPECT_EQ("aaaaa", text1_values[0]);
  6419. EXPECT_EQ("bbbbb", text1_values[1]);
  6420. }
  6421. {
  6422. const auto &file1_values = req.form.get_files("multi_file1");
  6423. EXPECT_EQ(2u, file1_values.size());
  6424. auto file1 = file1_values[0];
  6425. EXPECT_EQ(file1.filename, "hello.txt");
  6426. EXPECT_EQ(file1.content_type, "text/plain");
  6427. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6428. auto file2 = file1_values[1];
  6429. EXPECT_EQ(file2.filename, "world.json");
  6430. EXPECT_EQ(file2.content_type, "application/json");
  6431. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6432. }
  6433. })
  6434. .Post("/empty",
  6435. [&](const Request &req, Response &res) {
  6436. EXPECT_EQ(req.body, "");
  6437. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6438. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6439. res.set_content("empty", "text/plain");
  6440. })
  6441. .Post("/empty-no-content-type",
  6442. [&](const Request &req, Response &res) {
  6443. EXPECT_EQ(req.body, "");
  6444. EXPECT_FALSE(req.has_header("Content-Type"));
  6445. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6446. res.set_content("empty-no-content-type", "text/plain");
  6447. })
  6448. .Post("/path-only",
  6449. [&](const Request &req, Response &res) {
  6450. EXPECT_EQ(req.body, "");
  6451. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6452. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6453. res.set_content("path-only", "text/plain");
  6454. })
  6455. .Post("/path-headers-only",
  6456. [&](const Request &req, Response &res) {
  6457. EXPECT_EQ(req.body, "");
  6458. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6459. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6460. EXPECT_EQ("world", req.get_header_value("hello"));
  6461. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6462. res.set_content("path-headers-only", "text/plain");
  6463. })
  6464. .Post("/post-large",
  6465. [&](const Request &req, Response &res) {
  6466. EXPECT_EQ(req.body, LARGE_DATA);
  6467. res.set_content(req.body, "text/plain");
  6468. })
  6469. .Post("/post-loopback",
  6470. [&](const Request &, Response &res,
  6471. ContentReader const &content_reader) {
  6472. std::string body;
  6473. content_reader([&](const char *data, size_t data_length) {
  6474. body.append(data, data_length);
  6475. return true;
  6476. });
  6477. res.set_content(body, "text/plain");
  6478. })
  6479. .Put("/put-loopback",
  6480. [&](const Request &, Response &res,
  6481. ContentReader const &content_reader) {
  6482. std::string body;
  6483. content_reader([&](const char *data, size_t data_length) {
  6484. body.append(data, data_length);
  6485. return true;
  6486. });
  6487. res.set_content(body, "text/plain");
  6488. })
  6489. .Patch("/patch-loopback",
  6490. [&](const Request &, Response &res,
  6491. ContentReader const &content_reader) {
  6492. std::string body;
  6493. content_reader([&](const char *data, size_t data_length) {
  6494. body.append(data, data_length);
  6495. return true;
  6496. });
  6497. res.set_content(body, "text/plain");
  6498. })
  6499. .Put("/empty-no-content-type",
  6500. [&](const Request &req, Response &res) {
  6501. EXPECT_EQ(req.body, "");
  6502. EXPECT_FALSE(req.has_header("Content-Type"));
  6503. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6504. res.set_content("empty-no-content-type", "text/plain");
  6505. })
  6506. .Put("/put",
  6507. [&](const Request &req, Response &res) {
  6508. EXPECT_EQ(req.body, "PUT");
  6509. res.set_content(req.body, "text/plain");
  6510. })
  6511. .Put("/put-large",
  6512. [&](const Request &req, Response &res) {
  6513. EXPECT_EQ(req.body, LARGE_DATA);
  6514. res.set_content(req.body, "text/plain");
  6515. })
  6516. .Patch("/patch",
  6517. [&](const Request &req, Response &res) {
  6518. EXPECT_EQ(req.body, "PATCH");
  6519. res.set_content(req.body, "text/plain");
  6520. })
  6521. .Delete("/delete",
  6522. [&](const Request & /*req*/, Response &res) {
  6523. res.set_content("DELETE", "text/plain");
  6524. })
  6525. .Delete("/delete-body",
  6526. [&](const Request &req, Response &res) {
  6527. EXPECT_EQ(req.body, "content");
  6528. res.set_content(req.body, "text/plain");
  6529. })
  6530. .Options(R"(\*)",
  6531. [&](const Request & /*req*/, Response &res) {
  6532. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6533. })
  6534. .CustomRoute("PROPFIND", "/dav/:id",
  6535. [&](const Request &req, Response &res) {
  6536. res.set_header("x-body-size",
  6537. std::to_string(req.body.size()));
  6538. res.set_header("x-matched-route", req.matched_route);
  6539. res.set_header("x-dav-id", req.path_params.at("id"));
  6540. res.status = StatusCode::MultiStatus_207;
  6541. res.set_content(req.body, "application/xml");
  6542. })
  6543. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6544. [&](const Request &req, Response &res) {
  6545. res.set_header("x-dav-match", req.matches[1]);
  6546. res.status = StatusCode::MultiStatus_207;
  6547. })
  6548. .CustomRoute("MKCOL", "/dav-mkcol",
  6549. [&](const Request &req, Response &res) {
  6550. EXPECT_TRUE(req.body.empty());
  6551. res.status = StatusCode::Created_201;
  6552. })
  6553. .CustomRoute(
  6554. "REPORT", "/dav-report",
  6555. [&](const Request & /*req*/, Response &res,
  6556. const ContentReader &content_reader) {
  6557. std::string body;
  6558. content_reader([&](const char *data, size_t data_length) {
  6559. body.append(data, data_length);
  6560. return true;
  6561. });
  6562. res.set_header("x-body-size", std::to_string(body.size()));
  6563. res.status = StatusCode::MultiStatus_207;
  6564. res.set_content(body, "application/xml");
  6565. })
  6566. .Get("/request-target",
  6567. [&](const Request &req, Response & /*res*/) {
  6568. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6569. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6570. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6571. })
  6572. .Get("/long-query-value",
  6573. [&](const Request &req, Response & /*res*/) {
  6574. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6575. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6576. })
  6577. .Get("/too-long-query-value",
  6578. [&](const Request &req, Response & /*res*/) {
  6579. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6580. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6581. })
  6582. .Get("/array-param",
  6583. [&](const Request &req, Response & /*res*/) {
  6584. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6585. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6586. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6587. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6588. })
  6589. .Get("/array-param-values",
  6590. [&](const Request &req, Response & /*res*/) {
  6591. auto values = req.get_param_values("array");
  6592. EXPECT_EQ(3u, values.size());
  6593. EXPECT_EQ("value1", values[0]);
  6594. EXPECT_EQ("value2", values[1]);
  6595. EXPECT_EQ("value3", values[2]);
  6596. auto empty = req.get_param_values("nonexistent");
  6597. EXPECT_TRUE(empty.empty());
  6598. })
  6599. .Post("/validate-no-multiple-headers",
  6600. [&](const Request &req, Response & /*res*/) {
  6601. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6602. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6603. })
  6604. .Post("/content_receiver",
  6605. [&](const Request &req, Response &res,
  6606. const ContentReader &content_reader) {
  6607. if (req.is_multipart_form_data()) {
  6608. std::vector<FormData> items;
  6609. content_reader(
  6610. [&](const FormData &file) {
  6611. items.push_back(file);
  6612. return true;
  6613. },
  6614. [&](const char *data, size_t data_length) {
  6615. items.back().content.append(data, data_length);
  6616. return true;
  6617. });
  6618. EXPECT_EQ(5u, items.size());
  6619. {
  6620. const auto &file = get_file_value(items, "text1");
  6621. EXPECT_TRUE(file.filename.empty());
  6622. EXPECT_EQ("text default", file.content);
  6623. }
  6624. {
  6625. const auto &file = get_file_value(items, "text2");
  6626. EXPECT_TRUE(file.filename.empty());
  6627. EXPECT_EQ("aωb", file.content);
  6628. }
  6629. {
  6630. const auto &file = get_file_value(items, "file1");
  6631. EXPECT_EQ("hello.txt", file.filename);
  6632. EXPECT_EQ("text/plain", file.content_type);
  6633. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6634. }
  6635. {
  6636. const auto &file = get_file_value(items, "file2");
  6637. EXPECT_EQ("world.json", file.filename);
  6638. EXPECT_EQ("application/json", file.content_type);
  6639. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6640. }
  6641. {
  6642. const auto &file = get_file_value(items, "file3");
  6643. EXPECT_TRUE(file.filename.empty());
  6644. EXPECT_EQ("application/octet-stream", file.content_type);
  6645. EXPECT_EQ(0u, file.content.size());
  6646. }
  6647. } else {
  6648. std::string body;
  6649. content_reader([&](const char *data, size_t data_length) {
  6650. EXPECT_EQ(7U, data_length);
  6651. body.append(data, data_length);
  6652. return true;
  6653. });
  6654. EXPECT_EQ(body, "content");
  6655. res.set_content(body, "text/plain");
  6656. }
  6657. })
  6658. .Put("/content_receiver",
  6659. [&](const Request & /*req*/, Response &res,
  6660. const ContentReader &content_reader) {
  6661. std::string body;
  6662. content_reader([&](const char *data, size_t data_length) {
  6663. body.append(data, data_length);
  6664. return true;
  6665. });
  6666. EXPECT_EQ(body, "content");
  6667. res.set_content(body, "text/plain");
  6668. })
  6669. .Patch("/content_receiver",
  6670. [&](const Request & /*req*/, Response &res,
  6671. const ContentReader &content_reader) {
  6672. std::string body;
  6673. content_reader([&](const char *data, size_t data_length) {
  6674. body.append(data, data_length);
  6675. return true;
  6676. });
  6677. EXPECT_EQ(body, "content");
  6678. res.set_content(body, "text/plain");
  6679. })
  6680. .Post("/query-string-and-body",
  6681. [&](const Request &req, Response & /*res*/) {
  6682. ASSERT_TRUE(req.has_param("key"));
  6683. EXPECT_EQ(req.get_param_value("key"), "value");
  6684. EXPECT_EQ(req.body, "content");
  6685. })
  6686. .Get("/last-request",
  6687. [&](const Request &req, Response & /*res*/) {
  6688. EXPECT_EQ("close", req.get_header_value("Connection"));
  6689. })
  6690. .Get(R"(/redirect/(\d+))",
  6691. [&](const Request &req, Response &res) {
  6692. auto num = std::stoi(req.matches[1]) + 1;
  6693. std::string url = "/redirect/" + std::to_string(num);
  6694. res.set_redirect(url);
  6695. })
  6696. .Post("/binary",
  6697. [&](const Request &req, Response &res) {
  6698. EXPECT_EQ(4U, req.body.size());
  6699. EXPECT_EQ("application/octet-stream",
  6700. req.get_header_value("Content-Type"));
  6701. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6702. res.set_content(req.body, "application/octet-stream");
  6703. })
  6704. .Put("/binary",
  6705. [&](const Request &req, Response &res) {
  6706. EXPECT_EQ(4U, req.body.size());
  6707. EXPECT_EQ("application/octet-stream",
  6708. req.get_header_value("Content-Type"));
  6709. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6710. res.set_content(req.body, "application/octet-stream");
  6711. })
  6712. .Patch("/binary",
  6713. [&](const Request &req, Response &res) {
  6714. EXPECT_EQ(4U, req.body.size());
  6715. EXPECT_EQ("application/octet-stream",
  6716. req.get_header_value("Content-Type"));
  6717. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6718. res.set_content(req.body, "application/octet-stream");
  6719. })
  6720. .Delete("/binary",
  6721. [&](const Request &req, Response &res) {
  6722. EXPECT_EQ(4U, req.body.size());
  6723. EXPECT_EQ("application/octet-stream",
  6724. req.get_header_value("Content-Type"));
  6725. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6726. res.set_content(req.body, "application/octet-stream");
  6727. })
  6728. .Get("/issue1772",
  6729. [&](const Request & /*req*/, Response &res) {
  6730. res.status = 401;
  6731. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6732. })
  6733. .Delete("/issue609",
  6734. [](const httplib::Request &, httplib::Response &res,
  6735. const httplib::ContentReader &) {
  6736. res.set_content("ok", "text/plain");
  6737. })
  6738. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6739. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6740. .Get("/compress",
  6741. [&](const Request & /*req*/, Response &res) {
  6742. res.set_content(
  6743. "12345678901234567890123456789012345678901234567890123456789"
  6744. "01234567890123456789012345678901234567890",
  6745. "text/plain");
  6746. })
  6747. .Get("/compress-with-charset",
  6748. [&](const Request & /*req*/, Response &res) {
  6749. res.set_content(
  6750. "12345678901234567890123456789012345678901234567890123456789"
  6751. "01234567890123456789012345678901234567890",
  6752. "application/json; charset=utf-8");
  6753. })
  6754. .Get("/nocompress",
  6755. [&](const Request & /*req*/, Response &res) {
  6756. res.set_content(
  6757. "12345678901234567890123456789012345678901234567890123456789"
  6758. "01234567890123456789012345678901234567890",
  6759. "application/octet-stream");
  6760. })
  6761. .Post("/compress-multipart",
  6762. [&](const Request &req, Response & /*res*/) {
  6763. EXPECT_EQ(2u, req.form.fields.size());
  6764. ASSERT_TRUE(!req.form.has_field("???"));
  6765. {
  6766. const auto &text = req.form.get_field("key1");
  6767. EXPECT_EQ("test", text);
  6768. }
  6769. {
  6770. const auto &text = req.form.get_field("key2");
  6771. EXPECT_EQ("--abcdefg123", text);
  6772. }
  6773. })
  6774. #endif
  6775. ;
  6776. persons_["john"] = "programmer";
  6777. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6778. svr_.wait_until_ready();
  6779. }
  6780. virtual void TearDown() {
  6781. svr_.stop();
  6782. if (!request_threads_.empty()) {
  6783. std::this_thread::sleep_for(std::chrono::seconds(1));
  6784. for (auto &t : request_threads_) {
  6785. t.join();
  6786. }
  6787. }
  6788. t_.join();
  6789. }
  6790. map<string, string> persons_;
  6791. #ifdef CPPHTTPLIB_SSL_ENABLED
  6792. SSLClient cli_;
  6793. SSLServer svr_;
  6794. #else
  6795. Client cli_;
  6796. Server svr_;
  6797. #endif
  6798. thread t_;
  6799. std::vector<thread> request_threads_;
  6800. };
  6801. TEST_F(ServerTest, GetMethod200) {
  6802. auto res = cli_.Get("/hi");
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. EXPECT_EQ("HTTP/1.1", res->version);
  6805. EXPECT_EQ(StatusCode::OK_200, res->status);
  6806. EXPECT_EQ("OK", res->reason);
  6807. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6808. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6809. EXPECT_EQ("Hello World!", res->body);
  6810. }
  6811. TEST_F(ServerTest, GetEmptyFile) {
  6812. auto res = cli_.Get("/empty_file");
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6816. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6817. EXPECT_EQ("", res->body);
  6818. }
  6819. TEST_F(ServerTest, GetFileContent) {
  6820. auto res = cli_.Get("/file_content");
  6821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6822. EXPECT_EQ(StatusCode::OK_200, res->status);
  6823. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6824. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6825. EXPECT_EQ("test.html", res->body);
  6826. }
  6827. TEST_F(ServerTest, GetFileContentWithRange) {
  6828. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6830. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6831. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6832. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6833. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6834. EXPECT_EQ("est", res->body);
  6835. }
  6836. TEST_F(ServerTest, GetFileContentWithContentType) {
  6837. auto res = cli_.Get("/file_content_with_content_type");
  6838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6839. EXPECT_EQ(StatusCode::OK_200, res->status);
  6840. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6841. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6842. EXPECT_EQ("file\n", res->body);
  6843. }
  6844. TEST_F(ServerTest, GetInvalidFileContent) {
  6845. auto res = cli_.Get("/invalid_file_content");
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6848. }
  6849. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6850. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6852. EXPECT_EQ("HTTP/1.1", res->version);
  6853. EXPECT_EQ(StatusCode::OK_200, res->status);
  6854. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6855. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6856. EXPECT_EQ("Hello World!", res->body);
  6857. }
  6858. TEST_F(ServerTest, GetMethod302) {
  6859. auto res = cli_.Get("/");
  6860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6861. EXPECT_EQ(StatusCode::Found_302, res->status);
  6862. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6863. }
  6864. TEST_F(ServerTest, GetMethod302Redirect) {
  6865. cli_.set_follow_location(true);
  6866. auto res = cli_.Get("/");
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. EXPECT_EQ(StatusCode::OK_200, res->status);
  6869. EXPECT_EQ("Hello World!", res->body);
  6870. EXPECT_EQ("/hi", res->location);
  6871. }
  6872. TEST_F(ServerTest, GetMethod404) {
  6873. auto res = cli_.Get("/invalid");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6876. }
  6877. TEST_F(ServerTest, HeadMethod200) {
  6878. auto res = cli_.Head("/hi");
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. EXPECT_EQ(StatusCode::OK_200, res->status);
  6881. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6882. EXPECT_TRUE(res->body.empty());
  6883. }
  6884. TEST_F(ServerTest, HeadMethod200Static) {
  6885. auto res = cli_.Head("/mount/dir/index.html");
  6886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6887. EXPECT_EQ(StatusCode::OK_200, res->status);
  6888. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6889. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6890. EXPECT_TRUE(res->body.empty());
  6891. }
  6892. TEST_F(ServerTest, HeadMethod404) {
  6893. auto res = cli_.Head("/invalid");
  6894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6895. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6896. EXPECT_TRUE(res->body.empty());
  6897. }
  6898. TEST_F(ServerTest, GetMethodPersonJohn) {
  6899. auto res = cli_.Get("/person/john");
  6900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6901. EXPECT_EQ(StatusCode::OK_200, res->status);
  6902. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6903. EXPECT_EQ("programmer", res->body);
  6904. }
  6905. TEST_F(ServerTest, PostMethod1) {
  6906. auto res = cli_.Get("/person/john1");
  6907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6908. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6909. res = cli_.Post("/person", "name=john1&note=coder",
  6910. "application/x-www-form-urlencoded");
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. ASSERT_EQ(StatusCode::OK_200, res->status);
  6913. res = cli_.Get("/person/john1");
  6914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6915. ASSERT_EQ(StatusCode::OK_200, res->status);
  6916. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6917. ASSERT_EQ("coder", res->body);
  6918. }
  6919. TEST_F(ServerTest, PostMethod2) {
  6920. auto res = cli_.Get("/person/john2");
  6921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6922. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6923. Params params;
  6924. params.emplace("name", "john2");
  6925. params.emplace("note", "coder");
  6926. res = cli_.Post("/person", params);
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. ASSERT_EQ(StatusCode::OK_200, res->status);
  6929. res = cli_.Get("/person/john2");
  6930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6931. ASSERT_EQ(StatusCode::OK_200, res->status);
  6932. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6933. ASSERT_EQ("coder", res->body);
  6934. }
  6935. TEST_F(ServerTest, PutMethod3) {
  6936. auto res = cli_.Get("/person/john3");
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6939. Params params;
  6940. params.emplace("name", "john3");
  6941. params.emplace("note", "coder");
  6942. res = cli_.Put("/person", params);
  6943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6944. ASSERT_EQ(StatusCode::OK_200, res->status);
  6945. res = cli_.Get("/person/john3");
  6946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6947. ASSERT_EQ(StatusCode::OK_200, res->status);
  6948. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6949. ASSERT_EQ("coder", res->body);
  6950. }
  6951. TEST_F(ServerTest, DeleteMethod1) {
  6952. auto res = cli_.Get("/person/john4");
  6953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6954. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6955. Params params;
  6956. params.emplace("name", "john4");
  6957. params.emplace("note", "coder");
  6958. res = cli_.Post("/person", params);
  6959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6960. ASSERT_EQ(StatusCode::OK_200, res->status);
  6961. res = cli_.Get("/person/john4");
  6962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6963. ASSERT_EQ(StatusCode::OK_200, res->status);
  6964. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6965. ASSERT_EQ("coder", res->body);
  6966. Params delete_params;
  6967. delete_params.emplace("name", "john4");
  6968. res = cli_.Delete("/person", delete_params);
  6969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6970. ASSERT_EQ(StatusCode::OK_200, res->status);
  6971. ASSERT_EQ("DELETED", res->body);
  6972. res = cli_.Get("/person/john4");
  6973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6974. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6975. }
  6976. TEST_F(ServerTest, DeleteMethod2) {
  6977. auto res = cli_.Get("/person/john5");
  6978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6979. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6980. Params params;
  6981. params.emplace("name", "john5");
  6982. params.emplace("note", "developer");
  6983. res = cli_.Post("/person", params);
  6984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6985. ASSERT_EQ(StatusCode::OK_200, res->status);
  6986. res = cli_.Get("/person/john5");
  6987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6988. ASSERT_EQ(StatusCode::OK_200, res->status);
  6989. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6990. ASSERT_EQ("developer", res->body);
  6991. Params delete_params;
  6992. delete_params.emplace("name", "john5");
  6993. Headers headers;
  6994. headers.emplace("Custom-Header", "test-value");
  6995. res = cli_.Delete("/person", headers, delete_params);
  6996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6997. ASSERT_EQ(StatusCode::OK_200, res->status);
  6998. ASSERT_EQ("DELETED", res->body);
  6999. res = cli_.Get("/person/john5");
  7000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7001. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7002. }
  7003. TEST_F(ServerTest, DeleteMethod3) {
  7004. auto res = cli_.Get("/person/john6");
  7005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7006. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7007. Params params;
  7008. params.emplace("name", "john6");
  7009. params.emplace("note", "tester");
  7010. res = cli_.Post("/person", params);
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. ASSERT_EQ(StatusCode::OK_200, res->status);
  7013. res = cli_.Get("/person/john6");
  7014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7015. ASSERT_EQ(StatusCode::OK_200, res->status);
  7016. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  7017. ASSERT_EQ("tester", res->body);
  7018. Params delete_params;
  7019. delete_params.emplace("name", "john6");
  7020. Headers headers;
  7021. headers.emplace("Custom-Header", "test-value");
  7022. res = cli_.Delete("/person", headers, delete_params, nullptr);
  7023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7024. ASSERT_EQ(StatusCode::OK_200, res->status);
  7025. ASSERT_EQ("DELETED", res->body);
  7026. res = cli_.Get("/person/john6");
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7029. }
  7030. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  7031. Params params;
  7032. params.emplace("json", JSON_DATA);
  7033. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  7034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7035. ASSERT_EQ(StatusCode::OK_200, res->status);
  7036. ASSERT_EQ(JSON_DATA, res->body);
  7037. }
  7038. TEST_F(ServerTest, PostEmptyContent) {
  7039. auto res = cli_.Post("/empty", "", "text/plain");
  7040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7041. ASSERT_EQ(StatusCode::OK_200, res->status);
  7042. ASSERT_EQ("empty", res->body);
  7043. }
  7044. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  7045. auto res = cli_.Post("/empty-no-content-type");
  7046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7047. ASSERT_EQ(StatusCode::OK_200, res->status);
  7048. ASSERT_EQ("empty-no-content-type", res->body);
  7049. }
  7050. TEST_F(ServerTest, PostPathOnly) {
  7051. auto res = cli_.Post("/path-only");
  7052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7053. ASSERT_EQ(StatusCode::OK_200, res->status);
  7054. ASSERT_EQ("path-only", res->body);
  7055. }
  7056. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  7057. auto res = cli_.Post("/path-headers-only",
  7058. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  7059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7060. ASSERT_EQ(StatusCode::OK_200, res->status);
  7061. ASSERT_EQ("path-headers-only", res->body);
  7062. }
  7063. TEST_F(ServerTest, PostLarge) {
  7064. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  7065. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7066. ASSERT_EQ(StatusCode::OK_200, res->status);
  7067. EXPECT_EQ(LARGE_DATA, res->body);
  7068. }
  7069. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  7070. auto res = cli_.Put("/empty-no-content-type");
  7071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7072. ASSERT_EQ(StatusCode::OK_200, res->status);
  7073. ASSERT_EQ("empty-no-content-type", res->body);
  7074. }
  7075. TEST_F(ServerTest, GetMethodDir) {
  7076. auto res = cli_.Get("/dir/");
  7077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7078. EXPECT_EQ(StatusCode::OK_200, res->status);
  7079. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7080. auto body = R"(<html>
  7081. <head>
  7082. </head>
  7083. <body>
  7084. <a href="/dir/test.html">Test</a>
  7085. <a href="/hi">hi</a>
  7086. </body>
  7087. </html>
  7088. )";
  7089. EXPECT_EQ(body, res->body);
  7090. }
  7091. TEST_F(ServerTest, GetMethodDirTest) {
  7092. auto res = cli_.Get("/dir/test.html");
  7093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7094. EXPECT_EQ(StatusCode::OK_200, res->status);
  7095. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7096. EXPECT_EQ("test.html", res->body);
  7097. }
  7098. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  7099. auto res = cli_.Get("/dir/../dir/test.html");
  7100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7101. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7102. }
  7103. TEST_F(ServerTest, GetMethodInvalidPath) {
  7104. auto res = cli_.Get("/dir/../test.html");
  7105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7106. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7107. }
  7108. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  7109. auto res = cli_.Get("/../www/dir/test.html");
  7110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7111. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7112. }
  7113. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  7114. auto res = cli_.Get("/dir/../../www/dir/test.html");
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7117. }
  7118. TEST_F(ServerTest, GetMethodDirMountTest) {
  7119. auto res = cli_.Get("/mount/dir/test.html");
  7120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7121. EXPECT_EQ(StatusCode::OK_200, res->status);
  7122. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7123. EXPECT_EQ("test.html", res->body);
  7124. }
  7125. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  7126. auto res = cli_.Get("/mount/dir/../dir/test.html");
  7127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7128. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7129. }
  7130. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  7131. auto res = cli_.Get("/mount/dir/../test.html");
  7132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7133. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7134. }
  7135. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  7136. auto res = cli_.Get("/mount/dir/test.html%00.js");
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7139. }
  7140. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  7141. auto res = cli_.Get("/mount/../www2/dir/test.html");
  7142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7143. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7144. }
  7145. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  7146. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  7147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7148. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7149. }
  7150. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  7151. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7154. }
  7155. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  7156. auto res = cli_.Get("/mount/dir");
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7159. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7160. }
  7161. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7162. auto res = cli_.Get("//dir");
  7163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7164. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7165. EXPECT_FALSE(res->has_header("Location"));
  7166. }
  7167. TEST_F(ServerTest, PostMethod303) {
  7168. auto res = cli_.Post("/1", "body", "text/plain");
  7169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7170. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7171. EXPECT_EQ("/2", res->get_header_value("Location"));
  7172. }
  7173. TEST_F(ServerTest, PostMethod303Redirect) {
  7174. cli_.set_follow_location(true);
  7175. auto res = cli_.Post("/1", "body", "text/plain");
  7176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7177. EXPECT_EQ(StatusCode::OK_200, res->status);
  7178. EXPECT_EQ("redirected.", res->body);
  7179. EXPECT_EQ("/2", res->location);
  7180. }
  7181. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7182. auto res = cli_.Get("/dir/test.abcde");
  7183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7184. EXPECT_EQ(StatusCode::OK_200, res->status);
  7185. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7186. EXPECT_EQ("abcde", res->body);
  7187. }
  7188. TEST_F(ServerTest, StaticFileRange) {
  7189. auto res =
  7190. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7192. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7193. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7194. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7195. EXPECT_EQ(true, res->has_header("Content-Range"));
  7196. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7197. EXPECT_EQ(std::string("cd"), res->body);
  7198. }
  7199. TEST_F(ServerTest, StaticFileRanges) {
  7200. auto res = cli_.Get("/dir/test.abcde",
  7201. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7203. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7204. EXPECT_TRUE(
  7205. res->get_header_value("Content-Type")
  7206. .find(
  7207. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7208. 0);
  7209. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7210. }
  7211. TEST_F(ServerTest, StaticFileRangeHead) {
  7212. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7214. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7215. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7216. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7217. EXPECT_EQ(true, res->has_header("Content-Range"));
  7218. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7219. }
  7220. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7221. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7223. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7224. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7225. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7226. EXPECT_EQ(true, res->has_header("Content-Range"));
  7227. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7228. res->get_header_value("Content-Range"));
  7229. EXPECT_EQ("LAST\n", res->body);
  7230. }
  7231. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7232. auto res =
  7233. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7236. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7237. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7238. EXPECT_EQ(true, res->has_header("Content-Range"));
  7239. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7240. }
  7241. TEST_F(ServerTest, StaticFileBigFile) {
  7242. auto res = cli_.Get("/dir/1MB.txt");
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::OK_200, res->status);
  7245. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7246. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7247. }
  7248. TEST_F(ServerTest, InvalidBaseDirMount) {
  7249. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7250. }
  7251. TEST_F(ServerTest, Binary) {
  7252. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7253. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7254. "application/octet-stream");
  7255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7256. ASSERT_EQ(StatusCode::OK_200, res->status);
  7257. ASSERT_EQ(4U, res->body.size());
  7258. res = cli_.Put("/binary", binary.data(), binary.size(),
  7259. "application/octet-stream");
  7260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7261. ASSERT_EQ(StatusCode::OK_200, res->status);
  7262. ASSERT_EQ(4U, res->body.size());
  7263. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7264. "application/octet-stream");
  7265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7266. ASSERT_EQ(StatusCode::OK_200, res->status);
  7267. ASSERT_EQ(4U, res->body.size());
  7268. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7269. "application/octet-stream");
  7270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7271. ASSERT_EQ(StatusCode::OK_200, res->status);
  7272. ASSERT_EQ(4U, res->body.size());
  7273. }
  7274. TEST_F(ServerTest, BinaryString) {
  7275. auto binary = std::string("\x00\x01\x02\x03", 4);
  7276. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7278. ASSERT_EQ(StatusCode::OK_200, res->status);
  7279. ASSERT_EQ(4U, res->body.size());
  7280. res = cli_.Put("/binary", binary, "application/octet-stream");
  7281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7282. ASSERT_EQ(StatusCode::OK_200, res->status);
  7283. ASSERT_EQ(4U, res->body.size());
  7284. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7286. ASSERT_EQ(StatusCode::OK_200, res->status);
  7287. ASSERT_EQ(4U, res->body.size());
  7288. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7290. ASSERT_EQ(StatusCode::OK_200, res->status);
  7291. ASSERT_EQ(4U, res->body.size());
  7292. }
  7293. TEST_F(ServerTest, EmptyRequest) {
  7294. auto res = cli_.Get("");
  7295. ASSERT_TRUE(!res);
  7296. EXPECT_EQ(Error::Connection, res.error());
  7297. }
  7298. TEST_F(ServerTest, LongRequest) {
  7299. std::string request;
  7300. for (size_t i = 0; i < 545; i++) {
  7301. request += "/TooLongRequest";
  7302. }
  7303. request += "OK";
  7304. auto res = cli_.Get(request.c_str());
  7305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7306. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7307. }
  7308. TEST_F(ServerTest, TooLongRequest) {
  7309. std::string request;
  7310. for (size_t i = 0; i < 546; i++) {
  7311. request += "/TooLongRequest";
  7312. }
  7313. request += "_NG";
  7314. auto start = std::chrono::high_resolution_clock::now();
  7315. cli_.set_keep_alive(true);
  7316. auto res = cli_.Get(request.c_str());
  7317. auto end = std::chrono::high_resolution_clock::now();
  7318. auto elapsed =
  7319. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7320. .count();
  7321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7322. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7323. EXPECT_LE(elapsed, 1000);
  7324. EXPECT_EQ("close", res->get_header_value("Connection"));
  7325. EXPECT_FALSE(cli_.is_socket_open());
  7326. }
  7327. TEST_F(ServerTest, AlmostTooLongRequest) {
  7328. // test for #2046 - URI length check shouldn't include other content on req
  7329. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7330. // leading /, space, HTTP/1.1)
  7331. std::string request =
  7332. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7333. auto res = cli_.Get(request.c_str());
  7334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7335. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7336. }
  7337. TEST_F(ServerTest, LongHeader) {
  7338. Request req;
  7339. req.method = "GET";
  7340. req.path = "/hi";
  7341. std::string host_and_port;
  7342. host_and_port += HOST;
  7343. host_and_port += ":";
  7344. host_and_port += std::to_string(PORT);
  7345. req.headers.emplace("Host", host_and_port.c_str());
  7346. req.headers.emplace("Accept", "*/*");
  7347. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7348. req.headers.emplace(
  7349. "Header-Name",
  7350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7372. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7373. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7374. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7375. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7376. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7377. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7378. "@@@@@@@@@@@@@@@@");
  7379. auto res = std::make_shared<Response>();
  7380. auto error = Error::Success;
  7381. auto ret = cli_.send(req, *res, error);
  7382. ASSERT_TRUE(ret);
  7383. EXPECT_EQ(StatusCode::OK_200, res->status);
  7384. }
  7385. TEST_F(ServerTest, LongQueryValue) {
  7386. auto start = std::chrono::high_resolution_clock::now();
  7387. cli_.set_keep_alive(true);
  7388. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7389. auto end = std::chrono::high_resolution_clock::now();
  7390. auto elapsed =
  7391. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7392. .count();
  7393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7394. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7395. EXPECT_LE(elapsed, 1000);
  7396. EXPECT_EQ("close", res->get_header_value("Connection"));
  7397. EXPECT_FALSE(cli_.is_socket_open());
  7398. }
  7399. TEST_F(ServerTest, TooLongQueryValue) {
  7400. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7401. ASSERT_FALSE(res);
  7402. EXPECT_EQ(Error::Read, res.error());
  7403. }
  7404. TEST_F(ServerTest, TooLongHeader) {
  7405. Request req;
  7406. req.method = "GET";
  7407. req.path = "/hi";
  7408. std::string host_and_port;
  7409. host_and_port += HOST;
  7410. host_and_port += ":";
  7411. host_and_port += std::to_string(PORT);
  7412. req.headers.emplace("Host", host_and_port.c_str());
  7413. req.headers.emplace("Accept", "*/*");
  7414. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7415. req.headers.emplace(
  7416. "Header-Name",
  7417. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7418. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7419. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7420. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7421. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7422. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7423. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7424. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7425. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7426. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7427. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7428. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7429. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7430. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7431. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7432. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7433. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7434. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7435. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7436. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7437. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7438. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7439. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7440. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7441. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7442. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7443. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7444. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7445. "@@@@@@@@@@@@@@@@@");
  7446. auto res = std::make_shared<Response>();
  7447. auto error = Error::Success;
  7448. auto ret = cli_.send(req, *res, error);
  7449. ASSERT_TRUE(ret);
  7450. EXPECT_EQ(StatusCode::OK_200, res->status);
  7451. }
  7452. TEST_F(ServerTest, HeaderCountAtLimit) {
  7453. // Test with headers just under the 100 limit
  7454. httplib::Headers headers;
  7455. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7456. // This should keep us just under the 100 header limit
  7457. for (int i = 0; i < 95; i++) {
  7458. std::string name = "X-Test-Header-" + std::to_string(i);
  7459. std::string value = "value" + std::to_string(i);
  7460. headers.emplace(name, value);
  7461. }
  7462. // This should work fine as we're under the limit
  7463. auto res = cli_.Get("/hi", headers);
  7464. EXPECT_TRUE(res);
  7465. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7466. }
  7467. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7468. // Test with many headers to exceed the 100 limit
  7469. httplib::Headers headers;
  7470. // Add 150 headers to definitely exceed the 100 limit
  7471. for (int i = 0; i < 150; i++) {
  7472. std::string name = "X-Test-Header-" + std::to_string(i);
  7473. std::string value = "value" + std::to_string(i);
  7474. headers.emplace(name, value);
  7475. }
  7476. // This should fail due to exceeding header count limit
  7477. cli_.set_keep_alive(true);
  7478. auto res = cli_.Get("/hi", headers);
  7479. // The server should respond with 400 Bad Request
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7482. EXPECT_EQ("close", res->get_header_value("Connection"));
  7483. EXPECT_FALSE(cli_.is_socket_open());
  7484. }
  7485. TEST_F(ServerTest, PercentEncoding) {
  7486. auto res = cli_.Get("/e%6edwith%");
  7487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. }
  7490. TEST_F(ServerTest, PercentEncodingUnicode) {
  7491. auto res = cli_.Get("/e%u006edwith%");
  7492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7493. EXPECT_EQ(StatusCode::OK_200, res->status);
  7494. }
  7495. TEST_F(ServerTest, InvalidPercentEncoding) {
  7496. auto res = cli_.Get("/%endwith%");
  7497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7498. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7499. }
  7500. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7501. auto res = cli_.Get("/%uendwith%");
  7502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7503. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7504. }
  7505. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7506. auto res = cli_.Get("/hello?aaa=bbb%");
  7507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7508. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7509. }
  7510. TEST_F(ServerTest, PlusSignEncoding) {
  7511. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7513. EXPECT_EQ(StatusCode::OK_200, res->status);
  7514. EXPECT_EQ("a +b", res->body);
  7515. }
  7516. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7517. // This test simulates a potential DoS attack using many headers
  7518. // to verify our security fix prevents memory exhaustion
  7519. httplib::Headers attack_headers;
  7520. // Attempt to add many headers like an attacker would (200 headers to far
  7521. // exceed limit)
  7522. for (int i = 0; i < 200; i++) {
  7523. std::string name = "X-Attack-Header-" + std::to_string(i);
  7524. std::string value = "attack_payload_" + std::to_string(i);
  7525. attack_headers.emplace(name, value);
  7526. }
  7527. // Try to POST with excessive headers
  7528. cli_.set_keep_alive(true);
  7529. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7530. // Should either fail or return 400 Bad Request due to security limit
  7531. if (res) {
  7532. // If we get a response, it should be 400 Bad Request
  7533. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7534. EXPECT_EQ("close", res->get_header_value("Connection"));
  7535. }
  7536. EXPECT_FALSE(cli_.is_socket_open());
  7537. }
  7538. TEST_F(ServerTest, MultipartFormData) {
  7539. UploadFormDataItems items = {
  7540. {"text1", "text default", "", ""},
  7541. {"text2", "aωb", "", ""},
  7542. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7543. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7544. {"file3", "", "", "application/octet-stream"},
  7545. {"file4", "", "", " application/json tmp-string "}};
  7546. auto res = cli_.Post("/multipart", items);
  7547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7548. EXPECT_EQ(StatusCode::OK_200, res->status);
  7549. }
  7550. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7551. UploadFormDataItems items = {
  7552. {"text", "default text", "", ""},
  7553. {"multi_text1", "aaaaa", "", ""},
  7554. {"multi_text1", "bbbbb", "", ""},
  7555. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7556. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7557. "application/json"},
  7558. };
  7559. auto res = cli_.Post("/multipart/multi_file_values", items);
  7560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7561. EXPECT_EQ(StatusCode::OK_200, res->status);
  7562. }
  7563. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7564. auto res = cli_.Get("/hi");
  7565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7566. EXPECT_EQ(StatusCode::OK_200, res->status);
  7567. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7568. EXPECT_EQ("Hello World!", res->body);
  7569. }
  7570. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7571. Request req;
  7572. req.method = "POST";
  7573. req.path = "/chunked";
  7574. std::string host_and_port;
  7575. host_and_port += HOST;
  7576. host_and_port += ":";
  7577. host_and_port += std::to_string(PORT);
  7578. req.headers.emplace("Host", host_and_port.c_str());
  7579. req.headers.emplace("Accept", "*/*");
  7580. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7581. req.headers.emplace("Content-Type", "text/plain");
  7582. req.headers.emplace("Content-Length", "0");
  7583. req.headers.emplace(
  7584. "Transfer-Encoding",
  7585. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7586. // Client does not chunk, so make a chunked body manually.
  7587. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7588. auto res = std::make_shared<Response>();
  7589. auto error = Error::Success;
  7590. auto ret = cli_.send(req, *res, error);
  7591. ASSERT_TRUE(ret);
  7592. EXPECT_EQ(StatusCode::OK_200, res->status);
  7593. }
  7594. template <typename ClientT>
  7595. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7596. int expected_status) {
  7597. Request req;
  7598. req.method = "POST";
  7599. req.path = "/chunked";
  7600. std::string host_and_port;
  7601. host_and_port += HOST;
  7602. host_and_port += ":";
  7603. host_and_port += std::to_string(PORT);
  7604. req.headers.emplace("Host", host_and_port.c_str());
  7605. req.headers.emplace("Content-Length", "0");
  7606. req.headers.emplace("Transfer-Encoding", "chunked");
  7607. req.body = body;
  7608. auto res = std::make_shared<Response>();
  7609. auto error = Error::Success;
  7610. ASSERT_TRUE(cli.send(req, *res, error));
  7611. EXPECT_EQ(expected_status, res->status);
  7612. }
  7613. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7614. // rather than treat them as valid lengths.
  7615. template <typename ClientT>
  7616. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7617. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7618. }
  7619. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7620. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7621. }
  7622. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7623. expect_chunked_body_rejected(
  7624. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7625. }
  7626. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7627. // chunk-size line carries no CR, LF or other control character ahead of its
  7628. // terminator. Such a line must be refused rather than read as extension text.
  7629. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7630. expect_chunked_body_rejected(
  7631. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7632. }
  7633. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7634. expect_chunked_body_rejected(
  7635. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7636. }
  7637. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7638. expect_chunked_body_rejected(
  7639. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7640. }
  7641. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7642. // The literal stays split: a hex escape consumes every hex digit that
  7643. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7644. expect_chunked_body_rejected(
  7645. cli_, "4;a\x01"
  7646. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7647. }
  7648. // The bytes around chunk data are no payload, so they cannot ride on the
  7649. // payload limit
  7650. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7651. // Small enough that the whole request is sent before the server turns it
  7652. // down, yet past the limit by the last chunks
  7653. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7654. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7655. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7656. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7657. SCOPED_TRACE(size_line.substr(0, 2));
  7658. std::string body;
  7659. for (auto c : std::string("dechunked post body")) {
  7660. body += size_line + "\r\n" + c + "\r\n";
  7661. }
  7662. body += "0\r\n\r\n";
  7663. expect_chunked_body_rejected(cli_, body.c_str());
  7664. }
  7665. }
  7666. TEST_F(ServerTest, AcceptsChunkExtension) {
  7667. expect_chunked_body_status(cli_,
  7668. "4;name=value\r\ndech\r\n"
  7669. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7670. "0;last\r\n\r\n",
  7671. StatusCode::OK_200);
  7672. }
  7673. TEST_F(ServerTest, GetStreamed2) {
  7674. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7676. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7677. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7678. EXPECT_EQ(true, res->has_header("Content-Range"));
  7679. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7680. EXPECT_EQ(std::string("ab"), res->body);
  7681. }
  7682. TEST_F(ServerTest, GetStreamed) {
  7683. auto res = cli_.Get("/streamed");
  7684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7685. EXPECT_EQ(StatusCode::OK_200, res->status);
  7686. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7687. EXPECT_EQ(std::string("aaabbb"), res->body);
  7688. }
  7689. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7690. auto res = cli_.Get("/streamed-without-length",
  7691. Headers{make_range_header({{0, -1}})});
  7692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7693. EXPECT_EQ(StatusCode::OK_200, res->status);
  7694. EXPECT_EQ(false, res->has_header("Content-Length"));
  7695. EXPECT_EQ(false, res->has_header("Content-Range"));
  7696. EXPECT_EQ(std::string("abcdefg"), res->body);
  7697. }
  7698. TEST_F(ServerTest, GetStreamedWithRange1) {
  7699. auto res =
  7700. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7702. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7703. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7704. EXPECT_EQ(true, res->has_header("Content-Range"));
  7705. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7706. EXPECT_EQ(std::string("def"), res->body);
  7707. }
  7708. TEST_F(ServerTest, GetStreamedWithRange2) {
  7709. auto res =
  7710. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7712. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7713. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7714. EXPECT_EQ(true, res->has_header("Content-Range"));
  7715. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7716. EXPECT_EQ(std::string("bcdefg"), res->body);
  7717. }
  7718. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7719. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7721. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7722. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7723. EXPECT_EQ(true, res->has_header("Content-Range"));
  7724. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7725. EXPECT_EQ(std::string("efg"), res->body);
  7726. }
  7727. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7728. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7729. // the entire representation.
  7730. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7731. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7733. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7734. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7735. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7736. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7737. }
  7738. }
  7739. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7740. auto res =
  7741. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7743. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7744. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7745. EXPECT_EQ(false, res->has_header("Content-Range"));
  7746. EXPECT_EQ(0U, res->body.size());
  7747. }
  7748. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7749. // Only a 206 is served as a partial representation. Under any other status
  7750. // `apply_ranges()` reported the full content length, so the body must match
  7751. // that header, and the content provider must never be asked for an offset
  7752. // outside the representation.
  7753. auto check = [&](int status, const char *range) {
  7754. auto path =
  7755. std::string("/streamed-with-range?status=") + std::to_string(status);
  7756. auto ctx = path + " Range: " + range;
  7757. auto res = cli_.Get(path, Headers{{"Range", range}});
  7758. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7759. EXPECT_EQ(status, res->status) << ctx;
  7760. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7761. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7762. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7763. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7764. };
  7765. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7766. check(403, "bytes=3-5");
  7767. // The offset is far past the representation.
  7768. check(403, "bytes=100000-100200");
  7769. // `first_pos` is still -1 here, and the bounds asserts in
  7770. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7771. check(403, "bytes=-3");
  7772. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7773. // multipart branch would have written one that is empty.
  7774. check(403, "bytes=1-2, 4-5");
  7775. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7776. // covers the whole representation.
  7777. check(200, "bytes=3-5");
  7778. check(200, "bytes=1-2, 4-5");
  7779. }
  7780. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7781. auto res =
  7782. cli_.Get("/streamed-with-range",
  7783. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7784. "92233720368547758079223372036854775807"}});
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7787. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7788. EXPECT_EQ(false, res->has_header("Content-Range"));
  7789. EXPECT_EQ(0U, res->body.size());
  7790. }
  7791. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7792. auto res = cli_.Get(
  7793. "/with-range",
  7794. Headers{{"Range",
  7795. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7796. {"Accept-Encoding", ""}});
  7797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7798. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7799. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7800. EXPECT_EQ(true, res->has_header("Content-Range"));
  7801. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7802. EXPECT_EQ(std::string("abcdefg"), res->body);
  7803. }
  7804. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7805. auto res = cli_.Get("/with-range", Headers{
  7806. {"Range", "bytes=0-"},
  7807. {"Accept-Encoding", ""},
  7808. });
  7809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7810. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7811. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7812. EXPECT_EQ(true, res->has_header("Content-Range"));
  7813. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7814. EXPECT_EQ(std::string("abcdefg"), res->body);
  7815. }
  7816. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7817. auto res = cli_.Get("/streamed-with-range",
  7818. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7820. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7821. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7822. EXPECT_EQ(false, res->has_header("Content-Range"));
  7823. EXPECT_EQ(267U, res->body.size());
  7824. // Check that both range contents are present
  7825. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7826. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7827. // Check that Content-Range headers are present for both ranges
  7828. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7829. std::string::npos);
  7830. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7831. std::string::npos);
  7832. }
  7833. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7834. Ranges ranges;
  7835. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7836. ranges.emplace_back(0, -1);
  7837. }
  7838. auto res = cli_.Get("/streamed-with-range?error",
  7839. Headers{{make_range_header(ranges)}});
  7840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7841. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7842. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7843. EXPECT_EQ(false, res->has_header("Content-Range"));
  7844. EXPECT_EQ(0U, res->body.size());
  7845. }
  7846. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7847. auto res = cli_.Get("/streamed-with-range",
  7848. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7850. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7851. EXPECT_EQ(5U, res->body.size());
  7852. // Check that overlapping ranges are coalesced into a single range
  7853. EXPECT_EQ("bcdef", res->body);
  7854. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7855. // Should be single range, not multipart
  7856. EXPECT_TRUE(res->has_header("Content-Range"));
  7857. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7858. }
  7859. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7860. auto res = cli_.Get("/streamed-with-range",
  7861. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7863. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7864. EXPECT_EQ(268U, res->body.size());
  7865. // Check that both range contents are present
  7866. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7867. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7868. // Check that Content-Range headers are present for both ranges
  7869. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7870. std::string::npos);
  7871. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7872. std::string::npos);
  7873. }
  7874. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7875. auto res = cli_.Get("/streamed-with-range",
  7876. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7878. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7879. EXPECT_EQ(269U, res->body.size());
  7880. // Check that both duplicate range contents are present
  7881. size_t first_abc = res->body.find("abc\r\n");
  7882. EXPECT_TRUE(first_abc != std::string::npos);
  7883. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7884. EXPECT_TRUE(second_abc != std::string::npos);
  7885. // Check that Content-Range headers are present for both ranges
  7886. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7887. EXPECT_TRUE(first_range != std::string::npos);
  7888. size_t second_range =
  7889. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7890. EXPECT_TRUE(second_range != std::string::npos);
  7891. }
  7892. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7893. auto res =
  7894. cli_.Get("/streamed-with-range?error",
  7895. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7897. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7898. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7899. EXPECT_EQ(false, res->has_header("Content-Range"));
  7900. EXPECT_EQ(0U, res->body.size());
  7901. }
  7902. TEST_F(ServerTest, GetStreamedEndless) {
  7903. uint64_t offset = 0;
  7904. auto res = cli_.Get("/streamed-cancel",
  7905. [&](const char * /*data*/, uint64_t data_length) {
  7906. if (offset < 100) {
  7907. offset += data_length;
  7908. return true;
  7909. }
  7910. return false;
  7911. });
  7912. ASSERT_TRUE(!res);
  7913. EXPECT_EQ(Error::Canceled, res.error());
  7914. }
  7915. TEST_F(ServerTest, ClientStop) {
  7916. std::atomic_size_t count{4};
  7917. std::vector<std::thread> threads;
  7918. for (auto i = count.load(); i != 0; --i) {
  7919. threads.emplace_back([&]() {
  7920. auto res = cli_.Get("/streamed-cancel",
  7921. [&](const char *, uint64_t) { return true; });
  7922. --count;
  7923. ASSERT_TRUE(!res);
  7924. EXPECT_TRUE(res.error() == Error::Canceled ||
  7925. res.error() == Error::Read || res.error() == Error::Write);
  7926. });
  7927. }
  7928. std::this_thread::sleep_for(std::chrono::seconds(2));
  7929. while (count != 0) {
  7930. cli_.stop();
  7931. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7932. }
  7933. for (auto &t : threads) {
  7934. t.join();
  7935. }
  7936. }
  7937. TEST_F(ServerTest, GetWithRange1) {
  7938. auto res = cli_.Get("/with-range", Headers{
  7939. make_range_header({{3, 5}}),
  7940. {"Accept-Encoding", ""},
  7941. });
  7942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7943. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7944. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7945. EXPECT_EQ(true, res->has_header("Content-Range"));
  7946. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7947. EXPECT_EQ(std::string("def"), res->body);
  7948. }
  7949. TEST_F(ServerTest, GetWithRange2) {
  7950. auto res = cli_.Get("/with-range", Headers{
  7951. make_range_header({{1, -1}}),
  7952. {"Accept-Encoding", ""},
  7953. });
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7956. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7957. EXPECT_EQ(true, res->has_header("Content-Range"));
  7958. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7959. EXPECT_EQ(std::string("bcdefg"), res->body);
  7960. }
  7961. TEST_F(ServerTest, GetWithRange3) {
  7962. auto res = cli_.Get("/with-range", Headers{
  7963. make_range_header({{0, 0}}),
  7964. {"Accept-Encoding", ""},
  7965. });
  7966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7967. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7968. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7969. EXPECT_EQ(true, res->has_header("Content-Range"));
  7970. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7971. EXPECT_EQ(std::string("a"), res->body);
  7972. }
  7973. TEST_F(ServerTest, GetWithRange4) {
  7974. auto res = cli_.Get("/with-range", Headers{
  7975. make_range_header({{-1, 2}}),
  7976. {"Accept-Encoding", ""},
  7977. });
  7978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7979. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7980. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7981. EXPECT_EQ(true, res->has_header("Content-Range"));
  7982. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7983. EXPECT_EQ(std::string("fg"), res->body);
  7984. }
  7985. TEST_F(ServerTest, GetWithRange5) {
  7986. auto res = cli_.Get("/with-range", Headers{
  7987. make_range_header({{0, 5}}),
  7988. {"Accept-Encoding", ""},
  7989. });
  7990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7991. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7992. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7993. EXPECT_EQ(true, res->has_header("Content-Range"));
  7994. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7995. EXPECT_EQ(std::string("abcdef"), res->body);
  7996. }
  7997. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7998. auto res =
  7999. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  8000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8001. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  8002. }
  8003. TEST_F(ServerTest, GetWithRangeMultipart) {
  8004. auto res =
  8005. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  8006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8007. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8008. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  8009. EXPECT_EQ(false, res->has_header("Content-Range"));
  8010. EXPECT_EQ(267U, res->body.size());
  8011. }
  8012. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  8013. // RFC 9110 14.1.1: the set is satisfiable when any of its ranges is, and the
  8014. // unsatisfiable ones are left out of the response.
  8015. auto res = cli_.Get("/with-range",
  8016. Headers{make_range_header({{-1, 2}, {10000, 30000}}),
  8017. {"Accept-Encoding", ""}});
  8018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8019. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8020. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8021. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  8022. EXPECT_EQ(std::string("fg"), res->body);
  8023. }
  8024. TEST_F(ServerTest, GetWithRangeMultipartSkipsUnsatisfiableRange) {
  8025. auto res =
  8026. cli_.Get("/with-range",
  8027. Headers{{make_range_header({{1, 2}, {10000, 30000}, {4, 5}})}});
  8028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8029. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8030. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  8031. EXPECT_EQ(false, res->has_header("Content-Range"));
  8032. EXPECT_EQ(267U, res->body.size());
  8033. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  8034. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  8035. }
  8036. TEST_F(ServerTest, GetWithRangeMultipartNoneSatisfiable) {
  8037. for (auto range : {"bytes=7-, -0", "bytes=10000-30000, 7-8"}) {
  8038. auto res = cli_.Get("/with-range", Headers{{"Range", range}});
  8039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8040. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status) << range;
  8041. }
  8042. }
  8043. TEST_F(ServerTest, GetStreamedWithRangeSkipsUnsatisfiableRange) {
  8044. auto res =
  8045. cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=7-, 2-3"}});
  8046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8047. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8048. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8049. EXPECT_EQ("bytes 2-3/7", res->get_header_value("Content-Range"));
  8050. EXPECT_EQ(std::string("cd"), res->body);
  8051. }
  8052. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  8053. auto res = cli_.Get("/with-range-customized-response",
  8054. Headers{{make_range_header({{1, 2}})}});
  8055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8056. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8057. EXPECT_EQ(true, res->has_header("Content-Length"));
  8058. EXPECT_EQ(false, res->has_header("Content-Range"));
  8059. EXPECT_EQ(JSON_DATA, res->body);
  8060. }
  8061. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  8062. auto res = cli_.Get("/with-range-customized-response",
  8063. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  8064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8065. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8066. EXPECT_EQ(true, res->has_header("Content-Length"));
  8067. EXPECT_EQ(false, res->has_header("Content-Range"));
  8068. EXPECT_EQ(JSON_DATA, res->body);
  8069. }
  8070. TEST_F(ServerTest, Issue1772) {
  8071. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  8072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8073. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  8074. }
  8075. TEST_F(ServerTest, Issue609) {
  8076. auto res = cli_.Delete("/issue609");
  8077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8078. EXPECT_EQ(StatusCode::OK_200, res->status);
  8079. EXPECT_EQ(std::string("ok"), res->body);
  8080. }
  8081. TEST_F(ServerTest, GetStreamedChunked) {
  8082. auto res = cli_.Get("/streamed-chunked");
  8083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8084. EXPECT_EQ(StatusCode::OK_200, res->status);
  8085. EXPECT_EQ(std::string("123456789"), res->body);
  8086. }
  8087. TEST_F(ServerTest, GetStreamedChunked2) {
  8088. auto res = cli_.Get("/streamed-chunked2");
  8089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8090. EXPECT_EQ(StatusCode::OK_200, res->status);
  8091. EXPECT_EQ(std::string("123456789"), res->body);
  8092. }
  8093. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  8094. auto res = cli_.Get("/streamed-chunked-with-trailer");
  8095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8096. EXPECT_EQ(StatusCode::OK_200, res->status);
  8097. EXPECT_EQ(std::string("123456789"), res->body);
  8098. EXPECT_TRUE(res->has_header("Trailer"));
  8099. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  8100. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  8101. // Trailers are now stored separately from headers (security fix)
  8102. EXPECT_EQ(2U, res->trailers.size());
  8103. EXPECT_TRUE(res->has_trailer("Dummy1"));
  8104. EXPECT_TRUE(res->has_trailer("Dummy2"));
  8105. EXPECT_FALSE(res->has_trailer("Dummy3"));
  8106. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  8107. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  8108. // Verify trailers are NOT in headers (security verification)
  8109. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  8110. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  8111. }
  8112. TEST_F(ServerTest, LargeChunkedPost) {
  8113. Request req;
  8114. req.method = "POST";
  8115. req.path = "/large-chunked";
  8116. std::string host_and_port;
  8117. host_and_port += HOST;
  8118. host_and_port += ":";
  8119. host_and_port += std::to_string(PORT);
  8120. req.headers.emplace("Host", host_and_port.c_str());
  8121. req.headers.emplace("Accept", "*/*");
  8122. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  8123. req.headers.emplace("Content-Type", "text/plain");
  8124. req.headers.emplace("Content-Length", "0");
  8125. req.headers.emplace("Transfer-Encoding", "chunked");
  8126. std::string long_string(30 * 1024u, 'a');
  8127. std::string chunk = "7800\r\n" + long_string + "\r\n";
  8128. // Attempt to make a large enough post to exceed OS buffers, to test that
  8129. // the server handles short reads if the full chunk data isn't available.
  8130. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  8131. auto res = std::make_shared<Response>();
  8132. auto error = Error::Success;
  8133. auto ret = cli_.send(req, *res, error);
  8134. ASSERT_TRUE(ret);
  8135. EXPECT_EQ(StatusCode::OK_200, res->status);
  8136. }
  8137. TEST_F(ServerTest, GetMethodRemoteAddr) {
  8138. auto res = cli_.Get("/remote_addr");
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ(StatusCode::OK_200, res->status);
  8141. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8142. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  8143. }
  8144. TEST_F(ServerTest, GetMethodLocalAddr) {
  8145. auto res = cli_.Get("/local_addr");
  8146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8147. EXPECT_EQ(StatusCode::OK_200, res->status);
  8148. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8149. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  8150. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  8151. }
  8152. TEST_F(ServerTest, HTTPResponseSplitting) {
  8153. auto res = cli_.Get("/http_response_splitting");
  8154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8155. EXPECT_EQ(StatusCode::OK_200, res->status);
  8156. }
  8157. TEST_F(ServerTest, SlowRequest) {
  8158. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8159. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8160. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8161. }
  8162. #if 0
  8163. TEST_F(ServerTest, SlowPost) {
  8164. char buffer[64 * 1024];
  8165. memset(buffer, 0x42, sizeof(buffer));
  8166. auto res = cli_.Post(
  8167. "/slowpost", 64 * 1024 * 1024,
  8168. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8169. auto ret = sink.write(buffer, sizeof(buffer));
  8170. EXPECT_TRUE(ret);
  8171. return true;
  8172. },
  8173. "text/plain");
  8174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8175. EXPECT_EQ(StatusCode::OK_200, res->status);
  8176. }
  8177. TEST_F(ServerTest, SlowPostFail) {
  8178. char buffer[64 * 1024];
  8179. memset(buffer, 0x42, sizeof(buffer));
  8180. cli_.set_write_timeout(std::chrono::seconds(0));
  8181. auto res = cli_.Post(
  8182. "/slowpost", 64 * 1024 * 1024,
  8183. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8184. sink.write(buffer, sizeof(buffer));
  8185. return true;
  8186. },
  8187. "text/plain");
  8188. ASSERT_TRUE(!res);
  8189. EXPECT_EQ(Error::Write, res.error());
  8190. }
  8191. #endif
  8192. TEST_F(ServerTest, Put) {
  8193. auto res = cli_.Put("/put", "PUT", "text/plain");
  8194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8195. EXPECT_EQ(StatusCode::OK_200, res->status);
  8196. EXPECT_EQ("PUT", res->body);
  8197. }
  8198. TEST_F(ServerTest, PutWithContentProvider) {
  8199. auto res = cli_.Put(
  8200. "/put", 3,
  8201. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8202. sink.os << "PUT";
  8203. return true;
  8204. },
  8205. "text/plain");
  8206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8207. EXPECT_EQ(StatusCode::OK_200, res->status);
  8208. EXPECT_EQ("PUT", res->body);
  8209. }
  8210. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8211. auto res = cli_.Post(
  8212. "/post", 42,
  8213. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8214. return false;
  8215. },
  8216. "text/plain");
  8217. ASSERT_TRUE(!res);
  8218. EXPECT_EQ(Error::Canceled, res.error());
  8219. }
  8220. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8221. auto res = cli_.Put(
  8222. "/put",
  8223. [](size_t /*offset*/, DataSink &sink) {
  8224. sink.os << "PUT";
  8225. sink.done();
  8226. return true;
  8227. },
  8228. "text/plain");
  8229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8230. EXPECT_EQ(StatusCode::OK_200, res->status);
  8231. EXPECT_EQ("PUT", res->body);
  8232. }
  8233. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8234. auto res = cli_.Post(
  8235. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8236. "text/plain");
  8237. ASSERT_TRUE(!res);
  8238. EXPECT_EQ(Error::Canceled, res.error());
  8239. }
  8240. TEST_F(ServerTest, PostLoopBack) {
  8241. std::string body;
  8242. auto res = cli_.Post(
  8243. "/post-loopback", 9,
  8244. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8245. EXPECT_EQ(9u, length);
  8246. sink.write("123", 3);
  8247. sink.write("456", 3);
  8248. sink.write("789", 3);
  8249. return true;
  8250. },
  8251. "text/plain",
  8252. [&body](const char *data, size_t data_length) {
  8253. body.append(data, data_length);
  8254. return true;
  8255. });
  8256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8257. EXPECT_EQ(StatusCode::OK_200, res->status);
  8258. EXPECT_EQ("123456789", body);
  8259. }
  8260. TEST_F(ServerTest, PutLoopBack) {
  8261. std::string body;
  8262. auto res = cli_.Put(
  8263. "/put-loopback", 9,
  8264. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8265. EXPECT_EQ(9u, length);
  8266. sink.write("123", 3);
  8267. sink.write("456", 3);
  8268. sink.write("789", 3);
  8269. return true;
  8270. },
  8271. "text/plain",
  8272. [&body](const char *data, size_t data_length) {
  8273. body.append(data, data_length);
  8274. return true;
  8275. });
  8276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8277. EXPECT_EQ(StatusCode::OK_200, res->status);
  8278. EXPECT_EQ("123456789", body);
  8279. }
  8280. TEST_F(ServerTest, PatchLoopBack) {
  8281. std::string body;
  8282. auto res = cli_.Patch(
  8283. "/patch-loopback", 9,
  8284. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8285. EXPECT_EQ(9u, length);
  8286. sink.write("123", 3);
  8287. sink.write("456", 3);
  8288. sink.write("789", 3);
  8289. return true;
  8290. },
  8291. "text/plain",
  8292. [&body](const char *data, size_t data_length) {
  8293. body.append(data, data_length);
  8294. return true;
  8295. });
  8296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8297. EXPECT_EQ(StatusCode::OK_200, res->status);
  8298. EXPECT_EQ("123456789", body);
  8299. }
  8300. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8301. std::string body;
  8302. auto res = cli_.Post(
  8303. "/post-loopback",
  8304. [](size_t /*offset*/, DataSink &sink) {
  8305. sink.write("123", 3);
  8306. sink.write("456", 3);
  8307. sink.write("789", 3);
  8308. sink.done();
  8309. return true;
  8310. },
  8311. "text/plain",
  8312. [&body](const char *data, size_t data_length) {
  8313. body.append(data, data_length);
  8314. return true;
  8315. });
  8316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8317. EXPECT_EQ(StatusCode::OK_200, res->status);
  8318. EXPECT_EQ("123456789", body);
  8319. }
  8320. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8321. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8322. cli_.set_compress(true);
  8323. auto res = cli_.Put(
  8324. "/put", 3,
  8325. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8326. sink.os << "PUT";
  8327. return true;
  8328. },
  8329. "text/plain");
  8330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8331. EXPECT_EQ(StatusCode::OK_200, res->status);
  8332. EXPECT_EQ("PUT", res->body);
  8333. }
  8334. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8335. cli_.set_compress(true);
  8336. auto res = cli_.Post(
  8337. "/post", 42,
  8338. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8339. return false;
  8340. },
  8341. "text/plain");
  8342. ASSERT_TRUE(!res);
  8343. EXPECT_EQ(Error::Canceled, res.error());
  8344. }
  8345. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8346. cli_.set_compress(true);
  8347. auto res = cli_.Put(
  8348. "/put",
  8349. [](size_t /*offset*/, DataSink &sink) {
  8350. sink.os << "PUT";
  8351. sink.done();
  8352. return true;
  8353. },
  8354. "text/plain");
  8355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8356. EXPECT_EQ(StatusCode::OK_200, res->status);
  8357. EXPECT_EQ("PUT", res->body);
  8358. }
  8359. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8360. cli_.set_compress(true);
  8361. auto res = cli_.Post(
  8362. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8363. "text/plain");
  8364. ASSERT_TRUE(!res);
  8365. EXPECT_EQ(Error::Canceled, res.error());
  8366. }
  8367. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8368. cli_.set_compress(true);
  8369. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8371. EXPECT_EQ(StatusCode::OK_200, res->status);
  8372. EXPECT_EQ(LARGE_DATA, res->body);
  8373. }
  8374. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8375. #ifdef CPPHTTPLIB_SSL_ENABLED
  8376. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8377. Client cli(s.c_str());
  8378. cli.enable_server_certificate_verification(false);
  8379. #else
  8380. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8381. Client cli(s.c_str());
  8382. #endif
  8383. cli.set_compress(true);
  8384. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8386. EXPECT_EQ(StatusCode::OK_200, res->status);
  8387. EXPECT_EQ(LARGE_DATA, res->body);
  8388. // The compressed size should be less than a 10th of the original. May vary
  8389. // depending on the zlib library.
  8390. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8391. static_cast<uint64_t>(10 * 1024 * 1024));
  8392. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8393. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8394. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8395. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8396. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8397. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8398. #endif
  8399. }
  8400. TEST_F(ServerTest, PutContentWithDeflate) {
  8401. cli_.set_compress(false);
  8402. Headers headers;
  8403. headers.emplace("Content-Encoding", "deflate");
  8404. // PUT in deflate format:
  8405. auto res = cli_.Put("/put", headers,
  8406. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8408. EXPECT_EQ(StatusCode::OK_200, res->status);
  8409. EXPECT_EQ("PUT", res->body);
  8410. }
  8411. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8412. Headers headers;
  8413. headers.emplace("Accept-Encoding", "gzip, deflate");
  8414. auto res = cli_.Get("/streamed-chunked", headers);
  8415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8416. EXPECT_EQ(StatusCode::OK_200, res->status);
  8417. EXPECT_EQ(std::string("123456789"), res->body);
  8418. }
  8419. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8420. Headers headers;
  8421. headers.emplace("Accept-Encoding", "gzip, deflate");
  8422. auto res = cli_.Get("/streamed-chunked2", headers);
  8423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8424. EXPECT_EQ(StatusCode::OK_200, res->status);
  8425. EXPECT_EQ(std::string("123456789"), res->body);
  8426. }
  8427. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8428. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8430. EXPECT_EQ(StatusCode::OK_200, res->status);
  8431. }
  8432. TEST(GzipDecompressor, ChunkedDecompression) {
  8433. std::string data;
  8434. for (size_t i = 0; i < 32 * 1024; ++i) {
  8435. data.push_back(static_cast<char>('a' + i % 26));
  8436. }
  8437. std::string compressed_data;
  8438. {
  8439. httplib::detail::gzip_compressor compressor;
  8440. bool result = compressor.compress(
  8441. data.data(), data.size(),
  8442. /*last=*/true,
  8443. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8444. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8445. compressed_data_size);
  8446. return true;
  8447. });
  8448. ASSERT_TRUE(result);
  8449. }
  8450. std::string decompressed_data;
  8451. {
  8452. httplib::detail::gzip_decompressor decompressor;
  8453. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8454. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8455. size_t chunk_size = 130;
  8456. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8457. chunk_begin += chunk_size) {
  8458. size_t current_chunk_size =
  8459. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8460. bool result = decompressor.decompress(
  8461. compressed_data.data() + chunk_begin, current_chunk_size,
  8462. [&](const char *decompressed_data_chunk,
  8463. size_t decompressed_data_chunk_size) {
  8464. decompressed_data.insert(decompressed_data.size(),
  8465. decompressed_data_chunk,
  8466. decompressed_data_chunk_size);
  8467. return true;
  8468. });
  8469. ASSERT_TRUE(result);
  8470. }
  8471. }
  8472. ASSERT_EQ(data, decompressed_data);
  8473. }
  8474. TEST(GzipDecompressor, DeflateDecompression) {
  8475. std::string original_text = "Raw deflate without gzip";
  8476. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8477. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8478. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8479. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8480. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8481. std::string decompressed_data;
  8482. {
  8483. httplib::detail::gzip_decompressor decompressor;
  8484. bool result = decompressor.decompress(
  8485. compressed_data.data(), compressed_data.size(),
  8486. [&](const char *decompressed_data_chunk,
  8487. size_t decompressed_data_chunk_size) {
  8488. decompressed_data.insert(decompressed_data.size(),
  8489. decompressed_data_chunk,
  8490. decompressed_data_chunk_size);
  8491. return true;
  8492. });
  8493. ASSERT_TRUE(result);
  8494. }
  8495. ASSERT_EQ(original_text, decompressed_data);
  8496. }
  8497. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8498. std::string original_text = "Raw deflate without gzip";
  8499. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8500. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8501. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8502. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8503. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8504. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8505. std::string decompressed_data;
  8506. {
  8507. httplib::detail::gzip_decompressor decompressor;
  8508. bool result = decompressor.decompress(
  8509. compressed_data.data(), compressed_data.size(),
  8510. [&](const char *decompressed_data_chunk,
  8511. size_t decompressed_data_chunk_size) {
  8512. decompressed_data.insert(decompressed_data.size(),
  8513. decompressed_data_chunk,
  8514. decompressed_data_chunk_size);
  8515. return true;
  8516. });
  8517. ASSERT_TRUE(result);
  8518. }
  8519. ASSERT_EQ(original_text, decompressed_data);
  8520. }
  8521. TEST(GzipDecompressor, MultipleMembers) {
  8522. auto gzip = [](const std::string &data) {
  8523. std::string out;
  8524. httplib::detail::gzip_compressor compressor;
  8525. compressor.compress(data.data(), data.size(), /*last=*/true,
  8526. [&](const char *chunk, size_t n) {
  8527. out.append(chunk, n);
  8528. return true;
  8529. });
  8530. return out;
  8531. };
  8532. // Decompresses `data` handed over in two calls, the first `split` bytes long
  8533. auto decompress = [](const std::string &data, size_t split,
  8534. std::string &out) {
  8535. httplib::detail::gzip_decompressor decompressor;
  8536. auto callback = [&](const char *chunk, size_t n) {
  8537. out.append(chunk, n);
  8538. return true;
  8539. };
  8540. return decompressor.decompress(data.data(), split, callback) &&
  8541. decompressor.decompress(data.data() + split, data.size() - split,
  8542. callback);
  8543. };
  8544. // RFC 1952 2.2: a gzip body is a series of members, an empty one included.
  8545. // Bytes after the last member that start no other one are still ignored.
  8546. const auto members = gzip("Hello, ") + gzip("") + gzip("World!");
  8547. for (const auto &body : {members, members + std::string(8, '\0')}) {
  8548. for (size_t split = 0; split <= body.size(); split++) {
  8549. std::string out;
  8550. ASSERT_TRUE(decompress(body, split, out)) << "split at " << split;
  8551. EXPECT_EQ("Hello, World!", out) << "split at " << split;
  8552. }
  8553. }
  8554. // A broken later member fails like a broken first one
  8555. auto broken = gzip("Hello, ") + gzip("World!");
  8556. auto crc_pos = broken.size() - 8;
  8557. broken[crc_pos] = static_cast<char>(broken[crc_pos] ^ 0x01);
  8558. std::string out;
  8559. EXPECT_FALSE(decompress(broken, broken.size(), out));
  8560. }
  8561. #endif
  8562. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8563. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8564. Headers headers;
  8565. headers.emplace("Accept-Encoding", "br");
  8566. auto res = cli_.Get("/streamed-chunked", headers);
  8567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8568. EXPECT_EQ(StatusCode::OK_200, res->status);
  8569. EXPECT_EQ(std::string("123456789"), res->body);
  8570. }
  8571. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8572. Headers headers;
  8573. headers.emplace("Accept-Encoding", "br");
  8574. auto res = cli_.Get("/streamed-chunked2", headers);
  8575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8576. EXPECT_EQ(StatusCode::OK_200, res->status);
  8577. EXPECT_EQ(std::string("123456789"), res->body);
  8578. }
  8579. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8580. cli_.set_compress(true);
  8581. auto res = cli_.Put(
  8582. "/put", 3,
  8583. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8584. sink.os << "PUT";
  8585. return true;
  8586. },
  8587. "text/plain");
  8588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8589. EXPECT_EQ(StatusCode::OK_200, res->status);
  8590. EXPECT_EQ("PUT", res->body);
  8591. }
  8592. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8593. cli_.set_compress(true);
  8594. auto res = cli_.Put(
  8595. "/put",
  8596. [](size_t /*offset*/, DataSink &sink) {
  8597. sink.os << "PUT";
  8598. sink.done();
  8599. return true;
  8600. },
  8601. "text/plain");
  8602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8603. EXPECT_EQ(StatusCode::OK_200, res->status);
  8604. EXPECT_EQ("PUT", res->body);
  8605. }
  8606. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8607. cli_.set_compress(true);
  8608. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8610. EXPECT_EQ(StatusCode::OK_200, res->status);
  8611. EXPECT_EQ(LARGE_DATA, res->body);
  8612. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8613. }
  8614. #endif
  8615. TEST_F(ServerTest, Patch) {
  8616. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8618. EXPECT_EQ(StatusCode::OK_200, res->status);
  8619. EXPECT_EQ("PATCH", res->body);
  8620. }
  8621. TEST_F(ServerTest, Delete) {
  8622. auto res = cli_.Delete("/delete");
  8623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8624. EXPECT_EQ(StatusCode::OK_200, res->status);
  8625. EXPECT_EQ("DELETE", res->body);
  8626. }
  8627. TEST_F(ServerTest, DeleteContentReceiver) {
  8628. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8630. EXPECT_EQ(StatusCode::OK_200, res->status);
  8631. EXPECT_EQ("content", res->body);
  8632. }
  8633. TEST_F(ServerTest, Options) {
  8634. auto res = cli_.Options("*");
  8635. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8636. EXPECT_EQ(StatusCode::OK_200, res->status);
  8637. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8638. EXPECT_TRUE(res->body.empty());
  8639. }
  8640. TEST_F(ServerTest, URL) {
  8641. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8643. EXPECT_EQ(StatusCode::OK_200, res->status);
  8644. }
  8645. TEST_F(ServerTest, ArrayParam) {
  8646. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8648. EXPECT_EQ(StatusCode::OK_200, res->status);
  8649. }
  8650. TEST_F(ServerTest, ArrayParamValues) {
  8651. auto res =
  8652. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8654. EXPECT_EQ(StatusCode::OK_200, res->status);
  8655. }
  8656. TEST_F(ServerTest, NoMultipleHeaders) {
  8657. Headers headers = {{"Content-Length", "5"}};
  8658. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8659. "text/plain");
  8660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8661. EXPECT_EQ(StatusCode::OK_200, res->status);
  8662. }
  8663. TEST_F(ServerTest, PostContentReceiver) {
  8664. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8666. ASSERT_EQ(StatusCode::OK_200, res->status);
  8667. ASSERT_EQ("content", res->body);
  8668. }
  8669. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8670. UploadFormDataItems items = {
  8671. {"text1", "text default", "", ""},
  8672. {"text2", "aωb", "", ""},
  8673. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8674. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8675. {"file3", "", "", "application/octet-stream"},
  8676. };
  8677. auto res = cli_.Post("/content_receiver", items);
  8678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8679. EXPECT_EQ(StatusCode::OK_200, res->status);
  8680. }
  8681. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8682. UploadFormDataItems items = {
  8683. {"text1", "text default", "", ""},
  8684. {"text2", "aωb", "", ""},
  8685. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8686. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8687. {"file3", "", "", "application/octet-stream"},
  8688. };
  8689. auto boundary = std::string("+++++");
  8690. std::string body;
  8691. for (const auto &item : items) {
  8692. body += "--" + boundary + "\r\n";
  8693. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8694. if (!item.filename.empty()) {
  8695. body += "; filename=\"" + item.filename + "\"";
  8696. }
  8697. body += "\r\n";
  8698. if (!item.content_type.empty()) {
  8699. body += "Content-Type: " + item.content_type + "\r\n";
  8700. }
  8701. body += "\r\n";
  8702. body += item.content + "\r\n";
  8703. }
  8704. body += "--" + boundary + "--\r\n";
  8705. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8706. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8708. EXPECT_EQ(StatusCode::OK_200, res->status);
  8709. }
  8710. TEST(MultipartFormDataTest, FieldEscaping) {
  8711. Server svr;
  8712. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8713. const ContentReader &content_reader) {
  8714. ASSERT_TRUE(req.is_multipart_form_data());
  8715. std::vector<FormData> received;
  8716. content_reader(
  8717. [&](const FormData &file) {
  8718. received.push_back(file);
  8719. return true;
  8720. },
  8721. [&](const char *data, size_t data_length) {
  8722. received.back().content.append(data, data_length);
  8723. return true;
  8724. });
  8725. // '"', CR and LF in names and filenames are escaped following the
  8726. // WHATWG HTML standard, so each part still parses as a single part
  8727. // with no injected headers. Content types get CR/LF escaped too,
  8728. // while '"' (legal there, e.g. quoted charset) is preserved.
  8729. ASSERT_EQ(4U, received.size());
  8730. EXPECT_EQ("na%22me", received[0].name);
  8731. EXPECT_EQ("quoted name", received[0].content);
  8732. EXPECT_EQ("file", received[1].name);
  8733. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8734. received[1].filename);
  8735. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8736. EXPECT_EQ("injected", received[1].content);
  8737. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8738. EXPECT_EQ("my%22file.txt", received[2].filename);
  8739. EXPECT_EQ("cr lf name", received[2].content);
  8740. EXPECT_EQ("typed", received[3].name);
  8741. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8742. received[3].content_type);
  8743. EXPECT_EQ("typed content", received[3].content);
  8744. });
  8745. auto port = svr.bind_to_any_port("localhost");
  8746. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8747. auto se = detail::scope_exit([&] {
  8748. svr.stop();
  8749. t.join();
  8750. ASSERT_FALSE(svr.is_running());
  8751. });
  8752. svr.wait_until_ready();
  8753. Client cli("localhost", port);
  8754. UploadFormDataItems items = {
  8755. {"na\"me", "quoted name", "", ""},
  8756. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8757. "application/octet-stream"},
  8758. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8759. {"typed", "typed content", "",
  8760. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8761. };
  8762. auto res = cli.Post("/post", items);
  8763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8764. EXPECT_EQ(StatusCode::OK_200, res->status);
  8765. }
  8766. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8767. const UploadFormDataItems items = {
  8768. {"name1", "Content 1", "", ""},
  8769. {"name2", "Content 2", "file2.txt", "text/plain"},
  8770. };
  8771. Server svr;
  8772. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8773. const ContentReader &content_reader) {
  8774. ASSERT_TRUE(req.is_multipart_form_data());
  8775. std::vector<FormData> received;
  8776. content_reader(
  8777. [&](const FormData &file) {
  8778. received.push_back(file);
  8779. return true;
  8780. },
  8781. [&](const char *data, size_t data_length) {
  8782. received.back().content.append(data, data_length);
  8783. return true;
  8784. });
  8785. ASSERT_EQ(2U, received.size());
  8786. EXPECT_EQ("name1", received[0].name);
  8787. EXPECT_EQ("Content 1", received[0].content);
  8788. EXPECT_EQ("name2", received[1].name);
  8789. EXPECT_EQ("Content 2", received[1].content);
  8790. EXPECT_EQ("file2.txt", received[1].filename);
  8791. EXPECT_EQ("text/plain", received[1].content_type);
  8792. });
  8793. auto port = svr.bind_to_any_port("localhost");
  8794. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8795. auto se = detail::scope_exit([&] {
  8796. svr.stop();
  8797. t.join();
  8798. ASSERT_FALSE(svr.is_running());
  8799. });
  8800. svr.wait_until_ready();
  8801. Client cli("localhost", port);
  8802. // Whole-body serialization with a generated boundary
  8803. {
  8804. MultipartFormDataWriter writer;
  8805. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8806. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8807. writer.content_type());
  8808. auto body = writer.serialize(items);
  8809. EXPECT_EQ(body.size(), writer.content_length(items));
  8810. auto res = cli.Post("/post", body, writer.content_type());
  8811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8812. EXPECT_EQ(StatusCode::OK_200, res->status);
  8813. }
  8814. // Per-part framing with a custom boundary via a content provider
  8815. {
  8816. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8817. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8818. MultipartFormDataWriter writer("custom-boundary_123");
  8819. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8820. std::string body;
  8821. for (const auto &item : items) {
  8822. body += writer.item_begin(item);
  8823. body += item.content;
  8824. body += MultipartFormDataWriter::item_end();
  8825. }
  8826. body += writer.finish();
  8827. EXPECT_EQ(body.size(), writer.content_length(items));
  8828. auto res = cli.Post(
  8829. "/post", body.size(),
  8830. [&](size_t offset, size_t length, DataSink &sink) {
  8831. sink.write(body.data() + offset, length);
  8832. return true;
  8833. },
  8834. writer.content_type());
  8835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8836. EXPECT_EQ(StatusCode::OK_200, res->status);
  8837. }
  8838. }
  8839. TEST_F(ServerTest, PostContentReceiverGzip) {
  8840. cli_.set_compress(true);
  8841. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8843. ASSERT_EQ(StatusCode::OK_200, res->status);
  8844. ASSERT_EQ("content", res->body);
  8845. }
  8846. TEST_F(ServerTest, PutContentReceiver) {
  8847. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8849. ASSERT_EQ(StatusCode::OK_200, res->status);
  8850. ASSERT_EQ("content", res->body);
  8851. }
  8852. TEST_F(ServerTest, PatchContentReceiver) {
  8853. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8855. ASSERT_EQ(StatusCode::OK_200, res->status);
  8856. ASSERT_EQ("content", res->body);
  8857. }
  8858. template <typename ClientType>
  8859. void TestWithHeadersAndContentReceiver(
  8860. ClientType &cli,
  8861. std::function<Result(ClientType &, const std::string &, const Headers &,
  8862. const std::string &, const std::string &,
  8863. ContentReceiver, DownloadProgress)>
  8864. request_func) {
  8865. Headers headers;
  8866. headers.emplace("X-Custom-Header", "test-value");
  8867. std::string received_body;
  8868. auto res = request_func(
  8869. cli, "/content_receiver", headers, "content", "application/json",
  8870. [&](const char *data, size_t data_length) {
  8871. received_body.append(data, data_length);
  8872. return true;
  8873. },
  8874. nullptr);
  8875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8876. EXPECT_EQ(StatusCode::OK_200, res->status);
  8877. EXPECT_EQ("content", received_body);
  8878. }
  8879. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8880. #ifdef CPPHTTPLIB_SSL_ENABLED
  8881. using ClientT = SSLClient;
  8882. #else
  8883. using ClientT = Client;
  8884. #endif
  8885. TestWithHeadersAndContentReceiver<ClientT>(
  8886. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8887. const std::string &body, const std::string &content_type,
  8888. ContentReceiver receiver, DownloadProgress progress) {
  8889. return cli.Post(path, headers, body, content_type, receiver, progress);
  8890. });
  8891. }
  8892. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8893. #ifdef CPPHTTPLIB_SSL_ENABLED
  8894. using ClientT = SSLClient;
  8895. #else
  8896. using ClientT = Client;
  8897. #endif
  8898. TestWithHeadersAndContentReceiver<ClientT>(
  8899. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8900. const std::string &body, const std::string &content_type,
  8901. ContentReceiver receiver, DownloadProgress progress) {
  8902. return cli.Put(path, headers, body, content_type, receiver, progress);
  8903. });
  8904. }
  8905. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8906. #ifdef CPPHTTPLIB_SSL_ENABLED
  8907. using ClientT = SSLClient;
  8908. #else
  8909. using ClientT = Client;
  8910. #endif
  8911. TestWithHeadersAndContentReceiver<ClientT>(
  8912. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8913. const std::string &body, const std::string &content_type,
  8914. ContentReceiver receiver, DownloadProgress progress) {
  8915. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8916. });
  8917. }
  8918. template <typename ClientType>
  8919. void TestWithHeadersAndContentReceiverWithProgress(
  8920. ClientType &cli,
  8921. std::function<Result(ClientType &, const std::string &, const Headers &,
  8922. const std::string &, const std::string &,
  8923. ContentReceiver, DownloadProgress)>
  8924. request_func) {
  8925. Headers headers;
  8926. headers.emplace("X-Test-Header", "progress-test");
  8927. std::string received_body;
  8928. auto progress_called = false;
  8929. auto res = request_func(
  8930. cli, "/content_receiver", headers, "content", "text/plain",
  8931. [&](const char *data, size_t data_length) {
  8932. received_body.append(data, data_length);
  8933. return true;
  8934. },
  8935. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8936. progress_called = true;
  8937. return true;
  8938. });
  8939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8940. EXPECT_EQ(StatusCode::OK_200, res->status);
  8941. EXPECT_EQ("content", received_body);
  8942. EXPECT_TRUE(progress_called);
  8943. }
  8944. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8945. #ifdef CPPHTTPLIB_SSL_ENABLED
  8946. using ClientT = SSLClient;
  8947. #else
  8948. using ClientT = Client;
  8949. #endif
  8950. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8951. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8952. const std::string &body, const std::string &content_type,
  8953. ContentReceiver receiver, DownloadProgress progress) {
  8954. return cli.Post(path, headers, body, content_type, receiver, progress);
  8955. });
  8956. }
  8957. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8958. #ifdef CPPHTTPLIB_SSL_ENABLED
  8959. using ClientT = SSLClient;
  8960. #else
  8961. using ClientT = Client;
  8962. #endif
  8963. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8964. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8965. const std::string &body, const std::string &content_type,
  8966. ContentReceiver receiver, DownloadProgress progress) {
  8967. return cli.Put(path, headers, body, content_type, receiver, progress);
  8968. });
  8969. }
  8970. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8971. #ifdef CPPHTTPLIB_SSL_ENABLED
  8972. using ClientT = SSLClient;
  8973. #else
  8974. using ClientT = Client;
  8975. #endif
  8976. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8977. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8978. const std::string &body, const std::string &content_type,
  8979. ContentReceiver receiver, DownloadProgress progress) {
  8980. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8981. });
  8982. }
  8983. template <typename ClientType>
  8984. void TestWithHeadersAndContentReceiverError(
  8985. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8986. const Headers &, const std::string &,
  8987. const std::string &, ContentReceiver)>
  8988. request_func) {
  8989. Headers headers;
  8990. headers.emplace("X-Error-Test", "true");
  8991. std::string received_body;
  8992. auto receiver_failed = false;
  8993. auto res =
  8994. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8995. [&](const char *data, size_t data_length) {
  8996. received_body.append(data, data_length);
  8997. receiver_failed = true;
  8998. return false;
  8999. });
  9000. ASSERT_FALSE(res);
  9001. EXPECT_TRUE(receiver_failed);
  9002. }
  9003. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  9004. #ifdef CPPHTTPLIB_SSL_ENABLED
  9005. using ClientT = SSLClient;
  9006. #else
  9007. using ClientT = Client;
  9008. #endif
  9009. TestWithHeadersAndContentReceiverError<ClientT>(
  9010. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  9011. const std::string &body, const std::string &content_type,
  9012. ContentReceiver receiver) {
  9013. return cli.Post(path, headers, body, content_type, receiver);
  9014. });
  9015. }
  9016. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  9017. #ifdef CPPHTTPLIB_SSL_ENABLED
  9018. using ClientT = SSLClient;
  9019. #else
  9020. using ClientT = Client;
  9021. #endif
  9022. TestWithHeadersAndContentReceiverError<ClientT>(
  9023. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  9024. const std::string &body, const std::string &content_type,
  9025. ContentReceiver receiver) {
  9026. return cli.Put(path, headers, body, content_type, receiver);
  9027. });
  9028. }
  9029. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  9030. #ifdef CPPHTTPLIB_SSL_ENABLED
  9031. using ClientT = SSLClient;
  9032. #else
  9033. using ClientT = Client;
  9034. #endif
  9035. TestWithHeadersAndContentReceiverError<ClientT>(
  9036. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  9037. const std::string &body, const std::string &content_type,
  9038. ContentReceiver receiver) {
  9039. return cli.Patch(path, headers, body, content_type, receiver);
  9040. });
  9041. }
  9042. TEST_F(ServerTest, PostQueryStringAndBody) {
  9043. auto res =
  9044. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  9045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9046. ASSERT_EQ(StatusCode::OK_200, res->status);
  9047. }
  9048. TEST_F(ServerTest, HTTP2Magic) {
  9049. Request req;
  9050. req.method = "PRI";
  9051. req.path = "*";
  9052. req.body = "SM";
  9053. auto res = std::make_shared<Response>();
  9054. auto error = Error::Success;
  9055. auto ret = cli_.send(req, *res, error);
  9056. ASSERT_TRUE(ret);
  9057. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9058. }
  9059. TEST_F(ServerTest, KeepAlive) {
  9060. auto res = cli_.Get("/hi");
  9061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9062. EXPECT_EQ(StatusCode::OK_200, res->status);
  9063. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9064. EXPECT_EQ("Hello World!", res->body);
  9065. res = cli_.Get("/hi");
  9066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9067. EXPECT_EQ(StatusCode::OK_200, res->status);
  9068. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9069. EXPECT_EQ("Hello World!", res->body);
  9070. res = cli_.Get("/hi");
  9071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9072. EXPECT_EQ(StatusCode::OK_200, res->status);
  9073. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9074. EXPECT_EQ("Hello World!", res->body);
  9075. res = cli_.Get("/not-exist");
  9076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9077. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9078. res = cli_.Post("/empty", "", "text/plain");
  9079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9080. EXPECT_EQ(StatusCode::OK_200, res->status);
  9081. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9082. EXPECT_EQ("empty", res->body);
  9083. EXPECT_EQ("close", res->get_header_value("Connection"));
  9084. res = cli_.Post(
  9085. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  9086. "text/plain");
  9087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9088. EXPECT_EQ(StatusCode::OK_200, res->status);
  9089. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9090. EXPECT_EQ("empty", res->body);
  9091. cli_.set_keep_alive(false);
  9092. res = cli_.Get("/last-request");
  9093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9094. EXPECT_EQ(StatusCode::OK_200, res->status);
  9095. EXPECT_EQ("close", res->get_header_value("Connection"));
  9096. }
  9097. TEST_F(ServerTest, TooManyRedirect) {
  9098. cli_.set_follow_location(true);
  9099. auto res = cli_.Get("/redirect/0");
  9100. ASSERT_TRUE(!res);
  9101. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  9102. }
  9103. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  9104. Request req;
  9105. req.method = "FOOBAR";
  9106. req.path = "/hi";
  9107. cli_.set_keep_alive(true);
  9108. auto res = cli_.send(req);
  9109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9110. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9111. EXPECT_EQ("close", res->get_header_value("Connection"));
  9112. EXPECT_FALSE(cli_.is_socket_open());
  9113. }
  9114. TEST_F(ServerTest, CustomRouteReadsBody) {
  9115. const std::string xml =
  9116. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  9117. Request req;
  9118. req.method = "PROPFIND";
  9119. req.path = "/dav/dir";
  9120. req.set_header("Depth", "1");
  9121. req.body = xml;
  9122. auto res = cli_.send(req);
  9123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9124. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9125. EXPECT_EQ(xml, res->body);
  9126. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  9127. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  9128. }
  9129. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  9130. Request req;
  9131. req.method = "PROPFIND";
  9132. req.path = "/dav/42";
  9133. auto res = cli_.send(req);
  9134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9135. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9136. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  9137. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  9138. }
  9139. TEST_F(ServerTest, CustomRouteRegexPattern) {
  9140. Request req;
  9141. req.method = "PROPFIND";
  9142. req.path = "/dav-re/123";
  9143. auto res = cli_.send(req);
  9144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9145. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9146. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  9147. }
  9148. TEST_F(ServerTest, CustomRouteWithoutBody) {
  9149. Request req;
  9150. req.method = "MKCOL";
  9151. req.path = "/dav-mkcol";
  9152. auto res = cli_.send(req);
  9153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9154. EXPECT_EQ(StatusCode::Created_201, res->status);
  9155. }
  9156. TEST_F(ServerTest, CustomRouteWithContentReader) {
  9157. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  9158. Request req;
  9159. req.method = "REPORT";
  9160. req.path = "/dav-report";
  9161. req.body = xml;
  9162. auto res = cli_.send(req);
  9163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9164. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9165. EXPECT_EQ(xml, res->body);
  9166. }
  9167. // A content reader route must fire even when the request carries no body,
  9168. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  9169. // Without that, a body-less PROPFIND-style request would fall through to 404.
  9170. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  9171. Request req;
  9172. req.method = "REPORT";
  9173. req.path = "/dav-report";
  9174. auto res = cli_.send(req);
  9175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9176. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9177. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  9178. }
  9179. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  9180. Request req;
  9181. req.method = "PROPFIND";
  9182. req.path = "/not-dav";
  9183. auto res = cli_.send(req);
  9184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9185. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9186. }
  9187. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  9188. Request req;
  9189. req.method = "UNLOCK";
  9190. req.path = "/dav/dir";
  9191. cli_.set_keep_alive(true);
  9192. auto res = cli_.send(req);
  9193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9194. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9195. EXPECT_EQ("close", res->get_header_value("Connection"));
  9196. EXPECT_FALSE(cli_.is_socket_open());
  9197. }
  9198. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  9199. // The mount point serves this path, but only for GET and HEAD.
  9200. auto get_res = cli_.Get("/dir/index.html");
  9201. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  9202. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  9203. Request req;
  9204. req.method = "PROPFIND";
  9205. req.path = "/dir/index.html";
  9206. auto res = cli_.send(req);
  9207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9208. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9209. }
  9210. TEST_F(ServerTest, CustomRouteKeepAlive) {
  9211. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9212. cli_.set_keep_alive(true);
  9213. for (auto i = 0; i < 2; i++) {
  9214. Request req;
  9215. req.method = "PROPFIND";
  9216. req.path = "/dav/dir";
  9217. req.body = xml;
  9218. auto res = cli_.send(req);
  9219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9220. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9221. EXPECT_EQ(xml, res->body);
  9222. EXPECT_TRUE(cli_.is_socket_open());
  9223. }
  9224. // A built-in method must still be served on the same connection.
  9225. cli_.set_keep_alive(false);
  9226. auto res = cli_.Get("/hi");
  9227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9228. EXPECT_EQ(StatusCode::OK_200, res->status);
  9229. EXPECT_EQ("close", res->get_header_value("Connection"));
  9230. }
  9231. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  9232. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9233. Request req;
  9234. req.method = "PROPFIND";
  9235. req.path = "/dav/dir";
  9236. req.set_header("Expect", "100-continue");
  9237. req.body = xml;
  9238. auto res = cli_.send(req);
  9239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9240. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9241. EXPECT_EQ(xml, res->body);
  9242. }
  9243. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9244. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9245. TEST_F(ServerTest, Gzip) {
  9246. Headers headers;
  9247. headers.emplace("Accept-Encoding", "gzip, deflate");
  9248. auto res = cli_.Get("/compress", headers);
  9249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9250. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9251. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9252. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9253. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9254. "7890123456789012345678901234567890",
  9255. res->body);
  9256. EXPECT_EQ(StatusCode::OK_200, res->status);
  9257. }
  9258. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9259. Headers headers;
  9260. headers.emplace("Accept-Encoding", "gzip, deflate");
  9261. auto res = cli_.Get("/compress-with-charset", headers);
  9262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9263. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9264. EXPECT_EQ("application/json; charset=utf-8",
  9265. res->get_header_value("Content-Type"));
  9266. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9267. "7890123456789012345678901234567890",
  9268. res->body);
  9269. EXPECT_EQ(StatusCode::OK_200, res->status);
  9270. }
  9271. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9272. Headers headers;
  9273. headers.emplace("Accept-Encoding", "");
  9274. auto res = cli_.Get("/compress", headers);
  9275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9276. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9277. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9278. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9279. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9280. "7890123456789012345678901234567890",
  9281. res->body);
  9282. EXPECT_EQ(StatusCode::OK_200, res->status);
  9283. }
  9284. TEST_F(ServerTest, GzipWithContentReceiver) {
  9285. Headers headers;
  9286. headers.emplace("Accept-Encoding", "gzip, deflate");
  9287. std::string body;
  9288. auto res =
  9289. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9290. EXPECT_EQ(100U, data_length);
  9291. body.append(data, data_length);
  9292. return true;
  9293. });
  9294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9295. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9296. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9297. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9298. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9299. "7890123456789012345678901234567890",
  9300. body);
  9301. EXPECT_EQ(StatusCode::OK_200, res->status);
  9302. }
  9303. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9304. Headers headers;
  9305. headers.emplace("Accept-Encoding", "gzip, deflate");
  9306. cli_.set_decompress(false);
  9307. auto res = cli_.Get("/compress", headers);
  9308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9309. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9310. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9311. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9312. EXPECT_EQ(33U, res->body.size());
  9313. EXPECT_EQ(StatusCode::OK_200, res->status);
  9314. }
  9315. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9316. Headers headers;
  9317. headers.emplace("Accept-Encoding", "");
  9318. std::string body;
  9319. auto res =
  9320. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9321. EXPECT_EQ(100U, data_length);
  9322. body.append(data, data_length);
  9323. return true;
  9324. });
  9325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9326. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9327. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9328. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9329. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9330. "7890123456789012345678901234567890",
  9331. body);
  9332. EXPECT_EQ(StatusCode::OK_200, res->status);
  9333. }
  9334. TEST_F(ServerTest, NoGzip) {
  9335. Headers headers;
  9336. headers.emplace("Accept-Encoding", "gzip, deflate");
  9337. auto res = cli_.Get("/nocompress", headers);
  9338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9339. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9340. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9341. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9342. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9343. "7890123456789012345678901234567890",
  9344. res->body);
  9345. EXPECT_EQ(StatusCode::OK_200, res->status);
  9346. }
  9347. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9348. Headers headers;
  9349. headers.emplace("Accept-Encoding", "gzip, deflate");
  9350. std::string body;
  9351. auto res = cli_.Get("/nocompress", headers,
  9352. [&](const char *data, size_t data_length) {
  9353. EXPECT_EQ(100U, data_length);
  9354. body.append(data, data_length);
  9355. return true;
  9356. });
  9357. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9358. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9359. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9360. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9361. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9362. "7890123456789012345678901234567890",
  9363. body);
  9364. EXPECT_EQ(StatusCode::OK_200, res->status);
  9365. }
  9366. TEST_F(ServerTest, MultipartFormDataGzip) {
  9367. UploadFormDataItems items = {
  9368. {"key1", "test", "", ""},
  9369. {"key2", "--abcdefg123", "", ""},
  9370. };
  9371. cli_.set_compress(true);
  9372. auto res = cli_.Post("/compress-multipart", items);
  9373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9374. EXPECT_EQ(StatusCode::OK_200, res->status);
  9375. }
  9376. #endif
  9377. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9378. // Static file compression is opt-in, so these run their own server rather than
  9379. // flipping it on for the shared ServerTest fixture, which would silently
  9380. // rewrite what every other static file test is asserting.
  9381. class StaticFileCompressionTest : public ::testing::Test {
  9382. protected:
  9383. void TearDown() override {
  9384. if (t_.joinable()) {
  9385. svr_.stop();
  9386. t_.join();
  9387. }
  9388. }
  9389. int start(const std::function<void(Server &)> &configure = nullptr) {
  9390. // Serves the same tree as a directory of build-time compressed assets
  9391. // would be served: the mount point names the coding the files are already
  9392. // stored in. Registered before "/" so it is the one that matches.
  9393. svr_.set_mount_point("/pre-encoded", "./www",
  9394. {{"Content-Encoding", "gzip"}});
  9395. svr_.set_mount_point("/", "./www");
  9396. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9397. res.set_file_content("./www/dir/index.html", "text/html");
  9398. });
  9399. svr_.Get("/pre-encoded-file-content",
  9400. [](const Request & /*req*/, Response &res) {
  9401. res.set_header("Content-Encoding", "gzip");
  9402. res.set_file_content("./www/dir/index.html", "text/html");
  9403. });
  9404. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9405. res.set_content_provider(
  9406. 6, "text/plain",
  9407. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9408. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9409. return true;
  9410. });
  9411. });
  9412. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9413. res.set_content_provider(
  9414. 1000, "text/plain",
  9415. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9416. if (offset < 100) {
  9417. std::string data(100, 'A');
  9418. sink.write(data.data(), data.size());
  9419. return true;
  9420. }
  9421. std::this_thread::sleep_for(std::chrono::seconds(2));
  9422. std::string data(900, 'B');
  9423. sink.write(data.data(), data.size());
  9424. return true;
  9425. });
  9426. });
  9427. if (configure) { configure(svr_); }
  9428. auto port = svr_.bind_to_any_port(HOST);
  9429. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9430. svr_.wait_until_ready();
  9431. return port;
  9432. }
  9433. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9434. // Every file under ./www except 1MB.txt is smaller than the default
  9435. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9436. // it out of the way.
  9437. static void enable_without_floor(Server &svr) {
  9438. svr.set_static_file_compression(true);
  9439. svr.set_static_file_compression_min_length(0);
  9440. }
  9441. Server svr_;
  9442. std::thread t_;
  9443. };
  9444. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9445. auto port = start();
  9446. Client cli(HOST, port);
  9447. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9449. EXPECT_EQ(StatusCode::OK_200, res->status);
  9450. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9451. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9452. EXPECT_EQ(1048576U, res->body.size());
  9453. }
  9454. TEST_F(StaticFileCompressionTest, MountPoint) {
  9455. auto port = start(enable);
  9456. Client cli(HOST, port);
  9457. cli.set_decompress(false);
  9458. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9460. EXPECT_EQ(StatusCode::OK_200, res->status);
  9461. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9462. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9463. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9464. // The response stays self-delimiting: a length, not a chunked body.
  9465. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9466. EXPECT_EQ(std::to_string(res->body.size()),
  9467. res->get_header_value("Content-Length"));
  9468. EXPECT_LT(res->body.size(), 1048576U);
  9469. EXPECT_FALSE(res->body.empty());
  9470. }
  9471. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9472. auto port = start(enable);
  9473. Client cli(HOST, port);
  9474. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9476. EXPECT_EQ(StatusCode::OK_200, res->status);
  9477. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9478. EXPECT_EQ(1048576U, res->body.size());
  9479. }
  9480. TEST_F(StaticFileCompressionTest, FileContent) {
  9481. auto port = start(enable_without_floor);
  9482. Client cli(HOST, port);
  9483. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9485. EXPECT_EQ(StatusCode::OK_200, res->status);
  9486. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9487. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9488. EXPECT_EQ(104U, res->body.size());
  9489. }
  9490. // A handler that serves an already-encoded file names the coding itself. The
  9491. // file-backed path decided its coding from Accept-Encoding and the content
  9492. // type alone, so it compressed the stored bytes a second time and appended a
  9493. // second Content-Encoding field line.
  9494. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9495. auto port = start(enable_without_floor);
  9496. Client cli(HOST, port);
  9497. cli.set_decompress(false);
  9498. auto res = cli.Get("/pre-encoded-file-content",
  9499. Headers{{"Accept-Encoding", "gzip"}});
  9500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9501. EXPECT_EQ(StatusCode::OK_200, res->status);
  9502. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9503. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9504. // Vary belongs to a coding the server chose, and it chose none here.
  9505. EXPECT_FALSE(res->has_header("Vary"));
  9506. // The file travels exactly as it is stored on disk.
  9507. EXPECT_EQ(104U, res->body.size());
  9508. }
  9509. // The 1MB file clears the default floor, so this one runs the configuration a
  9510. // deployment would actually have.
  9511. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9512. auto port = start(enable);
  9513. Client cli(HOST, port);
  9514. cli.set_decompress(false);
  9515. auto res =
  9516. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9518. EXPECT_EQ(StatusCode::OK_200, res->status);
  9519. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9520. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9521. EXPECT_FALSE(res->has_header("Vary"));
  9522. EXPECT_EQ(1048576U, res->body.size());
  9523. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9524. }
  9525. TEST_F(StaticFileCompressionTest, Head) {
  9526. auto port = start(enable);
  9527. Client cli(HOST, port);
  9528. cli.set_decompress(false);
  9529. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9530. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9531. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9533. EXPECT_EQ(StatusCode::OK_200, res->status);
  9534. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9535. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9536. // HEAD still reports the size a GET would return.
  9537. EXPECT_EQ(get->get_header_value("Content-Length"),
  9538. res->get_header_value("Content-Length"));
  9539. EXPECT_TRUE(res->body.empty());
  9540. }
  9541. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9542. auto port = start(enable);
  9543. Client cli(HOST, port);
  9544. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9545. {"Accept-Encoding", "gzip"}});
  9546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9547. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9548. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9549. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9550. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9551. EXPECT_EQ("cd", res->body);
  9552. }
  9553. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9554. auto port = start(enable);
  9555. Client cli(HOST, port);
  9556. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9558. EXPECT_EQ(StatusCode::OK_200, res->status);
  9559. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9560. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9561. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9562. }
  9563. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9564. auto port = start(enable);
  9565. Client cli(HOST, port);
  9566. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9568. EXPECT_EQ(StatusCode::OK_200, res->status);
  9569. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9570. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9571. EXPECT_TRUE(res->body.empty());
  9572. }
  9573. TEST_F(StaticFileCompressionTest, MinLength) {
  9574. auto port = start(enable);
  9575. Client cli(HOST, port);
  9576. // 104 bytes, well under the default floor. Compressing it would add the
  9577. // gzip header and trailer to a body that already fits in one packet.
  9578. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9580. EXPECT_EQ(StatusCode::OK_200, res->status);
  9581. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9582. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9583. }
  9584. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9585. auto port = start([](Server &svr) {
  9586. svr.set_static_file_compression(true);
  9587. svr.set_static_file_compression_min_length(1);
  9588. });
  9589. Client cli(HOST, port);
  9590. cli.set_decompress(false);
  9591. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9593. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9594. // A 9-byte file comes back larger than it went in, because gzip's header and
  9595. // trailer outweigh anything deflate can save. That is the end of the range
  9596. // the floor exists to keep out.
  9597. EXPECT_GT(res->body.size(), 9U);
  9598. }
  9599. TEST_F(StaticFileCompressionTest, MaxLength) {
  9600. auto port = start([](Server &svr) {
  9601. svr.set_static_file_compression(true);
  9602. svr.set_static_file_compression_min_length(0);
  9603. svr.set_static_file_compression_max_length(1024);
  9604. });
  9605. Client cli(HOST, port);
  9606. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9607. // defines `small` as a macro on Windows.
  9608. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9609. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9610. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9611. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9612. // Under it: compressed.
  9613. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9614. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9615. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9616. }
  9617. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9618. auto port = start(enable_without_floor);
  9619. Client cli(HOST, port);
  9620. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9621. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9622. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9623. auto identity_etag = identity->get_header_value("ETag");
  9624. ASSERT_FALSE(identity_etag.empty());
  9625. auto gzipped =
  9626. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9627. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9628. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9629. auto gzip_etag = gzipped->get_header_value("ETag");
  9630. ASSERT_FALSE(gzip_etag.empty());
  9631. // Two representations, two validators.
  9632. EXPECT_NE(identity_etag, gzip_etag);
  9633. // Each one revalidates against the request that would produce it...
  9634. auto fresh =
  9635. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9636. {"If-None-Match", gzip_etag}});
  9637. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9638. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9639. auto fresh_identity =
  9640. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9641. {"If-None-Match", identity_etag}});
  9642. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9643. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9644. // ...and not against the other representation.
  9645. auto crossed =
  9646. cli.Get("/dir/index.html",
  9647. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9648. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9649. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9650. }
  9651. // The opt-in covers responses the server reads off disk itself. A caller's own
  9652. // known-length provider keeps its Content-Length and, more importantly, keeps
  9653. // delivering incrementally: routing it through a compressor would hold every
  9654. // write back until zlib's window filled.
  9655. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9656. auto port = start(enable);
  9657. Client cli(HOST, port);
  9658. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9660. EXPECT_EQ(StatusCode::OK_200, res->status);
  9661. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9662. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9663. EXPECT_EQ("aaabbb", res->body);
  9664. }
  9665. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9666. auto port = start(enable);
  9667. Client cli(HOST, port);
  9668. cli.set_read_timeout(1, 0);
  9669. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9670. Headers{{"Accept-Encoding", "gzip"}});
  9671. ASSERT_TRUE(handle.is_valid());
  9672. // The provider writes 100 bytes and then stalls for longer than the read
  9673. // timeout. Those first bytes have to arrive anyway: run the response through
  9674. // a compressor and zlib holds them until its window fills, so the read would
  9675. // come back empty instead.
  9676. char buf[256];
  9677. auto n = handle.read(buf, sizeof(buf));
  9678. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9679. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9680. }
  9681. #endif
  9682. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9683. TEST_F(ServerTest, Brotli) {
  9684. Headers headers;
  9685. headers.emplace("Accept-Encoding", "br");
  9686. auto res = cli_.Get("/compress", headers);
  9687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9688. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9689. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9690. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9691. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9692. "7890123456789012345678901234567890",
  9693. res->body);
  9694. EXPECT_EQ(StatusCode::OK_200, res->status);
  9695. }
  9696. #endif
  9697. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9698. TEST_F(ServerTest, Zstd) {
  9699. Headers headers;
  9700. headers.emplace("Accept-Encoding", "zstd");
  9701. auto res = cli_.Get("/compress", headers);
  9702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9703. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9704. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9705. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9706. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9707. "7890123456789012345678901234567890",
  9708. res->body);
  9709. EXPECT_EQ(StatusCode::OK_200, res->status);
  9710. }
  9711. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9712. Headers headers;
  9713. headers.emplace("Accept-Encoding", "");
  9714. auto res = cli_.Get("/compress", headers);
  9715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9716. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9717. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9718. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9719. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9720. "7890123456789012345678901234567890",
  9721. res->body);
  9722. EXPECT_EQ(StatusCode::OK_200, res->status);
  9723. }
  9724. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9725. Headers headers;
  9726. headers.emplace("Accept-Encoding", "zstd");
  9727. std::string body;
  9728. auto res =
  9729. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9730. EXPECT_EQ(100U, data_length);
  9731. body.append(data, data_length);
  9732. return true;
  9733. });
  9734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9735. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9736. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9737. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9738. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9739. "7890123456789012345678901234567890",
  9740. body);
  9741. EXPECT_EQ(StatusCode::OK_200, res->status);
  9742. }
  9743. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9744. Headers headers;
  9745. headers.emplace("Accept-Encoding", "zstd");
  9746. cli_.set_decompress(false);
  9747. auto res = cli_.Get("/compress", headers);
  9748. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9749. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9750. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9751. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9753. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9754. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9755. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9756. EXPECT_EQ(StatusCode::OK_200, res->status);
  9757. ASSERT_EQ(26U, res->body.size());
  9758. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9759. 0);
  9760. }
  9761. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9762. Headers headers;
  9763. headers.emplace("Accept-Encoding", "");
  9764. std::string body;
  9765. auto res =
  9766. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9767. EXPECT_EQ(100U, data_length);
  9768. body.append(data, data_length);
  9769. return true;
  9770. });
  9771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9772. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9773. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9774. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9775. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9776. "7890123456789012345678901234567890",
  9777. body);
  9778. EXPECT_EQ(StatusCode::OK_200, res->status);
  9779. }
  9780. TEST_F(ServerTest, NoZstd) {
  9781. Headers headers;
  9782. headers.emplace("Accept-Encoding", "zstd");
  9783. auto res = cli_.Get("/nocompress", headers);
  9784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9785. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9786. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9787. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9788. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9789. "7890123456789012345678901234567890",
  9790. res->body);
  9791. EXPECT_EQ(StatusCode::OK_200, res->status);
  9792. }
  9793. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9794. Headers headers;
  9795. headers.emplace("Accept-Encoding", "zstd");
  9796. std::string body;
  9797. auto res = cli_.Get("/nocompress", headers,
  9798. [&](const char *data, size_t data_length) {
  9799. EXPECT_EQ(100U, data_length);
  9800. body.append(data, data_length);
  9801. return true;
  9802. });
  9803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9804. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9805. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9806. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9807. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9808. "7890123456789012345678901234567890",
  9809. body);
  9810. EXPECT_EQ(StatusCode::OK_200, res->status);
  9811. }
  9812. // TODO: How to enable zstd ??
  9813. TEST_F(ServerTest, MultipartFormDataZstd) {
  9814. UploadFormDataItems items = {
  9815. {"key1", "test", "", ""},
  9816. {"key2", "--abcdefg123", "", ""},
  9817. };
  9818. Headers headers;
  9819. headers.emplace("Accept-Encoding", "zstd");
  9820. cli_.set_compress(true);
  9821. auto res = cli_.Post("/compress-multipart", headers, items);
  9822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9823. EXPECT_EQ(StatusCode::OK_200, res->status);
  9824. }
  9825. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9826. Headers headers;
  9827. headers.emplace("Accept-Encoding", "zstd");
  9828. cli_.set_compress(true);
  9829. auto res = cli_.Put(
  9830. "/put", headers, 3,
  9831. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9832. sink.os << "PUT";
  9833. return true;
  9834. },
  9835. "text/plain");
  9836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9837. EXPECT_EQ(StatusCode::OK_200, res->status);
  9838. EXPECT_EQ("PUT", res->body);
  9839. }
  9840. // Pre-compression logging tests
  9841. TEST_F(ServerTest, PreCompressionLogging) {
  9842. // Test data for compression (matches the actual /compress endpoint content)
  9843. const std::string test_content =
  9844. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9845. "3456789012345678901234567890";
  9846. // Variables to capture logging data
  9847. std::string pre_compression_body;
  9848. std::string pre_compression_content_type;
  9849. std::string pre_compression_content_encoding;
  9850. std::string post_compression_body;
  9851. std::string post_compression_content_type;
  9852. std::string post_compression_content_encoding;
  9853. // Set up pre-compression logger
  9854. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9855. const Response &res) {
  9856. pre_compression_body = res.body;
  9857. pre_compression_content_type = res.get_header_value("Content-Type");
  9858. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9859. });
  9860. // Set up post-compression logger
  9861. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9862. post_compression_body = res.body;
  9863. post_compression_content_type = res.get_header_value("Content-Type");
  9864. post_compression_content_encoding =
  9865. res.get_header_value("Content-Encoding");
  9866. });
  9867. // Test with gzip compression
  9868. Headers headers;
  9869. headers.emplace("Accept-Encoding", "gzip");
  9870. auto res = cli_.Get("/compress", headers);
  9871. // Verify response was compressed
  9872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9873. EXPECT_EQ(StatusCode::OK_200, res->status);
  9874. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9875. // Verify pre-compression logger captured uncompressed content
  9876. EXPECT_EQ(test_content, pre_compression_body);
  9877. EXPECT_EQ("text/plain", pre_compression_content_type);
  9878. EXPECT_TRUE(pre_compression_content_encoding
  9879. .empty()); // No encoding header before compression
  9880. // Verify post-compression logger captured compressed content
  9881. EXPECT_NE(test_content,
  9882. post_compression_body); // Should be different after compression
  9883. EXPECT_EQ("text/plain", post_compression_content_type);
  9884. EXPECT_EQ("gzip", post_compression_content_encoding);
  9885. // Verify compressed content is smaller
  9886. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9887. }
  9888. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9889. const std::string test_content =
  9890. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9891. "3456789012345678901234567890";
  9892. std::string pre_compression_body;
  9893. std::string post_compression_body;
  9894. svr_.set_pre_compression_logger(
  9895. [&](const Request & /*req*/, const Response &res) {
  9896. pre_compression_body = res.body;
  9897. });
  9898. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9899. post_compression_body = res.body;
  9900. });
  9901. Headers headers;
  9902. headers.emplace("Accept-Encoding", "br");
  9903. auto res = cli_.Get("/compress", headers);
  9904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9905. EXPECT_EQ(StatusCode::OK_200, res->status);
  9906. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9907. // Verify pre-compression content is uncompressed
  9908. EXPECT_EQ(test_content, pre_compression_body);
  9909. // Verify post-compression content is compressed
  9910. EXPECT_NE(test_content, post_compression_body);
  9911. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9912. }
  9913. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9914. const std::string test_content =
  9915. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9916. "3456789012345678901234567890";
  9917. std::string pre_compression_body;
  9918. std::string post_compression_body;
  9919. svr_.set_pre_compression_logger(
  9920. [&](const Request & /*req*/, const Response &res) {
  9921. pre_compression_body = res.body;
  9922. });
  9923. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9924. post_compression_body = res.body;
  9925. });
  9926. // Request without compression (use /nocompress endpoint)
  9927. Headers headers;
  9928. auto res = cli_.Get("/nocompress", headers);
  9929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9930. EXPECT_EQ(StatusCode::OK_200, res->status);
  9931. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9932. // Pre-compression logger should not be called when no compression is applied
  9933. EXPECT_TRUE(
  9934. pre_compression_body.empty()); // Pre-compression logger not called
  9935. EXPECT_EQ(
  9936. test_content,
  9937. post_compression_body); // Post-compression logger captures final content
  9938. }
  9939. TEST_F(ServerTest, LoggerSeesContentLength) {
  9940. size_t logged_content_length = 0;
  9941. std::string logged_content_length_header;
  9942. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9943. logged_content_length = res.content_length_;
  9944. logged_content_length_header = res.get_header_value("Content-Length");
  9945. });
  9946. auto res = cli_.Get("/nocompress");
  9947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9948. EXPECT_EQ(StatusCode::OK_200, res->status);
  9949. EXPECT_EQ(res->body.size(), logged_content_length);
  9950. EXPECT_EQ(std::to_string(logged_content_length),
  9951. logged_content_length_header);
  9952. }
  9953. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9954. const std::string test_content =
  9955. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9956. "3456789012345678901234567890";
  9957. std::string pre_compression_body;
  9958. bool pre_logger_called = false;
  9959. // Set only pre-compression logger
  9960. svr_.set_pre_compression_logger(
  9961. [&](const Request & /*req*/, const Response &res) {
  9962. pre_compression_body = res.body;
  9963. pre_logger_called = true;
  9964. });
  9965. Headers headers;
  9966. headers.emplace("Accept-Encoding", "gzip");
  9967. auto res = cli_.Get("/compress", headers);
  9968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9969. EXPECT_EQ(StatusCode::OK_200, res->status);
  9970. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9971. // Verify pre-compression logger was called
  9972. EXPECT_TRUE(pre_logger_called);
  9973. EXPECT_EQ(test_content, pre_compression_body);
  9974. }
  9975. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9976. {
  9977. // Test with Expect: 100-continue header - success case
  9978. // Server returns 100 Continue, client sends body, server returns 200 OK
  9979. Request req;
  9980. req.method = "POST";
  9981. req.path = "/post-large";
  9982. req.set_header("Expect", "100-continue");
  9983. req.body = LARGE_DATA;
  9984. Response res;
  9985. auto error = Error::Success;
  9986. cli_.set_keep_alive(true);
  9987. auto ret = cli_.send(req, res, error);
  9988. EXPECT_TRUE(ret);
  9989. EXPECT_EQ(StatusCode::OK_200, res.status);
  9990. EXPECT_EQ(LARGE_DATA, res.body);
  9991. }
  9992. {
  9993. // Test with Expect: 100-continue header - error case
  9994. // Client should not send the body when server returns an error
  9995. Request req;
  9996. req.method = "POST";
  9997. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9998. req.set_header("Expect", "100-continue");
  9999. req.body = LARGE_DATA;
  10000. Response res;
  10001. auto error = Error::Success;
  10002. auto start = std::chrono::high_resolution_clock::now();
  10003. cli_.set_keep_alive(true);
  10004. auto ret = cli_.send(req, res, error);
  10005. auto end = std::chrono::high_resolution_clock::now();
  10006. auto elapsed =
  10007. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  10008. .count();
  10009. // With Expect: 100-continue, request completes successfully but with error
  10010. EXPECT_TRUE(ret);
  10011. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  10012. EXPECT_EQ("close", res.get_header_value("Connection"));
  10013. EXPECT_FALSE(cli_.is_socket_open());
  10014. EXPECT_LE(elapsed, 2000);
  10015. }
  10016. {
  10017. // Send an extra GET request to ensure error recovery without hanging
  10018. Request req;
  10019. req.method = "GET";
  10020. req.path = "/hi";
  10021. auto start = std::chrono::high_resolution_clock::now();
  10022. auto res = cli_.send(req);
  10023. auto end = std::chrono::high_resolution_clock::now();
  10024. auto elapsed =
  10025. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  10026. .count();
  10027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10028. EXPECT_EQ(StatusCode::OK_200, res->status);
  10029. EXPECT_EQ("Hello World!", res->body);
  10030. EXPECT_LE(elapsed, 500);
  10031. }
  10032. }
  10033. TEST(ZstdDecompressor, ChunkedDecompression) {
  10034. std::string data;
  10035. for (size_t i = 0; i < 32 * 1024; ++i) {
  10036. data.push_back(static_cast<char>('a' + i % 26));
  10037. }
  10038. std::string compressed_data;
  10039. {
  10040. httplib::detail::zstd_compressor compressor;
  10041. bool result = compressor.compress(
  10042. data.data(), data.size(),
  10043. /*last=*/true,
  10044. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  10045. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  10046. compressed_data_size);
  10047. return true;
  10048. });
  10049. ASSERT_TRUE(result);
  10050. }
  10051. std::string decompressed_data;
  10052. {
  10053. httplib::detail::zstd_decompressor decompressor;
  10054. // Chunk size is chosen specifically to have a decompressed chunk size equal
  10055. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  10056. size_t chunk_size = 130;
  10057. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  10058. chunk_begin += chunk_size) {
  10059. size_t current_chunk_size =
  10060. std::min(compressed_data.size() - chunk_begin, chunk_size);
  10061. bool result = decompressor.decompress(
  10062. compressed_data.data() + chunk_begin, current_chunk_size,
  10063. [&](const char *decompressed_data_chunk,
  10064. size_t decompressed_data_chunk_size) {
  10065. decompressed_data.insert(decompressed_data.size(),
  10066. decompressed_data_chunk,
  10067. decompressed_data_chunk_size);
  10068. return true;
  10069. });
  10070. ASSERT_TRUE(result);
  10071. }
  10072. }
  10073. ASSERT_EQ(data, decompressed_data);
  10074. }
  10075. TEST(ZstdDecompressor, Decompress) {
  10076. std::string original_text = "Compressed with ZSTD";
  10077. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  10078. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  10079. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  10080. 0x20, 0x5a, 0x53, 0x54, 0x44};
  10081. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  10082. std::string decompressed_data;
  10083. {
  10084. httplib::detail::zstd_decompressor decompressor;
  10085. bool result = decompressor.decompress(
  10086. compressed_data.data(), compressed_data.size(),
  10087. [&](const char *decompressed_data_chunk,
  10088. size_t decompressed_data_chunk_size) {
  10089. decompressed_data.insert(decompressed_data.size(),
  10090. decompressed_data_chunk,
  10091. decompressed_data_chunk_size);
  10092. return true;
  10093. });
  10094. ASSERT_TRUE(result);
  10095. }
  10096. ASSERT_EQ(original_text, decompressed_data);
  10097. }
  10098. #endif
  10099. // Sends a raw request to a server listening at HOST:PORT, writing it in
  10100. // separate chunks so that the server sees each part in its own read(). Used to
  10101. // place a read boundary at a specific offset of a request body.
  10102. static bool send_request_in_parts(time_t read_timeout_sec,
  10103. const std::vector<std::string> &parts,
  10104. std::string *resp = nullptr,
  10105. int port = PORT) {
  10106. auto error = Error::Success;
  10107. auto client_sock = detail::create_client_socket(
  10108. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10109. /*connection_timeout_sec=*/5, 0,
  10110. /*read_timeout_sec=*/5, 0,
  10111. /*write_timeout_sec=*/5, 0, std::string(), error);
  10112. if (client_sock == INVALID_SOCKET) { return false; }
  10113. auto ret = detail::process_client_socket(
  10114. client_sock, read_timeout_sec, 0, 0, 0, 0,
  10115. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  10116. for (size_t i = 0; i < parts.size(); i++) {
  10117. const auto &part = parts[i];
  10118. if (part.size() !=
  10119. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  10120. return false;
  10121. }
  10122. if (i + 1 < parts.size()) {
  10123. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10124. }
  10125. }
  10126. char buf[512];
  10127. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  10128. while (line_reader.getline()) {
  10129. if (resp) { *resp += line_reader.ptr(); }
  10130. }
  10131. return true;
  10132. });
  10133. detail::close_socket(client_sock);
  10134. return ret;
  10135. }
  10136. // Sends a raw request to a server listening at HOST:PORT.
  10137. static bool send_request(time_t read_timeout_sec, const std::string &req,
  10138. std::string *resp = nullptr, int port = PORT) {
  10139. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  10140. }
  10141. #ifdef CPPHTTPLIB_SSL_ENABLED
  10142. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  10143. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10144. ASSERT_TRUE(svr.is_valid());
  10145. svr.set_read_timeout(1, 0);
  10146. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10147. auto se = detail::scope_exit([&] {
  10148. svr.stop();
  10149. t.join();
  10150. ASSERT_FALSE(svr.is_running());
  10151. });
  10152. svr.wait_until_ready();
  10153. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  10154. // keeps each wait well within the read timeout. The server gives up a
  10155. // second in, so the bytes sent after that fail.
  10156. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  10157. parts.resize(26, std::string(1, '\0'));
  10158. EXPECT_FALSE(send_request_in_parts(5, parts));
  10159. }
  10160. #endif
  10161. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10162. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  10163. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  10164. const std::vector<std::string> &parts,
  10165. std::string *resp = nullptr,
  10166. int port = PORT) {
  10167. auto error = Error::Success;
  10168. auto sock = detail::create_client_socket(
  10169. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10170. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  10171. /*write_timeout_sec=*/5, 0, std::string(), error);
  10172. if (sock == INVALID_SOCKET) { return false; }
  10173. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10174. auto ctx = SSL_CTX_new(TLS_client_method());
  10175. auto ssl = SSL_new(ctx);
  10176. auto ssl_se = detail::scope_exit([&] {
  10177. SSL_free(ssl);
  10178. SSL_CTX_free(ctx);
  10179. });
  10180. SSL_set_fd(ssl, static_cast<int>(sock));
  10181. if (SSL_connect(ssl) != 1) { return false; }
  10182. for (size_t i = 0; i < parts.size(); i++) {
  10183. const auto &part = parts[i];
  10184. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  10185. static_cast<int>(part.size())) {
  10186. return false;
  10187. }
  10188. if (i + 1 < parts.size()) {
  10189. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10190. }
  10191. }
  10192. char buf[512];
  10193. int n;
  10194. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10195. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  10196. }
  10197. return true;
  10198. }
  10199. #endif
  10200. // The request line, then a header value a byte at a time.
  10201. static std::vector<std::string> slow_request_head_parts() {
  10202. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  10203. parts.resize(26, "a");
  10204. parts.emplace_back("\r\n\r\n");
  10205. return parts;
  10206. }
  10207. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  10208. // within the one-second read timeout. The server gives up a second in, before
  10209. // the head is complete.
  10210. static void
  10211. expect_slow_request_head_dropped(Server &svr,
  10212. const std::function<std::string()> &send) {
  10213. std::atomic<bool> handled(false);
  10214. svr.Get("/", [&](const Request &, Response &res) {
  10215. handled = true;
  10216. res.set_content("ok", "text/plain");
  10217. });
  10218. svr.set_read_timeout(1, 0);
  10219. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10220. auto se = detail::scope_exit([&] {
  10221. svr.stop();
  10222. t.join();
  10223. ASSERT_FALSE(svr.is_running());
  10224. });
  10225. svr.wait_until_ready();
  10226. auto resp = send();
  10227. EXPECT_FALSE(handled);
  10228. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  10229. }
  10230. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10231. Server svr;
  10232. expect_slow_request_head_dropped(svr, [] {
  10233. std::string resp;
  10234. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10235. return resp;
  10236. });
  10237. }
  10238. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10239. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10240. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10241. ASSERT_TRUE(svr.is_valid());
  10242. expect_slow_request_head_dropped(svr, [] {
  10243. std::string resp;
  10244. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10245. return resp;
  10246. });
  10247. }
  10248. #endif
  10249. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10250. Server svr;
  10251. std::string header_value;
  10252. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10253. header_value = req.get_header_value("foo");
  10254. res.set_content("ok", "text/plain");
  10255. });
  10256. thread t = thread([&] { svr.listen(HOST, PORT); });
  10257. auto se = detail::scope_exit([&] {
  10258. svr.stop();
  10259. t.join();
  10260. ASSERT_FALSE(svr.is_running());
  10261. });
  10262. svr.wait_until_ready();
  10263. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10264. // like characters are not treated the same - use vertical tab and escape.
  10265. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10266. "foo: \t \v bar \x1B\t \r\n"
  10267. "Connection: close\r\n"
  10268. "\r\n";
  10269. std::string res;
  10270. ASSERT_TRUE(send_request(5, req, &res));
  10271. EXPECT_EQ(header_value, "");
  10272. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10273. }
  10274. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10275. Server svr;
  10276. std::string received;
  10277. svr.Get("/order", [&](const Request &req, Response &res) {
  10278. received = entries_to_string(req.headers);
  10279. res.set_content("ok", "text/plain");
  10280. });
  10281. auto port = svr.bind_to_any_port(HOST);
  10282. thread t = thread([&] { svr.listen_after_bind(); });
  10283. auto se = detail::scope_exit([&] {
  10284. svr.stop();
  10285. t.join();
  10286. ASSERT_FALSE(svr.is_running());
  10287. });
  10288. svr.wait_until_ready();
  10289. const std::string req = "GET /order HTTP/1.1\r\n"
  10290. "Host: localhost\r\n"
  10291. "X-First: 1\r\n"
  10292. "X-Dup: a\r\n"
  10293. "X-Second: 2\r\n"
  10294. "X-Dup: b\r\n"
  10295. "Connection: close\r\n"
  10296. "\r\n";
  10297. std::string res;
  10298. ASSERT_TRUE(send_request(5, req, &res, port));
  10299. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10300. EXPECT_EQ(
  10301. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10302. received);
  10303. }
  10304. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10305. Server svr;
  10306. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10307. res.set_header("Set-Cookie", "first=1");
  10308. res.set_header("X-Between", "y");
  10309. res.set_header("Set-Cookie", "second=2");
  10310. res.set_content("ok", "text/plain");
  10311. });
  10312. auto port = svr.bind_to_any_port(HOST);
  10313. thread t = thread([&] { svr.listen_after_bind(); });
  10314. auto se = detail::scope_exit([&] {
  10315. svr.stop();
  10316. t.join();
  10317. ASSERT_FALSE(svr.is_running());
  10318. });
  10319. svr.wait_until_ready();
  10320. Client cli(HOST, port);
  10321. auto res = cli.Get("/cookies");
  10322. ASSERT_TRUE(res);
  10323. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10324. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10325. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10326. }
  10327. // A stream may send a byte at a time with a small extension on each chunk,
  10328. // however long it runs
  10329. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10330. Server svr;
  10331. svr.Post("/count", [](const Request &req, Response &res) {
  10332. res.set_content(std::to_string(req.body.size()), "text/plain");
  10333. });
  10334. auto port = svr.bind_to_any_port(HOST);
  10335. ASSERT_LT(0, port);
  10336. thread t = thread([&] { svr.listen_after_bind(); });
  10337. auto se = detail::scope_exit([&] {
  10338. svr.stop();
  10339. t.join();
  10340. ASSERT_FALSE(svr.is_running());
  10341. });
  10342. svr.wait_until_ready();
  10343. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10344. "\r\nTransfer-Encoding: chunked\r\n"
  10345. "Connection: close\r\n\r\n";
  10346. for (auto i = 0; i < 4096; i++) {
  10347. req += "1;a=b\r\nx\r\n";
  10348. }
  10349. req += "0\r\n\r\n";
  10350. std::string res;
  10351. ASSERT_TRUE(send_request(5, req, &res, port));
  10352. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10353. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10354. }
  10355. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10356. Server svr;
  10357. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10358. auto i = new int(0);
  10359. res.set_header("Trailer", "X-Safe, X-Reflected");
  10360. res.set_chunked_content_provider(
  10361. "text/plain",
  10362. [i](size_t /*offset*/, DataSink &sink) {
  10363. if (*i == 0) {
  10364. sink.os << "body";
  10365. } else {
  10366. Headers trailer;
  10367. // A valid trailer that must survive.
  10368. trailer.emplace("X-Safe", "safe");
  10369. // Attacker-controlled value carrying CR/LF (response splitting).
  10370. trailer.emplace("X-Reflected",
  10371. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10372. // Attacker-controlled name carrying CR/LF.
  10373. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10374. sink.done_with_trailer(trailer);
  10375. }
  10376. (*i)++;
  10377. return true;
  10378. },
  10379. [i](bool /*success*/) { delete i; });
  10380. });
  10381. thread t = thread([&] { svr.listen(HOST, PORT); });
  10382. auto se = detail::scope_exit([&] {
  10383. svr.stop();
  10384. t.join();
  10385. ASSERT_FALSE(svr.is_running());
  10386. });
  10387. svr.wait_until_ready();
  10388. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10389. "Host: " + HOST +
  10390. "\r\n"
  10391. "Connection: close\r\n"
  10392. "\r\n";
  10393. std::string res;
  10394. ASSERT_TRUE(send_request(5, req, &res));
  10395. // The injected fields must not appear anywhere in the raw response.
  10396. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10397. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10398. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10399. // Invalid trailers are dropped entirely, matching set_header().
  10400. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10401. // The valid trailer still passes through.
  10402. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10403. }
  10404. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10405. // A custom header writer gets only the fields the default one writes
  10406. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10407. std::string s;
  10408. for (const auto &h : hdrs) {
  10409. s += h.first + ": " + h.second + "\r\n";
  10410. }
  10411. s += "\r\n";
  10412. return strm.write(s.data(), s.size());
  10413. };
  10414. for (auto custom_writer : {false, true}) {
  10415. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10416. Server svr;
  10417. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10418. svr.set_post_routing_handler([](const Request &, Response &res) {
  10419. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10420. });
  10421. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10422. // res.headers is a public field an application can populate directly,
  10423. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10424. // A valid header that must survive.
  10425. res.headers.emplace("X-Safe", "safe");
  10426. // Attacker-controlled value carrying CR/LF (response splitting).
  10427. res.headers.emplace("X-Reflected",
  10428. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10429. // Attacker-controlled name carrying CR/LF.
  10430. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10431. res.set_content("body", "text/plain");
  10432. });
  10433. thread t = thread([&] { svr.listen(HOST, PORT); });
  10434. auto se = detail::scope_exit([&] {
  10435. svr.stop();
  10436. t.join();
  10437. ASSERT_FALSE(svr.is_running());
  10438. });
  10439. svr.wait_until_ready();
  10440. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10441. "Host: " + HOST +
  10442. "\r\n"
  10443. "Connection: close\r\n"
  10444. "\r\n";
  10445. std::string res;
  10446. ASSERT_TRUE(send_request(5, req, &res));
  10447. // The injected fields must not appear anywhere in the raw response.
  10448. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10449. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10450. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10451. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10452. // Invalid headers are dropped entirely, matching set_header().
  10453. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10454. // The valid header still passes through.
  10455. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10456. }
  10457. }
  10458. // Forward declaration: in split builds split.py strips `inline` and moves the
  10459. // definition into httplib.cc, so detail::write_request_line is not visible from
  10460. // the public httplib.h. Re-declaring it here lets the tests link against the
  10461. // symbol in both header-only and split builds.
  10462. namespace httplib {
  10463. namespace detail {
  10464. ssize_t write_request_line(Stream &strm, const std::string &method,
  10465. const std::string &path);
  10466. } // namespace detail
  10467. } // namespace httplib
  10468. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10469. // A well-formed target is written verbatim.
  10470. {
  10471. detail::BufferStream strm;
  10472. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10473. EXPECT_GT(n, 0);
  10474. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10475. }
  10476. // A target carrying CR/LF, SP or other control octets must be rejected
  10477. // before anything reaches the wire, otherwise it splits the request line and
  10478. // injects a header or a whole request.
  10479. const std::string evil_targets[] = {
  10480. "/a\r\nInjected: pwned",
  10481. "/a\rInjected",
  10482. "/a\nInjected",
  10483. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10484. "/a b",
  10485. "/a\tb",
  10486. "/a\x7f",
  10487. };
  10488. for (const auto &evil : evil_targets) {
  10489. detail::BufferStream strm;
  10490. auto n = detail::write_request_line(strm, "GET", evil);
  10491. EXPECT_LT(n, 0);
  10492. EXPECT_TRUE(strm.get_buffer().empty());
  10493. }
  10494. }
  10495. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10496. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10497. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10498. // target reaches write_request. The client must fail cleanly with
  10499. // Error::Write instead of putting a request-line-less, header-injecting
  10500. // request on the wire.
  10501. Server svr;
  10502. svr.Get("/a", [](const Request &, Response &res) {
  10503. res.set_content("ok", "text/plain");
  10504. });
  10505. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10506. auto se = detail::scope_exit([&] {
  10507. svr.stop();
  10508. thread.join();
  10509. ASSERT_FALSE(svr.is_running());
  10510. });
  10511. svr.wait_until_ready();
  10512. {
  10513. Client cli(HOST, PORT);
  10514. cli.set_path_encode(false);
  10515. // The request is rejected before anything is written, so the connection
  10516. // stays silent and the subsequent response read would otherwise block for
  10517. // the full default read timeout. Shorten it -- the assertion is on the
  10518. // error, not the timeout.
  10519. cli.set_read_timeout(1, 0);
  10520. auto res = cli.Get("/a\r\nInjected: pwned");
  10521. EXPECT_FALSE(res);
  10522. EXPECT_EQ(Error::Write, res.error());
  10523. }
  10524. }
  10525. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10526. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10527. // including extension methods.
  10528. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10529. for (const auto &method : good_methods) {
  10530. detail::BufferStream strm;
  10531. auto n = detail::write_request_line(strm, method, "/");
  10532. EXPECT_GT(n, 0);
  10533. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10534. }
  10535. // A method carrying CR/LF would split the request line and smuggle a whole
  10536. // request ahead of the real one. A space or an empty method corrupts the
  10537. // request line. All must be rejected before anything reaches the wire.
  10538. const std::string evil_methods[] = {
  10539. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10540. "GET\r\nInjected: pwned",
  10541. "GET\r",
  10542. "GET\n",
  10543. "GE T",
  10544. "",
  10545. };
  10546. for (const auto &evil : evil_methods) {
  10547. detail::BufferStream strm;
  10548. auto n = detail::write_request_line(strm, evil, "/");
  10549. EXPECT_LT(n, 0);
  10550. EXPECT_TRUE(strm.get_buffer().empty());
  10551. }
  10552. }
  10553. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10554. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10555. // through Client::send must fail with Error::Write and no request, neither
  10556. // the smuggled one nor the real one, may reach the server.
  10557. Server svr;
  10558. std::atomic<int> request_count(0);
  10559. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10560. request_count++;
  10561. res.status = StatusCode::OK_200;
  10562. return Server::HandlerResponse::Handled;
  10563. });
  10564. auto port = svr.bind_to_any_port(HOST);
  10565. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10566. auto se = detail::scope_exit([&] {
  10567. svr.stop();
  10568. thread.join();
  10569. ASSERT_FALSE(svr.is_running());
  10570. });
  10571. svr.wait_until_ready();
  10572. {
  10573. Client cli(HOST, port);
  10574. const std::string evil_methods[] = {
  10575. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10576. "GE T",
  10577. "",
  10578. };
  10579. for (const auto &evil : evil_methods) {
  10580. Request req;
  10581. req.method = evil;
  10582. req.path = "/";
  10583. auto res = cli.send(req);
  10584. EXPECT_FALSE(res);
  10585. EXPECT_EQ(Error::Write, res.error());
  10586. }
  10587. auto handle =
  10588. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10589. EXPECT_FALSE(handle.is_valid());
  10590. EXPECT_EQ(Error::Write, handle.error);
  10591. // A valid request on the same client still goes through.
  10592. auto res = cli.Get("/");
  10593. ASSERT_TRUE(res);
  10594. EXPECT_EQ(StatusCode::OK_200, res->status);
  10595. }
  10596. EXPECT_EQ(1, request_count.load());
  10597. }
  10598. // Sends a raw request and verifies that there isn't a crash or exception.
  10599. static void test_raw_request(const std::string &req,
  10600. std::string *out = nullptr) {
  10601. Server svr;
  10602. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10603. res.set_content("ok", "text/plain");
  10604. });
  10605. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10606. res.set_content("ok", "text/plain");
  10607. });
  10608. svr.Get("/header_field_value_check",
  10609. [&](const Request & /*req*/, Response &res) {
  10610. res.set_content("ok", "text/plain");
  10611. });
  10612. svr.CustomRoute("PROPFIND", "/dav",
  10613. [&](const Request & /*req*/, Response &res) {
  10614. res.status = StatusCode::MultiStatus_207;
  10615. });
  10616. // Server read timeout must be longer than the client read timeout for the
  10617. // bug to reproduce, probably to force the server to process a request
  10618. // without a trailing blank line.
  10619. const time_t client_read_timeout_sec = 1;
  10620. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10621. bool listen_thread_ok = false;
  10622. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10623. auto se = detail::scope_exit([&] {
  10624. svr.stop();
  10625. t.join();
  10626. ASSERT_FALSE(svr.is_running());
  10627. EXPECT_TRUE(listen_thread_ok);
  10628. });
  10629. svr.wait_until_ready();
  10630. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10631. }
  10632. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10633. // A certain header line causes an exception if the header property is parsed
  10634. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10635. test_raw_request(
  10636. "GET /hi HTTP/1.1\r\n"
  10637. " : "
  10638. " "
  10639. " ");
  10640. }
  10641. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10642. // A certain header line causes an exception if the header property *name* is
  10643. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10644. // greedy matcher and requires backtracking when there are a lot of ":"
  10645. // characters.
  10646. // This occurs with libc++ but not libstdc++.
  10647. test_raw_request(
  10648. "GET /hi HTTP/1.1\r\n"
  10649. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10650. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10651. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10652. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10653. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10654. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10655. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10656. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10657. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10658. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10659. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10660. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10661. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10662. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10663. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10664. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10665. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10666. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10667. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10668. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10669. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10670. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10671. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10672. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10673. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10674. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10675. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10676. "&&&%%%");
  10677. }
  10678. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10679. // Make sure this doesn't crash the server.
  10680. // In a previous version of the header line regex, the "\r" rendered the line
  10681. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10682. // a new position where the leading white space ended and the field value
  10683. // began.
  10684. // The crash occurs with libc++ but not libstdc++.
  10685. test_raw_request("GET /hi HTTP/1.1\r\n"
  10686. "a:" +
  10687. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10688. "\r\n"
  10689. "\r\n");
  10690. }
  10691. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10692. const char *rejected[] = {
  10693. // RFC 9112 §3: one SP between the parts, and nothing else
  10694. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10695. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10696. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10697. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10698. // A request-target has no fragment
  10699. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10700. // An HTTP/1.1 request needs a Host
  10701. "GET /hi HTTP/1.1\r\n\r\n",
  10702. };
  10703. for (auto request : rejected) {
  10704. std::string out;
  10705. test_raw_request(request, &out);
  10706. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10707. }
  10708. std::string out;
  10709. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10710. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10711. }
  10712. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10713. // RFC 9112 §6.1
  10714. const char *requests[] = {
  10715. "PUT /put_hi HTTP/1.1\r\n"
  10716. "Host: localhost\r\n"
  10717. "Content-Length: 0\r\n"
  10718. "Transfer-Encoding: chunked\r\n"
  10719. "\r\n"
  10720. "0\r\n\r\n",
  10721. "PUT /put_hi HTTP/1.0\r\n"
  10722. "Connection: keep-alive\r\n"
  10723. "Transfer-Encoding: chunked\r\n"
  10724. "\r\n"
  10725. "0\r\n\r\n",
  10726. };
  10727. for (auto request : requests) {
  10728. std::string out;
  10729. test_raw_request(request, &out);
  10730. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10731. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10732. }
  10733. }
  10734. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10735. std::string out;
  10736. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10737. "Content-Type: text/plain\r\n"
  10738. "Transfer-Encoding: chunked\r\n"
  10739. "\r\n"
  10740. "nothex\r\n",
  10741. &out);
  10742. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10743. }
  10744. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10745. std::string out;
  10746. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10747. "Content-Type: text/plain\r\n"
  10748. "Transfer-Encoding: chunked\r\n"
  10749. "\r\n"
  10750. "3\r\n"
  10751. "xyz\r\n"
  10752. "NaN\r\n",
  10753. &out);
  10754. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10755. }
  10756. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10757. std::string out;
  10758. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10759. "Content-Type: text/plain\r\n"
  10760. "Transfer-Encoding: chunked\r\n"
  10761. "\r\n"
  10762. // Length is too large for 64 bits.
  10763. "1ffffffffffffffff\r\n"
  10764. "xyz\r\n",
  10765. &out);
  10766. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10767. }
  10768. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10769. test_raw_request("GET /hi HTTP/1.1\r\n"
  10770. "Content-Type: text/plain\r\n\r");
  10771. }
  10772. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10773. std::string out;
  10774. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10775. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10776. }
  10777. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10778. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10779. std::string out;
  10780. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10781. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10782. }
  10783. }
  10784. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10785. std::string out;
  10786. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10787. "Host: localhost\r\n"
  10788. "Connection: close\r\n\r\n",
  10789. &out);
  10790. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10791. }
  10792. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10793. Server svr;
  10794. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10795. EXPECT_TRUE(!req.remote_addr.empty());
  10796. });
  10797. thread t = thread([&] { svr.listen(HOST, PORT); });
  10798. auto se = detail::scope_exit([&] {
  10799. svr.stop();
  10800. t.join();
  10801. ASSERT_FALSE(svr.is_running());
  10802. });
  10803. svr.wait_until_ready();
  10804. // Send an invalid request line to trigger Bad Request
  10805. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10806. std::string out;
  10807. ASSERT_TRUE(send_request(5, bad_req, &out));
  10808. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10809. }
  10810. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10811. // answered right away rather than blocking on a read that waits for EOF.
  10812. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10813. std::string out;
  10814. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10815. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10816. }
  10817. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10818. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10819. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10820. for (const auto *method : methods) {
  10821. Server svr;
  10822. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10823. EXPECT_FALSE(svr.is_valid()) << method;
  10824. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10825. }
  10826. }
  10827. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10828. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10829. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10830. for (const auto *method : methods) {
  10831. Server svr;
  10832. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10833. EXPECT_FALSE(svr.is_valid()) << method;
  10834. }
  10835. }
  10836. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10837. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10838. "COPY", "MOVE", "LOCK",
  10839. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10840. Server svr;
  10841. for (const auto *method : methods) {
  10842. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10843. }
  10844. EXPECT_TRUE(svr.is_valid());
  10845. }
  10846. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10847. Server svr;
  10848. svr.CustomRoute("POST", "/x",
  10849. [](const Request &, Response &, const ContentReader &) {});
  10850. EXPECT_FALSE(svr.is_valid());
  10851. }
  10852. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10853. Server svr;
  10854. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10855. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10856. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10857. EXPECT_FALSE(svr.is_valid());
  10858. }
  10859. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10860. Server svr;
  10861. auto captured = Error::Success;
  10862. svr.set_error_logger(
  10863. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10864. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10865. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10866. }
  10867. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10868. std::string out;
  10869. std::string request(
  10870. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10871. test_raw_request(request, &out);
  10872. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10873. }
  10874. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10875. std::string out;
  10876. std::string request(
  10877. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10878. test_raw_request(request, &out);
  10879. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10880. }
  10881. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10882. std::string out;
  10883. std::string request(
  10884. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10885. test_raw_request(request, &out);
  10886. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10887. }
  10888. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10889. std::string out;
  10890. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10891. "Host: localhost\r\n"
  10892. "Test: \r\n\r\n",
  10893. &out);
  10894. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10895. }
  10896. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10897. Server svr;
  10898. std::string x_custom;
  10899. std::string cookie;
  10900. std::string xff;
  10901. std::string x_unicode;
  10902. std::string x_iis;
  10903. svr.Get("/check", [&](const Request &req, Response &res) {
  10904. x_custom = req.get_header_value("X-Custom");
  10905. cookie = req.get_header_value("Cookie");
  10906. xff = req.get_header_value("X-Forwarded-For");
  10907. x_unicode = req.get_header_value("X-Unicode");
  10908. x_iis = req.get_header_value("X-IIS");
  10909. res.set_content("ok", "text/plain");
  10910. });
  10911. thread t = thread([&] { svr.listen(HOST, PORT); });
  10912. auto se = detail::scope_exit([&] {
  10913. svr.stop();
  10914. t.join();
  10915. ASSERT_FALSE(svr.is_running());
  10916. });
  10917. svr.wait_until_ready();
  10918. const std::string req = "GET /check HTTP/1.1\r\n"
  10919. "Host: localhost\r\n"
  10920. "X-Custom: a%0D%0AInjected: b\r\n"
  10921. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10922. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10923. "X-Unicode: %E3%81%82\r\n"
  10924. "X-IIS: %u00E9\r\n"
  10925. "Connection: close\r\n"
  10926. "\r\n";
  10927. std::string res;
  10928. ASSERT_TRUE(send_request(5, req, &res));
  10929. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10930. // Every value must be returned verbatim (wire form), with no decoding.
  10931. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10932. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10933. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10934. EXPECT_EQ("%E3%81%82", x_unicode);
  10935. EXPECT_EQ("%u00E9", x_iis);
  10936. }
  10937. // Applications that previously relied on automatic percent-decoding can
  10938. // reproduce the old behavior by explicitly calling decode_path_component()
  10939. // or, for RFC 3986 conformance, decode_uri_component().
  10940. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10941. Server svr;
  10942. std::string decoded;
  10943. svr.Get("/check", [&](const Request &req, Response &res) {
  10944. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10945. res.set_content("ok", "text/plain");
  10946. });
  10947. thread t = thread([&] { svr.listen(HOST, PORT); });
  10948. auto se = detail::scope_exit([&] {
  10949. svr.stop();
  10950. t.join();
  10951. ASSERT_FALSE(svr.is_running());
  10952. });
  10953. svr.wait_until_ready();
  10954. const std::string req = "GET /check HTTP/1.1\r\n"
  10955. "Host: localhost\r\n"
  10956. "X-Custom: hello%20world\r\n"
  10957. "Connection: close\r\n"
  10958. "\r\n";
  10959. std::string res;
  10960. ASSERT_TRUE(send_request(5, req, &res));
  10961. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10962. EXPECT_EQ("hello world", decoded);
  10963. }
  10964. // Regression test for #2033. Browsers send Referer values that include
  10965. // percent-encoded characters such as %0A inside the URL. Decoding the
  10966. // header value would either trip the post-decode CR/LF/NUL guard (the
  10967. // original bug, returning 400) or, after that guard was relaxed, silently
  10968. // store a literal LF — both unacceptable. The wire form must round-trip.
  10969. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10970. Server svr;
  10971. std::string referer;
  10972. svr.Get("/check", [&](const Request &req, Response &res) {
  10973. referer = req.get_header_value("Referer");
  10974. res.set_content("ok", "text/plain");
  10975. });
  10976. thread t = thread([&] { svr.listen(HOST, PORT); });
  10977. auto se = detail::scope_exit([&] {
  10978. svr.stop();
  10979. t.join();
  10980. ASSERT_FALSE(svr.is_running());
  10981. });
  10982. svr.wait_until_ready();
  10983. const std::string req = "GET /check HTTP/1.1\r\n"
  10984. "Host: localhost\r\n"
  10985. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10986. "Connection: close\r\n"
  10987. "\r\n";
  10988. std::string res;
  10989. ASSERT_TRUE(send_request(5, req, &res));
  10990. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10991. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10992. }
  10993. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10994. Server svr;
  10995. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10996. res.set_header("Cache-Control", "no-cache");
  10997. res.set_chunked_content_provider(
  10998. "text/event-stream", [](size_t offset, DataSink &sink) {
  10999. std::string s = "data:";
  11000. s += std::to_string(offset);
  11001. s += "\n\n";
  11002. auto ret = sink.write(s.data(), s.size());
  11003. EXPECT_TRUE(ret);
  11004. std::this_thread::sleep_for(std::chrono::seconds(1));
  11005. return true;
  11006. });
  11007. });
  11008. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11009. svr.wait_until_ready();
  11010. Client client(HOST, PORT);
  11011. const Headers headers = {{"Accept", "text/event-stream"}};
  11012. auto get_thread = std::thread([&client, &headers]() {
  11013. auto res = client.Get(
  11014. "/events", headers,
  11015. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  11016. });
  11017. auto se = detail::scope_exit([&] {
  11018. svr.stop();
  11019. get_thread.join();
  11020. listen_thread.join();
  11021. ASSERT_FALSE(svr.is_running());
  11022. });
  11023. // Give GET time to get a few messages.
  11024. std::this_thread::sleep_for(std::chrono::seconds(2));
  11025. }
  11026. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  11027. httplib::Server svr;
  11028. svr.Post("/hi",
  11029. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  11030. res.status = StatusCode::OK_200;
  11031. });
  11032. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11033. svr.wait_until_ready();
  11034. Client cli(HOST, PORT);
  11035. auto res = cli.Post("/hi", "data", "text/plain");
  11036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11037. EXPECT_EQ(StatusCode::OK_200, res->status);
  11038. svr.stop();
  11039. thread.join();
  11040. ASSERT_FALSE(svr.is_running());
  11041. res = cli.Post("/hi", "data", "text/plain");
  11042. ASSERT_FALSE(res);
  11043. }
  11044. TEST(ServerStopTest, ListenFailure) {
  11045. Server svr;
  11046. auto t = thread([&]() {
  11047. auto ret = svr.listen("????", PORT);
  11048. EXPECT_FALSE(ret);
  11049. });
  11050. svr.wait_until_ready();
  11051. svr.stop();
  11052. t.join();
  11053. }
  11054. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11055. TEST(ServerStopTest, Decommision) {
  11056. Server svr;
  11057. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  11058. for (int i = 0; i < 4; i++) {
  11059. auto is_even = !(i % 2);
  11060. std::thread t{[&] {
  11061. try {
  11062. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  11063. if (is_even) {
  11064. throw std::runtime_error("Some thing that happens to go wrong.");
  11065. }
  11066. svr.listen(HOST, PORT);
  11067. } catch (...) { svr.decommission(); }
  11068. }};
  11069. svr.wait_until_ready();
  11070. // Server is up
  11071. {
  11072. Client cli(HOST, PORT);
  11073. auto res = cli.Get("/hi");
  11074. if (is_even) {
  11075. EXPECT_FALSE(res);
  11076. } else {
  11077. EXPECT_TRUE(res);
  11078. EXPECT_EQ("hi...", res->body);
  11079. }
  11080. }
  11081. svr.stop();
  11082. t.join();
  11083. // Server is down...
  11084. {
  11085. Client cli(HOST, PORT);
  11086. auto res = cli.Get("/hi");
  11087. EXPECT_FALSE(res);
  11088. }
  11089. }
  11090. }
  11091. #endif
  11092. // Helper function for string body upload progress tests
  11093. template <typename SetupHandler, typename ClientCall>
  11094. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  11095. ClientCall &&client_call,
  11096. const string &body) {
  11097. Server svr;
  11098. setup_handler(svr);
  11099. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11100. auto se = detail::scope_exit([&] {
  11101. svr.stop();
  11102. t.join();
  11103. });
  11104. svr.wait_until_ready();
  11105. Client cli(HOST, PORT);
  11106. vector<uint64_t> progress_values;
  11107. bool progress_called = false;
  11108. auto res =
  11109. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11110. progress_values.push_back(current);
  11111. progress_called = true;
  11112. return true;
  11113. });
  11114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11115. EXPECT_EQ(200, res->status);
  11116. EXPECT_TRUE(progress_called);
  11117. }
  11118. TEST(UploadProgressTest, PostStringBodyBasic) {
  11119. TestStringBodyUploadProgress(
  11120. [](Server &svr) {
  11121. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11122. res.set_content("received", "text/plain");
  11123. });
  11124. },
  11125. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11126. return cli.Post("/test", body, "text/plain", progress_callback);
  11127. },
  11128. "test data for upload progress");
  11129. }
  11130. TEST(UploadProgressTest, PutStringBodyBasic) {
  11131. TestStringBodyUploadProgress(
  11132. [](Server &svr) {
  11133. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  11134. res.set_content("put received", "text/plain");
  11135. });
  11136. },
  11137. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11138. return cli.Put("/test", body, "text/plain", progress_callback);
  11139. },
  11140. "put test data for upload progress");
  11141. }
  11142. TEST(UploadProgressTest, PatchStringBodyBasic) {
  11143. TestStringBodyUploadProgress(
  11144. [](Server &svr) {
  11145. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  11146. res.set_content("patch received", "text/plain");
  11147. });
  11148. },
  11149. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11150. return cli.Patch("/test", body, "text/plain", progress_callback);
  11151. },
  11152. "patch test data for upload progress");
  11153. }
  11154. // Helper function for content provider upload progress tests
  11155. template <typename SetupHandler, typename ClientCall>
  11156. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  11157. ClientCall &&client_call) {
  11158. Server svr;
  11159. setup_handler(svr);
  11160. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11161. auto se = detail::scope_exit([&] {
  11162. svr.stop();
  11163. t.join();
  11164. });
  11165. svr.wait_until_ready();
  11166. Client cli(HOST, PORT);
  11167. vector<uint64_t> progress_values;
  11168. auto res =
  11169. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11170. progress_values.push_back(current);
  11171. return true;
  11172. });
  11173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11174. EXPECT_EQ(200, res->status);
  11175. EXPECT_FALSE(progress_values.empty());
  11176. }
  11177. TEST(UploadProgressTest, PostContentProviderProgress) {
  11178. TestContentProviderUploadProgress(
  11179. [](Server &svr) {
  11180. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11181. res.set_content("provider received", "text/plain");
  11182. });
  11183. },
  11184. [](Client &cli, UploadProgress progress_callback) {
  11185. return cli.Post(
  11186. "/test", 9,
  11187. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  11188. sink.os << "test data";
  11189. return true;
  11190. },
  11191. "text/plain", progress_callback);
  11192. });
  11193. }
  11194. // Helper function for multipart upload progress tests
  11195. template <typename SetupHandler, typename ClientCall>
  11196. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  11197. ClientCall &&client_call,
  11198. const string &endpoint) {
  11199. Server svr;
  11200. setup_handler(svr);
  11201. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11202. auto se = detail::scope_exit([&] {
  11203. svr.stop();
  11204. t.join();
  11205. });
  11206. svr.wait_until_ready();
  11207. Client cli(HOST, PORT);
  11208. vector<uint64_t> progress_values;
  11209. UploadFormDataItems items = {
  11210. {"field1", "value1", "", ""},
  11211. {"field2", "longer value for progress tracking test", "", ""},
  11212. {"file1", "file content data for upload progress", "test.txt",
  11213. "text/plain"}};
  11214. auto res = client_call(cli, endpoint, items,
  11215. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11216. progress_values.push_back(current);
  11217. return true;
  11218. });
  11219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11220. EXPECT_EQ(200, res->status);
  11221. EXPECT_FALSE(progress_values.empty());
  11222. }
  11223. TEST(UploadProgressTest, PostMultipartProgress) {
  11224. TestMultipartUploadProgress(
  11225. [](Server &svr) {
  11226. svr.Post("/multipart", [](const Request &req, Response &res) {
  11227. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  11228. res.set_content("multipart received", "text/plain");
  11229. });
  11230. },
  11231. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  11232. UploadProgress progress_callback) {
  11233. return cli.Post(endpoint, items, progress_callback);
  11234. },
  11235. "/multipart");
  11236. }
  11237. // Helper function for basic download progress tests
  11238. template <typename SetupHandler, typename ClientCall>
  11239. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11240. ClientCall &&client_call, const string &endpoint,
  11241. size_t expected_content_size) {
  11242. Server svr;
  11243. setup_handler(svr);
  11244. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11245. auto se = detail::scope_exit([&] {
  11246. svr.stop();
  11247. t.join();
  11248. });
  11249. svr.wait_until_ready();
  11250. Client cli(HOST, PORT);
  11251. vector<uint64_t> progress_values;
  11252. auto res = client_call(cli, endpoint,
  11253. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11254. progress_values.push_back(current);
  11255. return true;
  11256. });
  11257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11258. EXPECT_EQ(200, res->status);
  11259. EXPECT_FALSE(progress_values.empty());
  11260. EXPECT_EQ(expected_content_size, res->body.size());
  11261. }
  11262. TEST(DownloadProgressTest, GetBasic) {
  11263. TestBasicDownloadProgress(
  11264. [](Server &svr) {
  11265. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11266. string content(1000, 'D');
  11267. res.set_content(content, "text/plain");
  11268. });
  11269. },
  11270. [](Client &cli, const string &endpoint,
  11271. DownloadProgress progress_callback) {
  11272. return cli.Get(endpoint, progress_callback);
  11273. },
  11274. "/download", 1000u);
  11275. }
  11276. // Helper function for content receiver download progress tests
  11277. template <typename SetupHandler, typename ClientCall>
  11278. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11279. ClientCall &&client_call,
  11280. const string &endpoint,
  11281. size_t expected_content_size) {
  11282. Server svr;
  11283. setup_handler(svr);
  11284. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11285. auto se = detail::scope_exit([&] {
  11286. svr.stop();
  11287. t.join();
  11288. });
  11289. svr.wait_until_ready();
  11290. Client cli(HOST, PORT);
  11291. vector<uint64_t> progress_values;
  11292. string received_body;
  11293. auto res = client_call(
  11294. cli, endpoint,
  11295. [&](const char *data, size_t data_length) -> bool {
  11296. received_body.append(data, data_length);
  11297. return true;
  11298. },
  11299. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11300. progress_values.push_back(current);
  11301. return true;
  11302. });
  11303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11304. EXPECT_EQ(200, res->status);
  11305. EXPECT_FALSE(progress_values.empty());
  11306. EXPECT_EQ(expected_content_size, received_body.size());
  11307. EXPECT_TRUE(res->body.empty());
  11308. }
  11309. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11310. TestContentReceiverDownloadProgress(
  11311. [](Server &svr) {
  11312. svr.Get("/download-receiver",
  11313. [](const Request & /*req*/, Response &res) {
  11314. string content(2000, 'R');
  11315. res.set_content(content, "text/plain");
  11316. });
  11317. },
  11318. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11319. DownloadProgress progress_callback) {
  11320. return cli.Get(endpoint, content_receiver, progress_callback);
  11321. },
  11322. "/download-receiver", 2000u);
  11323. }
  11324. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11325. // A provider reaching a pass with nothing to hand over - an empty buffer
  11326. // popped off a queue, say - must not be taken to mean the body is finished.
  11327. // It used to end the loop with the terminating chunk unwritten while the
  11328. // server still considered the response complete, so the peer waited for an
  11329. // end that never arrived.
  11330. Server svr;
  11331. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11332. auto step = std::make_shared<int>(0);
  11333. res.set_chunked_content_provider("text/plain",
  11334. [step](size_t /*offset*/, DataSink &sink) {
  11335. switch ((*step)++) {
  11336. case 0: sink.write("", 0); break;
  11337. case 1: sink.write("hello", 5); break;
  11338. default: sink.done(); break;
  11339. }
  11340. return true;
  11341. });
  11342. });
  11343. auto port = svr.bind_to_any_port(HOST);
  11344. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11345. auto listen_se = detail::scope_exit([&] {
  11346. svr.stop();
  11347. listen_thread.join();
  11348. ASSERT_FALSE(svr.is_running());
  11349. });
  11350. svr.wait_until_ready();
  11351. Client cli(HOST, port);
  11352. // Without the fix the body is never terminated, so bound the wait rather
  11353. // than letting the test hang on the default read timeout.
  11354. cli.set_read_timeout(5, 0);
  11355. auto res = cli.Get("/stream");
  11356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11357. EXPECT_EQ(StatusCode::OK_200, res->status);
  11358. EXPECT_EQ("hello", res->body);
  11359. }
  11360. TEST(StreamingTest, NoContentLengthStreaming) {
  11361. Server svr;
  11362. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11363. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11364. if (offset < 6) {
  11365. sink.os << (offset < 3 ? "a" : "b");
  11366. } else {
  11367. sink.done();
  11368. }
  11369. return true;
  11370. });
  11371. });
  11372. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11373. auto listen_se = detail::scope_exit([&] {
  11374. svr.stop();
  11375. listen_thread.join();
  11376. ASSERT_FALSE(svr.is_running());
  11377. });
  11378. svr.wait_until_ready();
  11379. Client client(HOST, PORT);
  11380. auto get_thread = std::thread([&client]() {
  11381. std::string s;
  11382. auto res =
  11383. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11384. s += std::string(data, len);
  11385. return true;
  11386. });
  11387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11388. EXPECT_EQ(StatusCode::OK_200, res->status);
  11389. EXPECT_EQ("aaabbb", s);
  11390. });
  11391. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11392. // Give GET time to get a few messages.
  11393. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11394. }
  11395. TEST(MountTest, Unmount) {
  11396. Server svr;
  11397. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11398. auto se = detail::scope_exit([&] {
  11399. svr.stop();
  11400. listen_thread.join();
  11401. ASSERT_FALSE(svr.is_running());
  11402. });
  11403. svr.wait_until_ready();
  11404. Client cli("localhost", PORT);
  11405. svr.set_mount_point("/mount2", "./www2");
  11406. auto res = cli.Get("/");
  11407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11408. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11409. res = cli.Get("/mount2/dir/test.html");
  11410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11411. EXPECT_EQ(StatusCode::OK_200, res->status);
  11412. svr.set_mount_point("/", "./www");
  11413. res = cli.Get("/dir/");
  11414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11415. EXPECT_EQ(StatusCode::OK_200, res->status);
  11416. svr.remove_mount_point("/");
  11417. res = cli.Get("/dir/");
  11418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11419. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11420. svr.remove_mount_point("/mount2");
  11421. res = cli.Get("/mount2/dir/test.html");
  11422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11423. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11424. }
  11425. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11426. Server svr;
  11427. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11428. svr.Get("/api/hello", [](const Request &, Response &res) {
  11429. res.set_content("api", "text/plain");
  11430. });
  11431. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11432. auto se = detail::scope_exit([&] {
  11433. svr.stop();
  11434. listen_thread.join();
  11435. ASSERT_FALSE(svr.is_running());
  11436. });
  11437. svr.wait_until_ready();
  11438. Client cli(HOST, PORT);
  11439. auto res = cli.Get("/dir/test.html");
  11440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11441. EXPECT_EQ(StatusCode::OK_200, res->status);
  11442. res = cli.Get("/api/hello");
  11443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11444. EXPECT_EQ(StatusCode::OK_200, res->status);
  11445. EXPECT_EQ("api", res->body);
  11446. }
  11447. TEST(MountTest, PathSegmentBoundary) {
  11448. Server svr;
  11449. svr.set_mount_point("/mount2", "./www2");
  11450. svr.set_mount_point("/", "./www");
  11451. auto port = svr.bind_to_any_port(HOST);
  11452. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11453. auto se = detail::scope_exit([&] {
  11454. svr.stop();
  11455. listen_thread.join();
  11456. ASSERT_FALSE(svr.is_running());
  11457. });
  11458. svr.wait_until_ready();
  11459. Client cli(HOST, port);
  11460. auto res = cli.Get("/mount2/dir/test.html");
  11461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11462. EXPECT_EQ(StatusCode::OK_200, res->status);
  11463. // "/mount2" must not match part-way through a path segment.
  11464. res = cli.Get("/mount2dir/test.html");
  11465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11466. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11467. // A mount point ending in '/' keeps matching every path below it.
  11468. res = cli.Get("/dir/test.html");
  11469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11470. EXPECT_EQ(StatusCode::OK_200, res->status);
  11471. }
  11472. TEST(MountTest, Redicect) {
  11473. Server svr;
  11474. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11475. auto se = detail::scope_exit([&] {
  11476. svr.stop();
  11477. listen_thread.join();
  11478. ASSERT_FALSE(svr.is_running());
  11479. });
  11480. svr.set_mount_point("/", "./www");
  11481. svr.wait_until_ready();
  11482. Client cli("localhost", PORT);
  11483. auto res = cli.Get("/dir/");
  11484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11485. EXPECT_EQ(StatusCode::OK_200, res->status);
  11486. res = cli.Get("/dir");
  11487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11488. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11489. res = cli.Get("/file");
  11490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11491. EXPECT_EQ(StatusCode::OK_200, res->status);
  11492. res = cli.Get("/file/");
  11493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11494. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11495. cli.set_follow_location(true);
  11496. res = cli.Get("/dir");
  11497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11498. EXPECT_EQ(StatusCode::OK_200, res->status);
  11499. }
  11500. TEST(MountTest, MultibytesPathName) {
  11501. Server svr;
  11502. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11503. auto se = detail::scope_exit([&] {
  11504. svr.stop();
  11505. listen_thread.join();
  11506. ASSERT_FALSE(svr.is_running());
  11507. });
  11508. svr.set_mount_point("/", "./www");
  11509. svr.wait_until_ready();
  11510. Client cli("localhost", PORT);
  11511. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11513. EXPECT_EQ(StatusCode::OK_200, res->status);
  11514. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11515. }
  11516. // A mount point serves no path with an empty segment or one ending in '.' or
  11517. // a space, so a guard in the pre-routing handler sees the path of every file
  11518. // that is served
  11519. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11520. Server svr;
  11521. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11522. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11523. if (req.path == "/dir/test.html") {
  11524. res.status = StatusCode::Unauthorized_401;
  11525. return Server::HandlerResponse::Handled;
  11526. }
  11527. return Server::HandlerResponse::Unhandled;
  11528. });
  11529. auto port = svr.bind_to_any_port(HOST);
  11530. ASSERT_LT(0, port);
  11531. thread t = thread([&] { svr.listen_after_bind(); });
  11532. auto se = detail::scope_exit([&] {
  11533. svr.stop();
  11534. t.join();
  11535. ASSERT_FALSE(svr.is_running());
  11536. });
  11537. svr.wait_until_ready();
  11538. Client cli(HOST, port);
  11539. for (auto path :
  11540. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11541. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11542. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11543. "/dir/test.html%3A%3A$DATA"}) {
  11544. SCOPED_TRACE(path);
  11545. auto res = cli.Get(path);
  11546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11547. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11548. }
  11549. }
  11550. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11551. Server svr;
  11552. svr.set_mount_point("/", "./www");
  11553. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11554. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11555. auto port = svr.bind_to_any_port(HOST);
  11556. ASSERT_GT(port, 0);
  11557. thread t = thread([&] { svr.listen_after_bind(); });
  11558. auto se = detail::scope_exit([&] {
  11559. svr.stop();
  11560. t.join();
  11561. ASSERT_FALSE(svr.is_running());
  11562. });
  11563. svr.wait_until_ready();
  11564. Client cli(HOST, port);
  11565. auto res = cli.Get("/dir/test.abcde");
  11566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11567. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11568. res = cli.Get("/dir/test.html");
  11569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11570. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11571. }
  11572. #ifdef _WIN32
  11573. // Issue #2435: mmap::open() must succeed even when another handle holds
  11574. // the file open for writing (e.g. an active log file).
  11575. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11576. const char *path = "mmap_concurrent_writer_test.txt";
  11577. const char *content = "hello";
  11578. {
  11579. std::ofstream f(path, std::ios::binary);
  11580. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11581. }
  11582. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11583. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11584. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11585. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11586. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11587. detail::mmap m(path);
  11588. ASSERT_TRUE(m.is_open());
  11589. EXPECT_EQ(strlen(content), m.size());
  11590. char buf[8];
  11591. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11592. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11593. }
  11594. #endif
  11595. #ifndef _WIN32
  11596. // A directory or a device has no size to serve.
  11597. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11598. const char *path = "./mmap_not_regular_test_dir";
  11599. ASSERT_EQ(0, ::mkdir(path, 0755));
  11600. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11601. for (auto p : {path, "/dev/null"}) {
  11602. detail::mmap m(p);
  11603. EXPECT_FALSE(m.is_open()) << p;
  11604. EXPECT_EQ(0U, m.size()) << p;
  11605. }
  11606. Server svr;
  11607. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11608. res.set_file_content("/dev/null");
  11609. });
  11610. auto port = svr.bind_to_any_port(HOST);
  11611. thread t = thread([&] { svr.listen_after_bind(); });
  11612. auto se = detail::scope_exit([&] {
  11613. svr.stop();
  11614. t.join();
  11615. });
  11616. svr.wait_until_ready();
  11617. auto res = Client(HOST, port).Get("/null");
  11618. ASSERT_TRUE(res);
  11619. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11620. }
  11621. #endif
  11622. #ifdef __linux__
  11623. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11624. TEST(MmapTest, FileIsNotMapped) {
  11625. const char *path = "mmap_not_mapped_test.txt";
  11626. {
  11627. std::ofstream f(path, std::ios::binary);
  11628. f << "hello";
  11629. }
  11630. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11631. detail::mmap m(path);
  11632. ASSERT_TRUE(m.is_open());
  11633. std::ifstream maps("/proc/self/maps");
  11634. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11635. std::istreambuf_iterator<char>());
  11636. EXPECT_EQ(std::string::npos, mappings.find(path));
  11637. }
  11638. #endif
  11639. TEST(KeepAliveTest, ReadTimeout) {
  11640. Server svr;
  11641. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11642. std::this_thread::sleep_for(std::chrono::seconds(2));
  11643. res.set_content("a", "text/plain");
  11644. });
  11645. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11646. res.set_content("b", "text/plain");
  11647. });
  11648. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11649. auto se = detail::scope_exit([&] {
  11650. svr.stop();
  11651. listen_thread.join();
  11652. ASSERT_FALSE(svr.is_running());
  11653. });
  11654. svr.wait_until_ready();
  11655. Client cli("localhost", PORT);
  11656. cli.set_keep_alive(true);
  11657. cli.set_read_timeout(std::chrono::seconds(1));
  11658. auto resa = cli.Get("/a");
  11659. ASSERT_FALSE(resa);
  11660. EXPECT_EQ(Error::Read, resa.error());
  11661. auto resb = cli.Get("/b");
  11662. ASSERT_TRUE(resb);
  11663. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11664. EXPECT_EQ("b", resb->body);
  11665. }
  11666. TEST(KeepAliveTest, MaxCount) {
  11667. size_t keep_alive_max_count = 3;
  11668. Server svr;
  11669. svr.set_keep_alive_max_count(keep_alive_max_count);
  11670. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11671. res.set_content("Hello World!", "text/plain");
  11672. });
  11673. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11674. auto se = detail::scope_exit([&] {
  11675. svr.stop();
  11676. listen_thread.join();
  11677. ASSERT_FALSE(svr.is_running());
  11678. });
  11679. svr.wait_until_ready();
  11680. Client cli(HOST, PORT);
  11681. cli.set_keep_alive(true);
  11682. for (size_t i = 0; i < 5; i++) {
  11683. auto result = cli.Get("/hi");
  11684. ASSERT_TRUE(result);
  11685. EXPECT_EQ(StatusCode::OK_200, result->status);
  11686. if (i == keep_alive_max_count - 1) {
  11687. EXPECT_EQ("close", result->get_header_value("Connection"));
  11688. } else {
  11689. EXPECT_FALSE(result->has_header("Connection"));
  11690. }
  11691. }
  11692. }
  11693. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11694. // can pull the next one into the server's buffer. The server must serve it
  11695. // without waiting for the socket to become readable again. The keep-alive
  11696. // timeout outlasts the client's read timeout, so a request left waiting for it
  11697. // shows up as a missing response.
  11698. static void serve_pipelining_routes(Server &svr,
  11699. const std::function<void(int)> &client) {
  11700. svr.set_keep_alive_timeout(5);
  11701. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11702. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11703. });
  11704. svr.Post("/echo", [](const Request &req, Response &res) {
  11705. res.set_content("echo " + req.body, "text/plain");
  11706. });
  11707. auto port = svr.bind_to_any_port(HOST);
  11708. thread t = thread([&] { svr.listen_after_bind(); });
  11709. auto se = detail::scope_exit([&] {
  11710. svr.stop();
  11711. t.join();
  11712. });
  11713. svr.wait_until_ready();
  11714. client(port);
  11715. }
  11716. static std::string
  11717. send_pipelined_requests(const std::vector<std::string> &parts) {
  11718. Server svr;
  11719. std::string res;
  11720. serve_pipelining_routes(svr, [&](int port) {
  11721. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11722. });
  11723. return res;
  11724. }
  11725. static void expect_in_order(const std::string &res,
  11726. const std::vector<std::string> &bodies) {
  11727. size_t pos = 0;
  11728. for (const auto &body : bodies) {
  11729. pos = res.find(body, pos);
  11730. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11731. pos += body.size();
  11732. }
  11733. }
  11734. TEST(KeepAliveTest, PipelinedRequests) {
  11735. auto res = send_pipelined_requests(
  11736. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11737. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11738. "Content-Length: 4\r\n\r\nbody"
  11739. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11740. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11741. }
  11742. // The second request starts in the server's buffer and ends on the socket.
  11743. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11744. auto res =
  11745. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11746. "GET /hi/2 HTTP/1.1\r\nHo",
  11747. "st: localhost\r\nConnection: close\r\n\r\n"});
  11748. expect_in_order(res, {"hi 1", "hi 2"});
  11749. }
  11750. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11751. // CRLF after a body does not turn into a 400 for the next request.
  11752. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11753. auto res = send_pipelined_requests(
  11754. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11755. "Content-Length: 4\r\n\r\nbody\r\n"
  11756. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11757. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11758. expect_in_order(res, {"echo body", "hi 2"});
  11759. }
  11760. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11761. // must not be served as the next request.
  11762. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11763. auto res = send_pipelined_requests(
  11764. {"INVALID REQUEST LINE\r\n\r\n"
  11765. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11766. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11767. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11768. }
  11769. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11770. // Over TLS, the next request is held by the TLS library as already decrypted
  11771. // data rather than on the socket.
  11772. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11774. std::string res;
  11775. serve_pipelining_routes(svr, [&](int port) {
  11776. // One part, so all three requests arrive in one TLS record
  11777. EXPECT_TRUE(send_ssl_request_in_parts(
  11778. 2,
  11779. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11780. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11781. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11782. &res, port));
  11783. });
  11784. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11785. }
  11786. #endif
  11787. TEST(KeepAliveTest, Issue1041) {
  11788. Server svr;
  11789. svr.set_keep_alive_timeout(3);
  11790. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11791. res.set_content("Hello World!", "text/plain");
  11792. });
  11793. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11794. auto se = detail::scope_exit([&] {
  11795. svr.stop();
  11796. listen_thread.join();
  11797. ASSERT_FALSE(svr.is_running());
  11798. });
  11799. svr.wait_until_ready();
  11800. Client cli(HOST, PORT);
  11801. cli.set_keep_alive(true);
  11802. auto result = cli.Get("/hi");
  11803. ASSERT_TRUE(result);
  11804. EXPECT_EQ(StatusCode::OK_200, result->status);
  11805. std::this_thread::sleep_for(std::chrono::seconds(5));
  11806. result = cli.Get("/hi");
  11807. ASSERT_TRUE(result);
  11808. EXPECT_EQ(StatusCode::OK_200, result->status);
  11809. }
  11810. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11811. Server svr;
  11812. svr.set_keep_alive_max_count(0);
  11813. std::set<int> remote_ports;
  11814. svr.Get("/hi", [&](const Request &req, Response &res) {
  11815. remote_ports.insert(req.remote_port);
  11816. res.set_content("hi", "text/plain");
  11817. });
  11818. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11819. auto se = detail::scope_exit([&] {
  11820. svr.stop();
  11821. listen_thread.join();
  11822. ASSERT_FALSE(svr.is_running());
  11823. });
  11824. svr.wait_until_ready();
  11825. Client cli(HOST, PORT);
  11826. cli.set_keep_alive(true);
  11827. for (int i = 0; i < 3; i++) {
  11828. auto res = cli.Get("/hi");
  11829. ASSERT_TRUE(res);
  11830. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11831. }
  11832. // All three over one connection
  11833. EXPECT_EQ(1u, remote_ports.size());
  11834. }
  11835. // Forward declaration (see the base64_encode note).
  11836. namespace httplib {
  11837. namespace detail {
  11838. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11839. } // namespace detail
  11840. } // namespace httplib
  11841. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11842. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11843. #ifndef _WIN32
  11844. signal(SIGPIPE, SIG_IGN);
  11845. #endif
  11846. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11847. ASSERT_NE(INVALID_SOCKET, srv);
  11848. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11849. default_socket_options(srv);
  11850. sockaddr_in addr{};
  11851. addr.sin_family = AF_INET;
  11852. addr.sin_port = 0;
  11853. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11854. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11855. ASSERT_EQ(0, ::listen(srv, 2));
  11856. socklen_t addr_len = sizeof(addr);
  11857. ASSERT_EQ(0,
  11858. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11859. auto port = ntohs(addr.sin_port);
  11860. struct Peer {
  11861. socket_t sock = INVALID_SOCKET;
  11862. #ifdef CPPHTTPLIB_SSL_ENABLED
  11863. tls::session_t session = nullptr;
  11864. #endif
  11865. };
  11866. #ifdef CPPHTTPLIB_SSL_ENABLED
  11867. tls::ctx_t ctx = nullptr;
  11868. if (use_tls) {
  11869. ctx = tls::create_server_context();
  11870. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11871. nullptr);
  11872. }
  11873. auto ctx_se = detail::scope_exit([&] {
  11874. if (ctx) { tls::free_context(ctx); }
  11875. });
  11876. #endif
  11877. auto close_peer = [](Peer &peer) {
  11878. #ifdef CPPHTTPLIB_SSL_ENABLED
  11879. if (peer.session) { tls::free_session(peer.session); }
  11880. #endif
  11881. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11882. };
  11883. auto accept_peer = [&]() {
  11884. Peer peer;
  11885. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11886. peer.sock = ::accept(srv, nullptr, nullptr);
  11887. if (peer.sock == INVALID_SOCKET) { return peer; }
  11888. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11889. #ifdef CPPHTTPLIB_SSL_ENABLED
  11890. if (use_tls) {
  11891. peer.session = tls::create_session(ctx, peer.sock);
  11892. tls::TlsError err;
  11893. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err,
  11894. nullptr)) {
  11895. close_peer(peer);
  11896. return Peer();
  11897. }
  11898. }
  11899. #endif
  11900. return peer;
  11901. };
  11902. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11903. #ifdef CPPHTTPLIB_SSL_ENABLED
  11904. tls::TlsError err;
  11905. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11906. #endif
  11907. return detail::read_socket(peer.sock, buf, len, 0);
  11908. };
  11909. auto read_head = [&](const Peer &peer) {
  11910. std::string head;
  11911. char buf[1024];
  11912. while (head.find("\r\n\r\n") == std::string::npos) {
  11913. auto n = read_some(peer, buf, sizeof(buf));
  11914. if (n <= 0) { break; }
  11915. head.append(buf, static_cast<size_t>(n));
  11916. }
  11917. };
  11918. auto send_text = [](const Peer &peer, const std::string &text) {
  11919. #ifdef CPPHTTPLIB_SSL_ENABLED
  11920. tls::TlsError err;
  11921. if (peer.session) {
  11922. tls::write(peer.session, text.data(), text.size(), err);
  11923. return;
  11924. }
  11925. #endif
  11926. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11927. };
  11928. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11929. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11930. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11931. // Sent once the first response is read, so that it lands on an idle socket
  11932. std::promise<void> first_response_read;
  11933. auto first_response_read_future = first_response_read.get_future();
  11934. auto server_thread = std::thread([&] {
  11935. auto peer1 = accept_peer();
  11936. if (peer1.sock == INVALID_SOCKET) { return; }
  11937. read_head(peer1);
  11938. if (same_write) {
  11939. send_text(peer1, first + stray);
  11940. } else {
  11941. send_text(peer1, first);
  11942. first_response_read_future.wait_for(std::chrono::seconds(5));
  11943. send_text(peer1, stray);
  11944. }
  11945. // peer1 stays open, so only the unread data can tell the client
  11946. auto peer2 = accept_peer();
  11947. if (peer2.sock != INVALID_SOCKET) {
  11948. read_head(peer2);
  11949. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11950. "Connection: close\r\n\r\nsecond");
  11951. close_peer(peer2);
  11952. }
  11953. close_peer(peer1);
  11954. });
  11955. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11956. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11957. std::to_string(port));
  11958. #ifdef CPPHTTPLIB_SSL_ENABLED
  11959. cli.enable_server_certificate_verification(false);
  11960. #endif
  11961. cli.set_keep_alive(true);
  11962. cli.set_read_timeout(5, 0);
  11963. auto res = cli.Get("/1");
  11964. first_response_read.set_value();
  11965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11966. EXPECT_EQ("first", res->body);
  11967. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11968. res = cli.Get("/2");
  11969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11970. EXPECT_EQ(StatusCode::OK_200, res->status);
  11971. EXPECT_EQ("second", res->body);
  11972. }
  11973. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11974. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11975. }
  11976. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11977. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11978. }
  11979. #ifdef CPPHTTPLIB_SSL_ENABLED
  11980. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11981. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11982. }
  11983. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11984. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11985. }
  11986. #endif
  11987. TEST(KeepAliveTest, Issue1959) {
  11988. Server svr;
  11989. svr.set_keep_alive_timeout(5);
  11990. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11991. res.set_content("a", "text/plain");
  11992. });
  11993. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11994. auto se = detail::scope_exit([&] {
  11995. if (!svr.is_running()) return;
  11996. svr.stop();
  11997. listen_thread.join();
  11998. ASSERT_FALSE(svr.is_running());
  11999. });
  12000. svr.wait_until_ready();
  12001. Client cli("localhost", PORT);
  12002. cli.set_keep_alive(true);
  12003. using namespace std::chrono;
  12004. auto start = steady_clock::now();
  12005. cli.Get("/a");
  12006. svr.stop();
  12007. listen_thread.join();
  12008. auto end = steady_clock::now();
  12009. auto elapsed = duration_cast<milliseconds>(end - start).count();
  12010. EXPECT_LT(elapsed, 5000);
  12011. }
  12012. #ifdef CPPHTTPLIB_SSL_ENABLED
  12013. TEST(KeepAliveTest, SSLClientReconnection) {
  12014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12015. ASSERT_TRUE(svr.is_valid());
  12016. svr.set_keep_alive_timeout(1);
  12017. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  12018. res.set_content("Hello World!", "text/plain");
  12019. });
  12020. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12021. auto se = detail::scope_exit([&] {
  12022. svr.stop();
  12023. listen_thread.join();
  12024. ASSERT_FALSE(svr.is_running());
  12025. });
  12026. svr.wait_until_ready();
  12027. SSLClient cli(HOST, PORT);
  12028. cli.enable_server_certificate_verification(false);
  12029. cli.set_keep_alive(true);
  12030. auto result = cli.Get("/hi");
  12031. ASSERT_TRUE(result);
  12032. EXPECT_EQ(StatusCode::OK_200, result->status);
  12033. result = cli.Get("/hi");
  12034. ASSERT_TRUE(result);
  12035. EXPECT_EQ(StatusCode::OK_200, result->status);
  12036. std::this_thread::sleep_for(std::chrono::seconds(2));
  12037. // Recoonect
  12038. result = cli.Get("/hi");
  12039. ASSERT_TRUE(result);
  12040. EXPECT_EQ(StatusCode::OK_200, result->status);
  12041. result = cli.Get("/hi");
  12042. ASSERT_TRUE(result);
  12043. EXPECT_EQ(StatusCode::OK_200, result->status);
  12044. }
  12045. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  12046. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12047. ASSERT_TRUE(svr.is_valid());
  12048. svr.set_keep_alive_timeout(1);
  12049. std::string content = "reconnect";
  12050. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  12051. res.set_content("Hello World!", "text/plain");
  12052. });
  12053. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12054. auto se = detail::scope_exit([&] {
  12055. svr.stop();
  12056. listen_thread.join();
  12057. ASSERT_FALSE(svr.is_running());
  12058. });
  12059. svr.wait_until_ready();
  12060. SSLClient cli(HOST, PORT);
  12061. cli.enable_server_certificate_verification(false);
  12062. cli.set_keep_alive(true);
  12063. auto result = cli.Post(
  12064. "/hi", content.size(),
  12065. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12066. sink.write(content.c_str(), content.size());
  12067. return true;
  12068. },
  12069. "text/plain");
  12070. ASSERT_TRUE(result);
  12071. EXPECT_EQ(200, result->status);
  12072. std::this_thread::sleep_for(std::chrono::seconds(2));
  12073. // Recoonect
  12074. result = cli.Post(
  12075. "/hi", content.size(),
  12076. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12077. sink.write(content.c_str(), content.size());
  12078. return true;
  12079. },
  12080. "text/plain");
  12081. ASSERT_TRUE(result);
  12082. EXPECT_EQ(200, result->status);
  12083. result = cli.Post(
  12084. "/hi", content.size(),
  12085. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12086. sink.write(content.c_str(), content.size());
  12087. return true;
  12088. },
  12089. "text/plain");
  12090. ASSERT_TRUE(result);
  12091. EXPECT_EQ(200, result->status);
  12092. }
  12093. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  12094. using namespace httplib::tls;
  12095. {
  12096. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12097. ASSERT_TRUE(svr.is_valid());
  12098. svr.Get("/sni", [&](const Request &req, Response &res) {
  12099. std::string expected = req.sni();
  12100. EXPECT_EQ(expected, req.get_param_value("expected"));
  12101. res.set_content("ok", "text/plain");
  12102. });
  12103. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12104. auto se = detail::scope_exit([&] {
  12105. svr.stop();
  12106. listen_thread.join();
  12107. ASSERT_FALSE(svr.is_running());
  12108. });
  12109. svr.wait_until_ready();
  12110. {
  12111. SSLClient cli("localhost", PORT);
  12112. cli.enable_server_certificate_verification(false);
  12113. auto res = cli.Get("/sni?expected=localhost");
  12114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12115. }
  12116. {
  12117. SSLClient cli("::1", PORT);
  12118. cli.enable_server_certificate_verification(false);
  12119. auto res = cli.Get("/sni?expected=");
  12120. // NOTE: This may fail if the server is listening on IPv4 only
  12121. // (e.g., when localhost resolves to 127.0.0.1 only)
  12122. if (res) {
  12123. EXPECT_EQ(StatusCode::OK_200, res->status);
  12124. } else {
  12125. EXPECT_EQ(Error::Connection, res.error());
  12126. }
  12127. }
  12128. }
  12129. }
  12130. // The SNI of a failed handshake does not reach the next connection that the
  12131. // same worker thread serves
  12132. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  12133. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12134. ASSERT_TRUE(svr.is_valid());
  12135. svr.new_task_queue = [] { return new ThreadPool(1); };
  12136. svr.Get("/sni", [](const Request &req, Response &res) {
  12137. res.set_content(req.sni(), "text/plain");
  12138. });
  12139. auto port = svr.bind_to_any_port("127.0.0.1");
  12140. ASSERT_LT(0, port);
  12141. thread t = thread([&] { svr.listen_after_bind(); });
  12142. auto se = detail::scope_exit([&] {
  12143. svr.stop();
  12144. t.join();
  12145. ASSERT_FALSE(svr.is_running());
  12146. });
  12147. svr.wait_until_ready();
  12148. {
  12149. // Sends SNI, then rejects the server certificate, which the CA did not sign
  12150. SSLClient cli("localhost", port);
  12151. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  12152. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  12153. auto res = cli.Get("/sni");
  12154. ASSERT_FALSE(res);
  12155. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12156. }
  12157. // An IP host sends no SNI (RFC 6066)
  12158. SSLClient cli("127.0.0.1", port);
  12159. cli.enable_server_certificate_verification(false);
  12160. auto res = cli.Get("/sni");
  12161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12162. EXPECT_EQ("", res->body);
  12163. }
  12164. #endif
  12165. TEST(ClientProblemDetectionTest, ContentProvider) {
  12166. Server svr;
  12167. size_t content_length = 1024 * 1024;
  12168. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12169. res.set_content_provider(
  12170. content_length, "text/plain",
  12171. [&](size_t offset, size_t length, DataSink &sink) {
  12172. auto out_len = std::min(length, static_cast<size_t>(1024));
  12173. std::string out(out_len, '@');
  12174. sink.write(out.data(), out_len);
  12175. return offset < 4096;
  12176. },
  12177. [](bool success) { ASSERT_FALSE(success); });
  12178. });
  12179. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  12180. res.set_content_provider(
  12181. 0, "text/plain",
  12182. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  12183. EXPECT_TRUE(false);
  12184. return true;
  12185. },
  12186. [](bool success) { ASSERT_FALSE(success); });
  12187. });
  12188. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12189. auto se = detail::scope_exit([&] {
  12190. svr.stop();
  12191. listen_thread.join();
  12192. ASSERT_FALSE(svr.is_running());
  12193. });
  12194. svr.wait_until_ready();
  12195. Client cli("localhost", PORT);
  12196. {
  12197. auto res = cli.Get("/hi", [&](const char * /*data*/,
  12198. size_t /*data_length*/) { return false; });
  12199. ASSERT_FALSE(res);
  12200. }
  12201. {
  12202. auto res = cli.Get("/empty", [&](const char * /*data*/,
  12203. size_t /*data_length*/) { return false; });
  12204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12205. }
  12206. }
  12207. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  12208. // A provider that reports success without writing anything and without
  12209. // calling done() used to be handed the same offset and length again on every
  12210. // pass, so it spun for as long as the peer stayed connected.
  12211. Server svr;
  12212. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12213. res.set_content("ok", "text/plain");
  12214. });
  12215. auto port = svr.bind_to_any_port(HOST);
  12216. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  12217. auto se = detail::scope_exit([&] {
  12218. svr.stop();
  12219. listen_thread.join();
  12220. ASSERT_FALSE(svr.is_running());
  12221. });
  12222. svr.wait_until_ready();
  12223. std::atomic<int> call_count{0};
  12224. Client cli(HOST, port);
  12225. auto res = cli.Post(
  12226. "/", 1024,
  12227. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  12228. // Give up after enough passes to show the spin, so that losing the
  12229. // check below fails this test instead of hanging it.
  12230. return ++call_count < 100;
  12231. },
  12232. "text/plain");
  12233. ASSERT_FALSE(res);
  12234. EXPECT_EQ(Error::Write, res.error());
  12235. EXPECT_EQ(1, call_count.load());
  12236. }
  12237. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12238. // A writer only has to assign `write`. The other three used to be left as
  12239. // empty std::functions, so a provider calling one threw
  12240. // std::bad_function_call out of the thread running it and took the whole
  12241. // process down.
  12242. DataSink sink;
  12243. std::string written;
  12244. sink.write = [&](const char *data, size_t data_len) {
  12245. written.append(data, data_len);
  12246. return true;
  12247. };
  12248. EXPECT_TRUE(sink.is_writable());
  12249. sink.done();
  12250. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12251. EXPECT_TRUE(written.empty());
  12252. }
  12253. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12254. // A sink that cannot carry trailers still has to finish.
  12255. DataSink sink;
  12256. auto done_count = 0;
  12257. sink.done = [&]() { done_count++; };
  12258. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12259. EXPECT_EQ(1, done_count);
  12260. }
  12261. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12262. Server svr;
  12263. const std::string body(4096, 'x');
  12264. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12265. res.set_content_provider(body.size(), "text/plain",
  12266. [&](size_t offset, size_t length, DataSink &sink) {
  12267. sink.write(body.data() + offset, length);
  12268. sink.done();
  12269. return true;
  12270. });
  12271. });
  12272. auto port = svr.bind_to_any_port(HOST);
  12273. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12274. auto se = detail::scope_exit([&] {
  12275. svr.stop();
  12276. listen_thread.join();
  12277. ASSERT_FALSE(svr.is_running());
  12278. });
  12279. svr.wait_until_ready();
  12280. Client cli(HOST, port);
  12281. auto res = cli.Get("/");
  12282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12283. EXPECT_EQ(StatusCode::OK_200, res->status);
  12284. EXPECT_EQ(body, res->body);
  12285. }
  12286. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12287. Server svr;
  12288. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12289. res.set_content_provider(
  12290. 1024, "text/plain",
  12291. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12292. sink.write("hello", 5);
  12293. sink.done(); // short of the 1024 bytes the response promised
  12294. return true;
  12295. });
  12296. });
  12297. auto port = svr.bind_to_any_port(HOST);
  12298. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12299. auto se = detail::scope_exit([&] {
  12300. svr.stop();
  12301. listen_thread.join();
  12302. ASSERT_FALSE(svr.is_running());
  12303. });
  12304. svr.wait_until_ready();
  12305. Client cli(HOST, port);
  12306. cli.set_read_timeout(5, 0);
  12307. // The response is short of its Content-Length, so the client cannot read a
  12308. // complete body. What matters is that this returns at all: a no-op done()
  12309. // would leave the writer looping over a provider that never makes progress.
  12310. auto res = cli.Get("/");
  12311. EXPECT_FALSE(res);
  12312. }
  12313. // Read as the next response by a peer that sees it after a framed body.
  12314. static const std::string smuggled_response =
  12315. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12316. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12317. Server svr;
  12318. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12319. res.set_content_provider(
  12320. 5, "text/plain",
  12321. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12322. auto data = "AAAAA" + smuggled_response;
  12323. sink.write(data.data(), data.size());
  12324. return true;
  12325. });
  12326. });
  12327. thread t = thread([&] { svr.listen(HOST, PORT); });
  12328. auto se = detail::scope_exit([&] {
  12329. svr.stop();
  12330. t.join();
  12331. ASSERT_FALSE(svr.is_running());
  12332. });
  12333. svr.wait_until_ready();
  12334. std::string resp;
  12335. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12336. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12337. resp.clear();
  12338. ASSERT_TRUE(send_request(
  12339. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12340. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12341. }
  12342. TEST(NoContentTest, BodyIsNotSent) {
  12343. Server svr;
  12344. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12345. res.status = StatusCode::NoContent_204;
  12346. res.set_content(smuggled_response, "text/plain");
  12347. });
  12348. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12349. res.status = StatusCode::NotModified_304;
  12350. res.set_chunked_content_provider(
  12351. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12352. sink.write(smuggled_response.data(), smuggled_response.size());
  12353. sink.done();
  12354. return true;
  12355. });
  12356. });
  12357. thread t = thread([&] { svr.listen(HOST, PORT); });
  12358. auto se = detail::scope_exit([&] {
  12359. svr.stop();
  12360. t.join();
  12361. ASSERT_FALSE(svr.is_running());
  12362. });
  12363. svr.wait_until_ready();
  12364. for (auto path : {"/204", "/304"}) {
  12365. std::string resp;
  12366. ASSERT_TRUE(send_request(
  12367. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12368. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12369. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12370. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12371. }
  12372. }
  12373. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12374. Server svr;
  12375. std::atomic<bool> smuggled(false);
  12376. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12377. res.set_content("ok", "text/plain");
  12378. });
  12379. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12380. smuggled = true;
  12381. });
  12382. auto port = svr.bind_to_any_port(HOST);
  12383. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12384. auto se = detail::scope_exit([&] {
  12385. svr.stop();
  12386. listen_thread.join();
  12387. ASSERT_FALSE(svr.is_running());
  12388. });
  12389. svr.wait_until_ready();
  12390. // What follows the body would be read as the next request.
  12391. Client cli(HOST, port);
  12392. auto res = cli.Post(
  12393. "/", 5,
  12394. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12395. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12396. sink.write(data.data(), data.size());
  12397. return true;
  12398. },
  12399. "text/plain");
  12400. ASSERT_FALSE(res);
  12401. EXPECT_EQ(Error::Write, res.error());
  12402. EXPECT_FALSE(smuggled);
  12403. }
  12404. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12405. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12406. // The compressed path builds the whole body before connecting, so this
  12407. // fails client-side and never reaches a server.
  12408. Client cli(HOST, PORT);
  12409. cli.set_compress(true);
  12410. auto res = cli.Post(
  12411. "/", 1024,
  12412. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12413. sink.write("hello", 5);
  12414. sink.done(); // short of the 1024 bytes the request announced
  12415. return true;
  12416. },
  12417. "text/plain");
  12418. ASSERT_FALSE(res);
  12419. EXPECT_EQ(Error::Write, res.error());
  12420. }
  12421. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12422. Server svr;
  12423. std::string received;
  12424. size_t content_length_count = 0;
  12425. bool has_transfer_encoding = true;
  12426. svr.Post("/echo", [&](const Request &req, Response &res) {
  12427. received = req.body;
  12428. content_length_count = req.get_header_value_count("Content-Length");
  12429. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12430. res.set_content("ok", "text/plain");
  12431. });
  12432. svr.Get("/next", [](const Request &, Response &res) {
  12433. res.set_content("next", "text/plain");
  12434. });
  12435. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12436. auto se = detail::scope_exit([&] {
  12437. svr.stop();
  12438. listen_thread.join();
  12439. ASSERT_FALSE(svr.is_running());
  12440. });
  12441. svr.wait_until_ready();
  12442. Client cli(HOST, PORT);
  12443. cli.set_keep_alive(true);
  12444. cli.set_compress(true);
  12445. const std::string body = "hello world";
  12446. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12447. auto res = cli.Post("/echo", headers, body, "text/plain");
  12448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12449. EXPECT_EQ(StatusCode::OK_200, res->status);
  12450. EXPECT_EQ(body, received);
  12451. EXPECT_EQ(1u, content_length_count);
  12452. EXPECT_FALSE(has_transfer_encoding);
  12453. // The rest of a truncated body would be read as this request
  12454. auto res2 = cli.Get("/next");
  12455. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12456. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12457. EXPECT_EQ("next", res2->body);
  12458. }
  12459. #endif
  12460. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12461. Server svr;
  12462. std::string received;
  12463. size_t content_length_count = 1;
  12464. bool has_transfer_encoding = false;
  12465. svr.Post("/echo", [&](const Request &req, Response &res) {
  12466. received = req.body;
  12467. content_length_count = req.get_header_value_count("Content-Length");
  12468. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12469. res.set_content("ok", "text/plain");
  12470. });
  12471. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12472. auto se = detail::scope_exit([&] {
  12473. svr.stop();
  12474. listen_thread.join();
  12475. ASSERT_FALSE(svr.is_running());
  12476. });
  12477. svr.wait_until_ready();
  12478. Client cli(HOST, PORT);
  12479. cli.set_keep_alive(true);
  12480. const std::string body = "hello world";
  12481. Headers headers = {{"Content-Length", "5"}};
  12482. auto res = cli.Post(
  12483. "/echo", headers,
  12484. [&](size_t /*offset*/, DataSink &sink) {
  12485. sink.write(body.data(), body.size());
  12486. sink.done();
  12487. return true;
  12488. },
  12489. "text/plain");
  12490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12491. EXPECT_EQ(StatusCode::OK_200, res->status);
  12492. EXPECT_EQ(body, received);
  12493. EXPECT_EQ(0u, content_length_count);
  12494. EXPECT_TRUE(has_transfer_encoding);
  12495. }
  12496. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12497. Server svr;
  12498. svr.set_error_handler([](Request const &, Response &res) -> void {
  12499. res.set_chunked_content_provider(
  12500. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12501. sink.os << "hello";
  12502. sink.os << "world";
  12503. sink.done();
  12504. return true;
  12505. });
  12506. });
  12507. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12508. auto se = detail::scope_exit([&] {
  12509. svr.stop();
  12510. listen_thread.join();
  12511. ASSERT_FALSE(svr.is_running());
  12512. });
  12513. svr.wait_until_ready();
  12514. Client cli("localhost", PORT);
  12515. auto res = cli.Get("/");
  12516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12517. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12518. EXPECT_EQ("helloworld", res->body);
  12519. }
  12520. // A body set after a content provider must replace it, not be sent through it.
  12521. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12522. Server svr;
  12523. svr.set_mount_point("/", "./www");
  12524. svr.set_file_request_handler([](const Request &req, Response &res) {
  12525. if (req.path == "/dir/test.html") {
  12526. res.status = StatusCode::Forbidden_403;
  12527. res.set_content(std::string(5000, 'D'), "text/plain");
  12528. } else if (req.path == "/file") {
  12529. res.status = StatusCode::Forbidden_403;
  12530. res.body = "Denied";
  12531. }
  12532. });
  12533. auto port = svr.bind_to_any_port(HOST);
  12534. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12535. auto se = detail::scope_exit([&] {
  12536. svr.stop();
  12537. t.join();
  12538. ASSERT_FALSE(svr.is_running());
  12539. });
  12540. svr.wait_until_ready();
  12541. Client cli(HOST, port);
  12542. {
  12543. auto res = cli.Get("/dir/test.html");
  12544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12545. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12546. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12547. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12548. }
  12549. {
  12550. auto res = cli.Get("/file");
  12551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12552. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12553. EXPECT_EQ("Denied", res->body);
  12554. }
  12555. {
  12556. auto res = cli.Get("/dir/index.html");
  12557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12558. EXPECT_EQ(StatusCode::OK_200, res->status);
  12559. EXPECT_EQ(0U, res->body.find("<html>"));
  12560. }
  12561. }
  12562. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12563. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12564. Server svr;
  12565. std::vector<bool> released;
  12566. std::mutex released_mutex;
  12567. auto releaser = [&](bool success) {
  12568. std::lock_guard<std::mutex> guard(released_mutex);
  12569. released.push_back(success);
  12570. };
  12571. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12572. return sink.write(&"hello"[offset], length);
  12573. };
  12574. svr.Get("/sized", [&](const Request &, Response &res) {
  12575. res.status = StatusCode::NotFound_404;
  12576. res.set_content_provider(5, "text/plain", provider, releaser);
  12577. });
  12578. svr.Get("/chunked", [&](const Request &, Response &res) {
  12579. res.status = StatusCode::ServiceUnavailable_503;
  12580. res.set_chunked_content_provider(
  12581. "text/plain",
  12582. [](size_t, DataSink &sink) {
  12583. sink.os << "chunk";
  12584. sink.done();
  12585. return true;
  12586. },
  12587. releaser);
  12588. });
  12589. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12590. res.set_content_provider(5, "text/plain", provider, releaser);
  12591. throw std::runtime_error("after the provider");
  12592. });
  12593. svr.set_error_handler([](const Request &req, Response &res) {
  12594. // Leave the exception handler's content to it.
  12595. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12596. res.set_content(std::string(1000, 'E'), "text/html");
  12597. return Server::HandlerResponse::Handled;
  12598. });
  12599. svr.set_exception_handler(
  12600. [](const Request &, Response &res, std::exception_ptr) {
  12601. res.status = StatusCode::InternalServerError_500;
  12602. res.set_content(std::string(1000, 'X'), "text/html");
  12603. });
  12604. auto port = svr.bind_to_any_port(HOST);
  12605. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12606. auto se = detail::scope_exit([&] {
  12607. svr.stop();
  12608. t.join();
  12609. ASSERT_FALSE(svr.is_running());
  12610. });
  12611. svr.wait_until_ready();
  12612. Client cli(HOST, port);
  12613. {
  12614. auto res = cli.Get("/sized");
  12615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12616. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12617. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12618. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12619. }
  12620. {
  12621. auto res = cli.Get("/chunked");
  12622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12623. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12624. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12625. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12626. }
  12627. {
  12628. auto res = cli.Get("/throw");
  12629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12630. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12631. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12632. }
  12633. std::lock_guard<std::mutex> guard(released_mutex);
  12634. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12635. }
  12636. #endif
  12637. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12638. Server svr;
  12639. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12640. return sink.write(&"abc"[offset], length);
  12641. };
  12642. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12643. res.set_file_content("./www/dir/test.html");
  12644. res.set_content("body", "text/plain");
  12645. });
  12646. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12647. res.set_content(std::string(100, 'B'), "text/plain");
  12648. res.set_file_content("./www/dir/test.html");
  12649. });
  12650. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12651. res.set_content(std::string(100, 'B'), "text/plain");
  12652. res.set_content_provider(3, "text/x-provider", abc);
  12653. });
  12654. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12655. res.set_content_provider(3, "text/x-provider", abc);
  12656. res.set_content(std::string(100, 'B'), "text/plain");
  12657. });
  12658. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12659. res.set_content_provider(3, "text/x-provider", abc);
  12660. res.set_file_content("./www/dir/test.html", "text/x-file");
  12661. });
  12662. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12663. res.set_file_content("./www/dir/test.html");
  12664. res.set_header("Content-Type", "text/x-handler");
  12665. });
  12666. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12667. res.set_content_provider(3, "text/plain", abc);
  12668. res.body = "direct";
  12669. });
  12670. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12671. res.set_file_content("./www/dir/test.html");
  12672. res.body = "direct";
  12673. });
  12674. auto port = svr.bind_to_any_port(HOST);
  12675. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12676. auto se = detail::scope_exit([&] {
  12677. svr.stop();
  12678. t.join();
  12679. ASSERT_FALSE(svr.is_running());
  12680. });
  12681. svr.wait_until_ready();
  12682. Client cli(HOST, port);
  12683. auto expect_body = [&](const char *path, const std::string &body,
  12684. const std::string &type) {
  12685. // Uncompressed, so Content-Length can be compared with the body.
  12686. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12687. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12688. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12689. EXPECT_EQ(body, res->body) << path;
  12690. EXPECT_EQ(std::to_string(body.size()),
  12691. res->get_header_value("Content-Length"))
  12692. << path;
  12693. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12694. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12695. };
  12696. expect_body("/file-then-body", "body", "text/plain");
  12697. expect_body("/body-then-file", "test.html", "text/html");
  12698. expect_body("/body-then-provider", "abc", "text/x-provider");
  12699. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12700. expect_body("/provider-then-file", "test.html", "text/x-file");
  12701. expect_body("/file-then-header", "test.html", "text/x-handler");
  12702. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12703. expect_body("/file-then-direct-body", "direct", "text/plain");
  12704. // Ranges are checked against the body, not the dropped provider.
  12705. {
  12706. auto res = cli.Get("/provider-then-direct-body",
  12707. Headers{{make_range_header({{1, 2}})}});
  12708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12709. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12710. EXPECT_EQ("ir", res->body);
  12711. }
  12712. {
  12713. auto res = cli.Get("/file-then-direct-body",
  12714. Headers{{make_range_header({{7, 8}})}});
  12715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12716. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12717. }
  12718. }
  12719. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12720. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12721. const char *path = "./truncated_while_served.txt";
  12722. const size_t size = 32 * 1024 * 1024;
  12723. {
  12724. std::ofstream f(path, std::ios::binary);
  12725. f << std::string(size, 'x');
  12726. }
  12727. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12728. // Over TLS, where the bytes are encrypted in this process rather than
  12729. // copied by send().
  12730. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12731. svr.Get("/file", [&](const Request &, Response &res) {
  12732. res.set_file_content(path, "text/plain");
  12733. });
  12734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12735. auto se = detail::scope_exit([&] {
  12736. svr.stop();
  12737. thread.join();
  12738. ASSERT_FALSE(svr.is_running());
  12739. });
  12740. svr.wait_until_ready();
  12741. // The file shrinks once the first bytes are in, as a rewrite in place
  12742. // would, and reading the mapping past its new end used to raise SIGBUS.
  12743. SSLClient cli(HOST, PORT);
  12744. cli.enable_server_certificate_verification(false);
  12745. size_t received = 0;
  12746. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12747. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12748. received += len;
  12749. return true;
  12750. });
  12751. EXPECT_FALSE(res);
  12752. EXPECT_LT(received, size);
  12753. }
  12754. #endif
  12755. // Forward declaration (see the base64_encode note).
  12756. namespace httplib {
  12757. namespace detail {
  12758. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12759. const std::string &content_type,
  12760. EncodingType encoding);
  12761. } // namespace detail
  12762. } // namespace httplib
  12763. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12764. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12765. ASSERT_TRUE(mm->is_open());
  12766. Response res;
  12767. detail::set_file_content_provider(res, mm, "text/html",
  12768. detail::EncodingType::None);
  12769. std::string out;
  12770. DataSink sink;
  12771. sink.write = [&](const char *d, size_t l) {
  12772. out.append(d, l);
  12773. return true;
  12774. };
  12775. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12776. EXPECT_EQ("test.html", out);
  12777. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12778. EXPECT_EQ("test.html", out);
  12779. }
  12780. TEST(LongPollingTest, ClientCloseDetection) {
  12781. Server svr;
  12782. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12783. res.set_chunked_content_provider(
  12784. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12785. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12786. sink.os << "hello";
  12787. auto count = 10;
  12788. while (count > 0 && sink.is_writable()) {
  12789. this_thread::sleep_for(chrono::milliseconds(10));
  12790. count--;
  12791. }
  12792. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12793. return true;
  12794. });
  12795. });
  12796. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12797. auto se = detail::scope_exit([&] {
  12798. svr.stop();
  12799. listen_thread.join();
  12800. ASSERT_FALSE(svr.is_running());
  12801. });
  12802. svr.wait_until_ready();
  12803. Client cli("localhost", PORT);
  12804. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12805. EXPECT_EQ("hello", string(data, data_length));
  12806. return false; // close the socket immediately.
  12807. });
  12808. ASSERT_FALSE(res);
  12809. }
  12810. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12811. Server svr;
  12812. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12813. res.set_chunked_content_provider(
  12814. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12815. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12816. sink.os << "hello";
  12817. EXPECT_TRUE(sink.os.good());
  12818. // Wait for the client to close the connection
  12819. auto count = 10;
  12820. while (count > 0 && sink.is_writable()) {
  12821. this_thread::sleep_for(chrono::milliseconds(10));
  12822. count--;
  12823. }
  12824. // After client disconnect, write repeatedly until the socket
  12825. // write actually fails (small writes may be absorbed by the
  12826. // kernel buffer)
  12827. std::string chunk(1024, 'x');
  12828. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12829. sink.os << chunk;
  12830. }
  12831. EXPECT_TRUE(sink.os.fail());
  12832. return true;
  12833. });
  12834. });
  12835. auto port = svr.bind_to_any_port("localhost");
  12836. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12837. auto se = detail::scope_exit([&] {
  12838. svr.stop();
  12839. listen_thread.join();
  12840. ASSERT_FALSE(svr.is_running());
  12841. });
  12842. svr.wait_until_ready();
  12843. Client cli("localhost", port);
  12844. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12845. EXPECT_EQ("hello", string(data, data_length));
  12846. return false; // close the socket immediately.
  12847. });
  12848. ASSERT_FALSE(res);
  12849. }
  12850. TEST(GetWithParametersTest, GetWithParameters) {
  12851. Server svr;
  12852. svr.Get("/", [&](const Request &req, Response &) {
  12853. EXPECT_EQ("world", req.get_param_value("hello"));
  12854. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12855. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12856. });
  12857. svr.Get("/params", [&](const Request &req, Response &) {
  12858. EXPECT_EQ("world", req.get_param_value("hello"));
  12859. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12860. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12861. });
  12862. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12863. EXPECT_EQ("resource-id", req.matches[1]);
  12864. EXPECT_EQ("foo", req.get_param_value("param1"));
  12865. EXPECT_EQ("bar", req.get_param_value("param2"));
  12866. });
  12867. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12868. EXPECT_EQ("user-id", req.path_params.at("id"));
  12869. EXPECT_EQ("foo", req.get_param_value("param1"));
  12870. EXPECT_EQ("bar", req.get_param_value("param2"));
  12871. });
  12872. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12873. auto se = detail::scope_exit([&] {
  12874. svr.stop();
  12875. listen_thread.join();
  12876. ASSERT_FALSE(svr.is_running());
  12877. });
  12878. svr.wait_until_ready();
  12879. {
  12880. Client cli(HOST, PORT);
  12881. Params params;
  12882. params.emplace("hello", "world");
  12883. params.emplace("hello2", "world2");
  12884. params.emplace("hello3", "world3");
  12885. auto res = cli.Get("/", params, Headers{});
  12886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12887. EXPECT_EQ(StatusCode::OK_200, res->status);
  12888. }
  12889. {
  12890. Client cli(HOST, PORT);
  12891. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12893. EXPECT_EQ(StatusCode::OK_200, res->status);
  12894. }
  12895. {
  12896. Client cli(HOST, PORT);
  12897. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12899. EXPECT_EQ(StatusCode::OK_200, res->status);
  12900. }
  12901. {
  12902. Client cli(HOST, PORT);
  12903. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12905. EXPECT_EQ(StatusCode::OK_200, res->status);
  12906. }
  12907. }
  12908. TEST(GetWithParametersTest, GetWithParameters2) {
  12909. Server svr;
  12910. svr.Get("/", [&](const Request &req, Response &res) {
  12911. auto text = req.get_param_value("hello");
  12912. res.set_content(text, "text/plain");
  12913. });
  12914. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12915. auto se = detail::scope_exit([&] {
  12916. svr.stop();
  12917. listen_thread.join();
  12918. ASSERT_FALSE(svr.is_running());
  12919. });
  12920. svr.wait_until_ready();
  12921. Client cli("localhost", PORT);
  12922. Params params;
  12923. params.emplace("hello", "world");
  12924. std::string body;
  12925. auto res = cli.Get("/", params, Headers{},
  12926. [&](const char *data, size_t data_length) {
  12927. body.append(data, data_length);
  12928. return true;
  12929. });
  12930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12931. EXPECT_EQ(StatusCode::OK_200, res->status);
  12932. EXPECT_EQ("world", body);
  12933. }
  12934. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12935. Server svr;
  12936. svr.Get("/search", [&](const Request &req, Response &res) {
  12937. auto q = req.get_param_value("q");
  12938. res.set_content(q, "text/plain");
  12939. });
  12940. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12941. auto se = detail::scope_exit([&] {
  12942. svr.stop();
  12943. listen_thread.join();
  12944. ASSERT_FALSE(svr.is_running());
  12945. });
  12946. svr.wait_until_ready();
  12947. Client cli("localhost", PORT);
  12948. // Verify that Get(path, params) works without requiring Headers argument
  12949. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12951. EXPECT_EQ(StatusCode::OK_200, res->status);
  12952. EXPECT_EQ("cpp-httplib", res->body);
  12953. }
  12954. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12955. auto host = "httpbingo.org";
  12956. auto path = std::string{"/range/32"};
  12957. #ifdef CPPHTTPLIB_SSL_ENABLED
  12958. SSLClient cli(host);
  12959. #else
  12960. Client cli(host);
  12961. #endif
  12962. cli.set_default_headers({make_range_header({{1, 10}})});
  12963. cli.set_connection_timeout(5);
  12964. {
  12965. auto res = retry_service_failures([&] { return cli.Get(path); });
  12966. SKIP_ON_SERVICE_FAILURE(res);
  12967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12968. EXPECT_EQ("bcdefghijk", res->body);
  12969. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12970. }
  12971. {
  12972. auto res = retry_service_failures([&] { return cli.Get(path); });
  12973. SKIP_ON_SERVICE_FAILURE(res);
  12974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12975. EXPECT_EQ("bcdefghijk", res->body);
  12976. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12977. }
  12978. }
  12979. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12980. Server svr;
  12981. svr.set_default_headers({{"Hello", "World"}});
  12982. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12983. res.set_content("ok", "text/plain");
  12984. });
  12985. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12986. auto se = detail::scope_exit([&] {
  12987. svr.stop();
  12988. listen_thread.join();
  12989. ASSERT_FALSE(svr.is_running());
  12990. });
  12991. svr.wait_until_ready();
  12992. Client cli("localhost", PORT);
  12993. auto res = cli.Get("/");
  12994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12995. EXPECT_EQ(StatusCode::OK_200, res->status);
  12996. EXPECT_EQ("ok", res->body);
  12997. EXPECT_EQ("World", res->get_header_value("Hello"));
  12998. }
  12999. #ifdef CPPHTTPLIB_SSL_ENABLED
  13000. TEST(KeepAliveTest, ReadTimeoutSSL) {
  13001. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13002. ASSERT_TRUE(svr.is_valid());
  13003. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  13004. std::this_thread::sleep_for(std::chrono::seconds(2));
  13005. res.set_content("a", "text/plain");
  13006. });
  13007. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  13008. res.set_content("b", "text/plain");
  13009. });
  13010. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  13011. auto se = detail::scope_exit([&] {
  13012. svr.stop();
  13013. listen_thread.join();
  13014. ASSERT_FALSE(svr.is_running());
  13015. });
  13016. svr.wait_until_ready();
  13017. SSLClient cli("localhost", PORT);
  13018. cli.enable_server_certificate_verification(false);
  13019. cli.set_keep_alive(true);
  13020. cli.set_read_timeout(std::chrono::seconds(1));
  13021. auto resa = cli.Get("/a");
  13022. ASSERT_TRUE(!resa);
  13023. EXPECT_EQ(Error::Read, resa.error());
  13024. auto resb = cli.Get("/b");
  13025. ASSERT_TRUE(resb);
  13026. EXPECT_EQ(StatusCode::OK_200, resb->status);
  13027. EXPECT_EQ("b", resb->body);
  13028. }
  13029. // Closing an idle keep-alive connection sends close_notify and returns. The
  13030. // server must not wait for the client's close_notify: an idle client never
  13031. // sends one, so the worker would be held until the read timeout expires, and
  13032. // stop() would wait for it.
  13033. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  13034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13035. ASSERT_TRUE(svr.is_valid());
  13036. svr.set_keep_alive_timeout(1);
  13037. svr.set_read_timeout(10, 0);
  13038. svr.Get("/", [](const Request &, Response &res) {
  13039. res.set_content("ok", "text/plain");
  13040. });
  13041. auto port = svr.bind_to_any_port(HOST);
  13042. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  13043. auto se = detail::scope_exit([&] {
  13044. if (listen_thread.joinable()) {
  13045. svr.stop();
  13046. listen_thread.join();
  13047. }
  13048. });
  13049. svr.wait_until_ready();
  13050. SSLClient cli(HOST, port);
  13051. cli.enable_server_certificate_verification(false);
  13052. cli.set_keep_alive(true);
  13053. auto res = cli.Get("/");
  13054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13055. EXPECT_EQ(StatusCode::OK_200, res->status);
  13056. // Stay idle past the keep-alive timeout so the server closes the connection.
  13057. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  13058. auto start = std::chrono::steady_clock::now();
  13059. svr.stop();
  13060. listen_thread.join();
  13061. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  13062. std::chrono::steady_clock::now() - start)
  13063. .count();
  13064. EXPECT_LT(elapsed, 3000);
  13065. }
  13066. #endif
  13067. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  13068. protected:
  13069. ServerTestWithAI_PASSIVE()
  13070. : cli_(HOST, PORT)
  13071. #ifdef CPPHTTPLIB_SSL_ENABLED
  13072. ,
  13073. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13074. #endif
  13075. {
  13076. #ifdef CPPHTTPLIB_SSL_ENABLED
  13077. cli_.enable_server_certificate_verification(false);
  13078. #endif
  13079. }
  13080. virtual void SetUp() {
  13081. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  13082. res.set_content("Hello World!", "text/plain");
  13083. });
  13084. t_ = thread(
  13085. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  13086. svr_.wait_until_ready();
  13087. }
  13088. virtual void TearDown() {
  13089. svr_.stop();
  13090. t_.join();
  13091. }
  13092. #ifdef CPPHTTPLIB_SSL_ENABLED
  13093. SSLClient cli_;
  13094. SSLServer svr_;
  13095. #else
  13096. Client cli_;
  13097. Server svr_;
  13098. #endif
  13099. thread t_;
  13100. };
  13101. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  13102. auto res = cli_.Get("/hi");
  13103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13104. EXPECT_EQ(StatusCode::OK_200, res->status);
  13105. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  13106. EXPECT_EQ("Hello World!", res->body);
  13107. }
  13108. class ServerUpDownTest : public ::testing::Test {
  13109. protected:
  13110. ServerUpDownTest() : cli_(HOST, PORT) {}
  13111. virtual void SetUp() {
  13112. t_ = thread([&]() {
  13113. svr_.bind_to_any_port(HOST);
  13114. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13115. ASSERT_TRUE(svr_.listen_after_bind());
  13116. });
  13117. svr_.wait_until_ready();
  13118. }
  13119. virtual void TearDown() {
  13120. svr_.stop();
  13121. t_.join();
  13122. }
  13123. Client cli_;
  13124. Server svr_;
  13125. thread t_;
  13126. };
  13127. TEST_F(ServerUpDownTest, QuickStartStop) {
  13128. // Should not crash, especially when run with
  13129. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  13130. }
  13131. class PayloadMaxLengthTest : public ::testing::Test {
  13132. protected:
  13133. PayloadMaxLengthTest()
  13134. : cli_(HOST, PORT)
  13135. #ifdef CPPHTTPLIB_SSL_ENABLED
  13136. ,
  13137. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13138. #endif
  13139. {
  13140. #ifdef CPPHTTPLIB_SSL_ENABLED
  13141. cli_.enable_server_certificate_verification(false);
  13142. #endif
  13143. }
  13144. virtual void SetUp() {
  13145. svr_.set_payload_max_length(8);
  13146. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13147. res.set_content("test", "text/plain");
  13148. });
  13149. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13150. svr_.wait_until_ready();
  13151. }
  13152. virtual void TearDown() {
  13153. svr_.stop();
  13154. t_.join();
  13155. }
  13156. #ifdef CPPHTTPLIB_SSL_ENABLED
  13157. SSLClient cli_;
  13158. SSLServer svr_;
  13159. #else
  13160. Client cli_;
  13161. Server svr_;
  13162. #endif
  13163. thread t_;
  13164. };
  13165. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  13166. auto res = cli_.Post("/test", "123456789", "text/plain");
  13167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13168. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13169. res = cli_.Post("/test", "12345678", "text/plain");
  13170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13171. EXPECT_EQ(StatusCode::OK_200, res->status);
  13172. }
  13173. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  13174. // Test chunked encoding with payload exceeding the 8-byte limit
  13175. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  13176. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  13177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13178. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13179. }
  13180. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  13181. // Test chunked encoding with payload within the 8-byte limit
  13182. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  13183. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  13184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13185. EXPECT_EQ(StatusCode::OK_200, res->status);
  13186. }
  13187. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  13188. // Test using send_request to send chunked data exceeding payload limit
  13189. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  13190. "Host: " +
  13191. std::string(HOST) + ":" + std::to_string(PORT) +
  13192. "\r\n"
  13193. "Transfer-Encoding: chunked\r\n"
  13194. "Connection: close\r\n"
  13195. "\r\n"
  13196. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  13197. "0123456789\r\n"
  13198. "0\r\n" // End chunk
  13199. "\r\n";
  13200. std::string response;
  13201. bool result = send_request(1, chunked_request, &response);
  13202. if (!result) {
  13203. // If send_request fails, it might be because the server closed the
  13204. // connection due to payload limit enforcement, which is acceptable
  13205. SUCCEED()
  13206. << "Server rejected oversized chunked request (connection closed)";
  13207. } else {
  13208. // If we got a response, check if it's an error response or connection was
  13209. // closed early Short response length indicates connection was closed due to
  13210. // payload limit
  13211. if (response.length() <= 10) {
  13212. SUCCEED() << "Server closed connection for oversized chunked request";
  13213. } else {
  13214. // Check for error status codes
  13215. EXPECT_TRUE(response.find("413") != std::string::npos ||
  13216. response.find("Payload Too Large") != std::string::npos ||
  13217. response.find("400") != std::string::npos);
  13218. }
  13219. }
  13220. }
  13221. class LargePayloadMaxLengthTest : public ::testing::Test {
  13222. protected:
  13223. LargePayloadMaxLengthTest()
  13224. : cli_(HOST, PORT)
  13225. #ifdef CPPHTTPLIB_SSL_ENABLED
  13226. ,
  13227. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13228. #endif
  13229. {
  13230. #ifdef CPPHTTPLIB_SSL_ENABLED
  13231. cli_.enable_server_certificate_verification(false);
  13232. #endif
  13233. }
  13234. virtual void SetUp() {
  13235. // Set 10MB payload limit
  13236. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13237. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13238. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13239. res.set_content("Large payload test", "text/plain");
  13240. });
  13241. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13242. svr_.wait_until_ready();
  13243. }
  13244. virtual void TearDown() {
  13245. svr_.stop();
  13246. t_.join();
  13247. }
  13248. #ifdef CPPHTTPLIB_SSL_ENABLED
  13249. SSLClient cli_;
  13250. SSLServer svr_;
  13251. #else
  13252. Client cli_;
  13253. Server svr_;
  13254. #endif
  13255. thread t_;
  13256. };
  13257. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13258. // Test chunked encoding with payload within 10MB limit
  13259. std::string medium_payload(5 * 1024 * 1024,
  13260. 'A'); // 5MB payload, within 10MB limit
  13261. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13263. EXPECT_EQ(StatusCode::OK_200, res->status);
  13264. }
  13265. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13266. // Test chunked encoding with payload exceeding 10MB limit
  13267. std::string large_payload(12 * 1024 * 1024,
  13268. 'B'); // 12MB payload, exceeds 10MB limit
  13269. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13270. // Server may either return 413 or close the connection
  13271. if (res) {
  13272. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13273. } else {
  13274. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13275. }
  13276. }
  13277. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13278. Server svr;
  13279. svr.Get("/", [](const Request &, Response &res) {
  13280. // Claims the most the client accepts, far more than it sends, then drops
  13281. // the connection.
  13282. res.set_content_provider(std::string().max_size(), "text/plain",
  13283. [](size_t, size_t, DataSink &sink) {
  13284. sink.write("abc", 3);
  13285. return false;
  13286. });
  13287. });
  13288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13289. auto se = detail::scope_exit([&] {
  13290. svr.stop();
  13291. thread.join();
  13292. ASSERT_FALSE(svr.is_running());
  13293. });
  13294. svr.wait_until_ready();
  13295. Client cli(HOST, PORT);
  13296. cli.set_payload_max_length(0);
  13297. EXPECT_FALSE(cli.Get("/"));
  13298. }
  13299. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13300. // Stream API does, not as a plain read failure
  13301. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13302. Server svr;
  13303. svr.Get("/big", [](const Request &, Response &res) {
  13304. res.set_content(std::string(100000, 'b'), "text/plain");
  13305. });
  13306. auto port = svr.bind_to_any_port(HOST);
  13307. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13308. auto se = detail::scope_exit([&] {
  13309. svr.stop();
  13310. thread.join();
  13311. });
  13312. svr.wait_until_ready();
  13313. Client cli(HOST, port);
  13314. cli.set_payload_max_length(1000);
  13315. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13316. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13317. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13318. [](const char *, size_t) { return true; });
  13319. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13320. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13321. // Small on the wire, over the limit once decompressed
  13322. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13323. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13324. #endif
  13325. }
  13326. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13327. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13328. // path.
  13329. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13330. Server svr;
  13331. const size_t LIMIT = 64 * 1024; // 64KB
  13332. svr.set_payload_max_length(LIMIT);
  13333. size_t total = 0;
  13334. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13335. const ContentReader &content_reader) {
  13336. content_reader([&](const char * /*data*/, size_t len) {
  13337. total += len;
  13338. return true;
  13339. });
  13340. res.status = 200;
  13341. res.set_content("stream_ok", "text/plain");
  13342. });
  13343. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13344. auto se = detail::scope_exit([&] {
  13345. svr.stop();
  13346. thread.join();
  13347. ASSERT_FALSE(svr.is_running());
  13348. });
  13349. svr.wait_until_ready();
  13350. // Prepare 256KB raw data and gzip-compress it
  13351. std::string raw(256 * 1024, 'A');
  13352. std::string gz;
  13353. {
  13354. z_stream zs{};
  13355. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13356. Z_DEFAULT_STRATEGY);
  13357. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13358. zs.avail_in = static_cast<uInt>(raw.size());
  13359. char outbuf[4096];
  13360. int ret;
  13361. do {
  13362. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13363. zs.avail_out = sizeof(outbuf);
  13364. ret = deflate(&zs, Z_FINISH);
  13365. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13366. } while (ret != Z_STREAM_END);
  13367. deflateEnd(&zs);
  13368. }
  13369. Client cli(HOST, PORT);
  13370. cli.set_connection_timeout(std::chrono::seconds(5));
  13371. Headers headers = {{"Content-Encoding", "gzip"}};
  13372. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13373. "application/octet-stream");
  13374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13375. // Server must reject oversized decompressed payloads with 413.
  13376. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13377. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13378. EXPECT_LE(total, LIMIT);
  13379. }
  13380. #endif
  13381. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13382. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13383. // the payload must be passed through untouched instead of being rejected.
  13384. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13385. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13386. Server svr;
  13387. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13388. res.set_content(body, "image/jpeg");
  13389. res.set_header("Content-Encoding", "UTF-8");
  13390. });
  13391. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13392. res.set_content(body, "image/jpeg");
  13393. res.set_header("Content-Encoding", "identity");
  13394. });
  13395. svr.Post("/echo", [](const Request &req, Response &res) {
  13396. res.set_content(req.body, "image/jpeg");
  13397. });
  13398. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13399. auto se = detail::scope_exit([&] {
  13400. svr.stop();
  13401. t.join();
  13402. ASSERT_FALSE(svr.is_running());
  13403. });
  13404. svr.wait_until_ready();
  13405. Client cli(HOST, PORT);
  13406. {
  13407. auto res = cli.Get("/image");
  13408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13409. EXPECT_EQ(StatusCode::OK_200, res->status);
  13410. EXPECT_EQ(body, res->body);
  13411. }
  13412. {
  13413. auto res = cli.Get("/identity");
  13414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13415. EXPECT_EQ(StatusCode::OK_200, res->status);
  13416. EXPECT_EQ(body, res->body);
  13417. }
  13418. {
  13419. // The same applies to a request body reaching the server.
  13420. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13421. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13423. EXPECT_EQ(StatusCode::OK_200, res->status);
  13424. EXPECT_EQ(body, res->body);
  13425. }
  13426. }
  13427. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13428. // gzip-encoded response even when the build has no zlib support.
  13429. static const char GZIPPED_HELLO_WORLD[] = {
  13430. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13431. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13432. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13433. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13434. // A content coding is a whole token, not something the field value merely
  13435. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13436. // as "fibre" look like Brotli, and turned a multi-coding value like
  13437. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13438. // it was never meant to see.
  13439. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13440. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13441. Server svr;
  13442. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13443. res.set_content(body, "image/jpeg");
  13444. res.set_header("Content-Encoding", "fibre");
  13445. });
  13446. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13447. res.set_content(body, "image/jpeg");
  13448. res.set_header("Content-Encoding", "gzip, br");
  13449. });
  13450. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13451. res.set_content(body, "image/jpeg");
  13452. res.set_header("Content-Encoding", "x-zstd-ish");
  13453. });
  13454. auto port = svr.bind_to_any_port(HOST);
  13455. thread t = thread([&]() { svr.listen_after_bind(); });
  13456. auto se = detail::scope_exit([&] {
  13457. svr.stop();
  13458. t.join();
  13459. ASSERT_FALSE(svr.is_running());
  13460. });
  13461. svr.wait_until_ready();
  13462. Client cli(HOST, port);
  13463. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13464. auto res = cli.Get(path);
  13465. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13466. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13467. // Not a coding we recognize, so the payload comes back untouched
  13468. EXPECT_EQ(body, res->body) << path;
  13469. }
  13470. }
  13471. // A content coding cpp-httplib recognizes but was not built with must be
  13472. // reported as such. Handing the still-compressed payload back to the caller
  13473. // would silently corrupt it.
  13474. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13475. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13476. Server svr;
  13477. // "image/jpeg" keeps the server from applying a content coding of its own,
  13478. // so the hand-crafted Content-Encoding below survives.
  13479. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13480. res.set_content(gzipped, "image/jpeg");
  13481. res.set_header("Content-Encoding", "gzip");
  13482. });
  13483. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13484. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13485. res.set_content(gzipped, "image/jpeg");
  13486. res.set_header("Content-Encoding", "GZIP");
  13487. });
  13488. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13489. auto se = detail::scope_exit([&] {
  13490. svr.stop();
  13491. t.join();
  13492. ASSERT_FALSE(svr.is_running());
  13493. });
  13494. svr.wait_until_ready();
  13495. Client cli(HOST, PORT);
  13496. {
  13497. auto res = cli.Get("/gzipped");
  13498. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13500. EXPECT_EQ("Hello World!", res->body);
  13501. #else
  13502. ASSERT_FALSE(res);
  13503. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13504. #endif
  13505. }
  13506. {
  13507. // open_stream() must behave the same way.
  13508. auto handle = cli.open_stream("GET", "/gzipped");
  13509. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13510. ASSERT_TRUE(handle.is_valid());
  13511. std::string received;
  13512. char buf[256];
  13513. ssize_t n;
  13514. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13515. received.append(buf, static_cast<size_t>(n));
  13516. }
  13517. EXPECT_EQ("Hello World!", received);
  13518. #else
  13519. EXPECT_FALSE(handle.is_valid());
  13520. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13521. #endif
  13522. }
  13523. {
  13524. // A differently-cased coding must not be mistaken for an unknown one, or
  13525. // the body would be handed back still compressed.
  13526. auto res = cli.Get("/gzipped-uppercase");
  13527. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13529. EXPECT_EQ("Hello World!", res->body);
  13530. #else
  13531. ASSERT_FALSE(res);
  13532. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13533. #endif
  13534. }
  13535. }
  13536. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13537. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13538. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13539. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13540. // body a second time and appending a second Content-Encoding field line, so
  13541. // clients that decode one coding per listed value handed back raw gzip bytes.
  13542. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13543. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13544. Server svr;
  13545. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13546. // keeps the server from applying a coding of its own.
  13547. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13548. res.set_content(gzipped, "text/plain");
  13549. res.set_header("Content-Encoding", "gzip");
  13550. });
  13551. auto port = svr.bind_to_any_port(HOST);
  13552. thread t = thread([&]() { svr.listen_after_bind(); });
  13553. auto se = detail::scope_exit([&] {
  13554. svr.stop();
  13555. t.join();
  13556. ASSERT_FALSE(svr.is_running());
  13557. });
  13558. svr.wait_until_ready();
  13559. Client cli(HOST, port);
  13560. Headers headers = {{"Accept-Encoding", "gzip"}};
  13561. auto res = cli.Get("/pre-gzipped", headers);
  13562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13563. EXPECT_EQ(StatusCode::OK_200, res->status);
  13564. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13565. EXPECT_EQ("Hello World!", res->body);
  13566. }
  13567. // set_compress(false) sends every handler response as it is, buffered or
  13568. // streamed
  13569. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13570. const std::string text(1000, 'a');
  13571. Server svr;
  13572. svr.set_compress(false);
  13573. svr.Get("/buffered", [&](const Request &, Response &res) {
  13574. res.set_content(text, "text/plain");
  13575. });
  13576. svr.Get("/streamed", [&](const Request &, Response &res) {
  13577. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13578. sink.write(text.data(), text.size());
  13579. sink.done();
  13580. return true;
  13581. });
  13582. });
  13583. auto port = svr.bind_to_any_port(HOST);
  13584. ASSERT_LT(0, port);
  13585. thread t = thread([&] { svr.listen_after_bind(); });
  13586. auto se = detail::scope_exit([&] {
  13587. svr.stop();
  13588. t.join();
  13589. ASSERT_FALSE(svr.is_running());
  13590. });
  13591. svr.wait_until_ready();
  13592. Client cli(HOST, port);
  13593. cli.set_decompress(false);
  13594. for (auto path : {"/buffered", "/streamed"}) {
  13595. SCOPED_TRACE(path);
  13596. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13598. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13599. EXPECT_EQ(text, res->body);
  13600. }
  13601. }
  13602. // A chunked provider settles its coding where the headers are written and
  13603. // reuses it at write time. Both ends of that have to hold: a handler's own
  13604. // Content-Encoding suppresses the coding, and a response without one is still
  13605. // compressed as it always was.
  13606. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13607. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13608. const std::string plain = "Hello World! Hello World! Hello World!";
  13609. Server svr;
  13610. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13611. res.set_header("Content-Encoding", "gzip");
  13612. res.set_chunked_content_provider(
  13613. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13614. sink.write(gzipped.data(), gzipped.size());
  13615. sink.done();
  13616. return true;
  13617. });
  13618. });
  13619. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13620. res.set_chunked_content_provider(
  13621. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13622. sink.write(plain.data(), plain.size());
  13623. sink.done();
  13624. return true;
  13625. });
  13626. });
  13627. auto port = svr.bind_to_any_port(HOST);
  13628. thread t = thread([&]() { svr.listen_after_bind(); });
  13629. auto se = detail::scope_exit([&] {
  13630. svr.stop();
  13631. t.join();
  13632. ASSERT_FALSE(svr.is_running());
  13633. });
  13634. svr.wait_until_ready();
  13635. Client cli(HOST, port);
  13636. Headers headers = {{"Accept-Encoding", "gzip"}};
  13637. {
  13638. auto res = cli.Get("/pre-gzipped", headers);
  13639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13640. EXPECT_EQ(StatusCode::OK_200, res->status);
  13641. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13642. EXPECT_EQ("Hello World!", res->body);
  13643. }
  13644. {
  13645. auto res = cli.Get("/negotiated", headers);
  13646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13647. EXPECT_EQ(StatusCode::OK_200, res->status);
  13648. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13649. EXPECT_EQ(plain, res->body);
  13650. }
  13651. }
  13652. #endif
  13653. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13654. // the same message as the comma-joined one, so both have to be read the same
  13655. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13656. // single gzip coding, and a body the sender says was encoded twice was handed
  13657. // back after one pass, still compressed but presented as decoded.
  13658. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13659. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13660. Server svr;
  13661. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13662. res.set_content(body, "image/jpeg");
  13663. res.headers.emplace("Content-Encoding", "gzip");
  13664. res.headers.emplace("Content-Encoding", "gzip");
  13665. });
  13666. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13667. res.set_content(body, "image/jpeg");
  13668. res.set_header("Content-Encoding", "gzip, gzip");
  13669. });
  13670. auto port = svr.bind_to_any_port(HOST);
  13671. thread t = thread([&]() { svr.listen_after_bind(); });
  13672. auto se = detail::scope_exit([&] {
  13673. svr.stop();
  13674. t.join();
  13675. ASSERT_FALSE(svr.is_running());
  13676. });
  13677. svr.wait_until_ready();
  13678. Client cli(HOST, port);
  13679. // Two codings is not something cpp-httplib decodes, so both representations
  13680. // take the pass-through path rather than one of them being gunzipped once.
  13681. for (const char *path : {"/split", "/joined"}) {
  13682. auto res = cli.Get(path);
  13683. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13684. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13685. EXPECT_EQ(body, res->body) << path;
  13686. }
  13687. }
  13688. // Regression test for DoS vulnerability: a malicious server sending a response
  13689. // without Content-Length header must not cause unbounded memory consumption on
  13690. // the client side. The client should stop reading after a reasonable limit,
  13691. // similar to the server-side set_payload_max_length protection.
  13692. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13693. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13694. #ifndef _WIN32
  13695. signal(SIGPIPE, SIG_IGN);
  13696. #endif
  13697. auto server_thread = std::thread([] {
  13698. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13699. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13700. default_socket_options(srv);
  13701. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13702. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13703. sockaddr_in addr{};
  13704. addr.sin_family = AF_INET;
  13705. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13706. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13707. int opt = 1;
  13708. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13709. #ifdef _WIN32
  13710. reinterpret_cast<const char *>(&opt),
  13711. #else
  13712. &opt,
  13713. #endif
  13714. sizeof(opt));
  13715. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13716. ::listen(srv, 1);
  13717. sockaddr_in cli_addr{};
  13718. socklen_t cli_len = sizeof(cli_addr);
  13719. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13720. if (cli != INVALID_SOCKET) {
  13721. char buf[4096];
  13722. ::recv(cli, buf, sizeof(buf), 0);
  13723. // Malicious response: no Content-Length, no chunked encoding
  13724. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13725. "Connection: close\r\n"
  13726. "\r\n";
  13727. ::send(cli,
  13728. #ifdef _WIN32
  13729. static_cast<const char *>(response_header.c_str()),
  13730. static_cast<int>(response_header.size()),
  13731. #else
  13732. response_header.c_str(), response_header.size(),
  13733. #endif
  13734. 0);
  13735. // Send 10MB of data
  13736. std::string chunk(64 * 1024, 'A');
  13737. size_t total_sent = 0;
  13738. while (total_sent < MALICIOUS_DATA_SIZE) {
  13739. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13740. auto sent = ::send(cli,
  13741. #ifdef _WIN32
  13742. static_cast<const char *>(chunk.c_str()),
  13743. static_cast<int>(to_send),
  13744. #else
  13745. chunk.c_str(), to_send,
  13746. #endif
  13747. 0);
  13748. if (sent <= 0) break;
  13749. total_sent += static_cast<size_t>(sent);
  13750. }
  13751. detail::close_socket(cli);
  13752. }
  13753. detail::close_socket(srv);
  13754. });
  13755. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13756. size_t total_read = 0;
  13757. {
  13758. Client cli("127.0.0.1", PORT + 2);
  13759. cli.set_read_timeout(5, 0);
  13760. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13761. auto stream = cli.open_stream("GET", "/malicious");
  13762. ASSERT_TRUE(stream.is_valid());
  13763. char buffer[64 * 1024];
  13764. ssize_t n;
  13765. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13766. total_read += static_cast<size_t>(n);
  13767. }
  13768. } // StreamHandle and Client destroyed here, closing the socket
  13769. server_thread.join();
  13770. // With set_payload_max_length, the client must stop reading before consuming
  13771. // all 10MB. The read loop should be cut off at or near the configured limit.
  13772. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13773. << "Client read " << total_read << " bytes, exceeding the configured "
  13774. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13775. }
  13776. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13777. // the entire response body without truncation.
  13778. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13779. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13780. #ifndef _WIN32
  13781. signal(SIGPIPE, SIG_IGN);
  13782. #endif
  13783. auto server_thread = std::thread([] {
  13784. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13785. default_socket_options(srv);
  13786. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13787. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13788. sockaddr_in addr{};
  13789. addr.sin_family = AF_INET;
  13790. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13791. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13792. int opt = 1;
  13793. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13794. #ifdef _WIN32
  13795. reinterpret_cast<const char *>(&opt),
  13796. #else
  13797. &opt,
  13798. #endif
  13799. sizeof(opt));
  13800. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13801. ::listen(srv, 1);
  13802. sockaddr_in cli_addr{};
  13803. socklen_t cli_len = sizeof(cli_addr);
  13804. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13805. if (cli != INVALID_SOCKET) {
  13806. char buf[4096];
  13807. ::recv(cli, buf, sizeof(buf), 0);
  13808. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13809. "Connection: close\r\n"
  13810. "\r\n";
  13811. ::send(cli,
  13812. #ifdef _WIN32
  13813. static_cast<const char *>(response_header.c_str()),
  13814. static_cast<int>(response_header.size()),
  13815. #else
  13816. response_header.c_str(), response_header.size(),
  13817. #endif
  13818. 0);
  13819. std::string chunk(64 * 1024, 'A');
  13820. size_t total_sent = 0;
  13821. while (total_sent < DATA_SIZE) {
  13822. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13823. auto sent = ::send(cli,
  13824. #ifdef _WIN32
  13825. static_cast<const char *>(chunk.c_str()),
  13826. static_cast<int>(to_send),
  13827. #else
  13828. chunk.c_str(), to_send,
  13829. #endif
  13830. 0);
  13831. if (sent <= 0) break;
  13832. total_sent += static_cast<size_t>(sent);
  13833. }
  13834. #ifdef _WIN32
  13835. ::shutdown(cli, SD_SEND);
  13836. #else
  13837. ::shutdown(cli, SHUT_WR);
  13838. #endif
  13839. // Drain until the client closes its end, ensuring all data is delivered
  13840. char drain[1024];
  13841. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13842. detail::close_socket(cli);
  13843. }
  13844. detail::close_socket(srv);
  13845. });
  13846. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13847. size_t total_read = 0;
  13848. {
  13849. Client cli("127.0.0.1", PORT + 2);
  13850. cli.set_read_timeout(5, 0);
  13851. cli.set_payload_max_length(0); // 0 means no limit
  13852. auto stream = cli.open_stream("GET", "/data");
  13853. ASSERT_TRUE(stream.is_valid());
  13854. char buffer[64 * 1024];
  13855. ssize_t n;
  13856. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13857. total_read += static_cast<size_t>(n);
  13858. }
  13859. }
  13860. server_thread.join();
  13861. EXPECT_EQ(total_read, DATA_SIZE)
  13862. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13863. << " bytes without truncation, but only read " << total_read << " bytes.";
  13864. }
  13865. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13866. // enormous Content-Length must not cause the client to pre-allocate a huge
  13867. // response body buffer. The reservation is capped at payload_max_length_, and
  13868. // the read itself fails when the body exceeds the limit.
  13869. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13870. #ifndef _WIN32
  13871. signal(SIGPIPE, SIG_IGN);
  13872. #endif
  13873. auto server_thread = std::thread([] {
  13874. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13875. default_socket_options(srv);
  13876. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13877. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13878. sockaddr_in addr{};
  13879. addr.sin_family = AF_INET;
  13880. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13881. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13882. int opt = 1;
  13883. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13884. #ifdef _WIN32
  13885. reinterpret_cast<const char *>(&opt),
  13886. #else
  13887. &opt,
  13888. #endif
  13889. sizeof(opt));
  13890. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13891. ::listen(srv, 1);
  13892. sockaddr_in cli_addr{};
  13893. socklen_t cli_len = sizeof(cli_addr);
  13894. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13895. if (cli != INVALID_SOCKET) {
  13896. char buf[4096];
  13897. ::recv(cli, buf, sizeof(buf), 0);
  13898. // Malicious response: claim a 20GB body but send only a tiny payload.
  13899. std::string response = "HTTP/1.1 200 OK\r\n"
  13900. "Content-Length: 20000000000\r\n"
  13901. "\r\n"
  13902. "abc";
  13903. ::send(cli,
  13904. #ifdef _WIN32
  13905. static_cast<const char *>(response.c_str()),
  13906. static_cast<int>(response.size()),
  13907. #else
  13908. response.c_str(), response.size(),
  13909. #endif
  13910. 0);
  13911. detail::close_socket(cli);
  13912. }
  13913. detail::close_socket(srv);
  13914. });
  13915. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13916. {
  13917. Client cli("127.0.0.1", PORT + 2);
  13918. cli.set_read_timeout(5, 0);
  13919. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13920. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13921. // (server claims more bytes than payload_max_length permits), but it must
  13922. // not exhaust memory before getting there.
  13923. auto res = cli.Get("/malicious");
  13924. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13925. }
  13926. server_thread.join();
  13927. }
  13928. // Verify that content_receiver bypasses the default payload_max_length,
  13929. // allowing streaming downloads larger than 100MB without requiring an explicit
  13930. // set_payload_max_length call.
  13931. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13932. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13933. #ifndef _WIN32
  13934. signal(SIGPIPE, SIG_IGN);
  13935. #endif
  13936. auto server_thread = std::thread([] {
  13937. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13938. default_socket_options(srv);
  13939. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13940. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13941. sockaddr_in addr{};
  13942. addr.sin_family = AF_INET;
  13943. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13944. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13945. int opt = 1;
  13946. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13947. #ifdef _WIN32
  13948. reinterpret_cast<const char *>(&opt),
  13949. #else
  13950. &opt,
  13951. #endif
  13952. sizeof(opt));
  13953. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13954. ::listen(srv, 1);
  13955. sockaddr_in cli_addr{};
  13956. socklen_t cli_len = sizeof(cli_addr);
  13957. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13958. if (cli != INVALID_SOCKET) {
  13959. char buf[4096];
  13960. ::recv(cli, buf, sizeof(buf), 0);
  13961. // Response with Content-Length larger than default 100MB limit
  13962. auto content_length = std::to_string(DATA_SIZE);
  13963. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13964. "Content-Length: " +
  13965. content_length +
  13966. "\r\n"
  13967. "Connection: close\r\n"
  13968. "\r\n";
  13969. ::send(cli,
  13970. #ifdef _WIN32
  13971. static_cast<const char *>(response_header.c_str()),
  13972. static_cast<int>(response_header.size()),
  13973. #else
  13974. response_header.c_str(), response_header.size(),
  13975. #endif
  13976. 0);
  13977. std::string chunk(64 * 1024, 'A');
  13978. size_t total_sent = 0;
  13979. while (total_sent < DATA_SIZE) {
  13980. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13981. auto sent = ::send(cli,
  13982. #ifdef _WIN32
  13983. static_cast<const char *>(chunk.c_str()),
  13984. static_cast<int>(to_send),
  13985. #else
  13986. chunk.c_str(), to_send,
  13987. #endif
  13988. 0);
  13989. if (sent <= 0) break;
  13990. total_sent += static_cast<size_t>(sent);
  13991. }
  13992. detail::close_socket(cli);
  13993. }
  13994. detail::close_socket(srv);
  13995. });
  13996. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13997. size_t total_received = 0;
  13998. {
  13999. Client cli("127.0.0.1", PORT + 2);
  14000. cli.set_read_timeout(10, 0);
  14001. // Do NOT call set_payload_max_length — use the default 100MB limit
  14002. auto res =
  14003. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14004. total_received += data_length;
  14005. return true;
  14006. });
  14007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14008. EXPECT_EQ(StatusCode::OK_200, res->status);
  14009. }
  14010. server_thread.join();
  14011. EXPECT_EQ(total_received, DATA_SIZE)
  14012. << "With content_receiver, the client should read all " << DATA_SIZE
  14013. << " bytes despite the default 100MB payload_max_length, but only read "
  14014. << total_received << " bytes.";
  14015. }
  14016. // Verify that an explicit set_payload_max_length smaller than the response is
  14017. // enforced even when a content_receiver is used.
  14018. TEST(ClientVulnerabilityTest,
  14019. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  14020. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  14021. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  14022. #ifndef _WIN32
  14023. signal(SIGPIPE, SIG_IGN);
  14024. #endif
  14025. auto server_thread = std::thread([] {
  14026. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14027. default_socket_options(srv);
  14028. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14029. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14030. sockaddr_in addr{};
  14031. addr.sin_family = AF_INET;
  14032. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  14033. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14034. int opt = 1;
  14035. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14036. #ifdef _WIN32
  14037. reinterpret_cast<const char *>(&opt),
  14038. #else
  14039. &opt,
  14040. #endif
  14041. sizeof(opt));
  14042. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14043. ::listen(srv, 1);
  14044. sockaddr_in cli_addr{};
  14045. socklen_t cli_len = sizeof(cli_addr);
  14046. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14047. if (cli != INVALID_SOCKET) {
  14048. char buf[4096];
  14049. ::recv(cli, buf, sizeof(buf), 0);
  14050. auto content_length = std::to_string(DATA_SIZE);
  14051. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14052. "Content-Length: " +
  14053. content_length +
  14054. "\r\n"
  14055. "Connection: close\r\n"
  14056. "\r\n";
  14057. ::send(cli,
  14058. #ifdef _WIN32
  14059. static_cast<const char *>(response_header.c_str()),
  14060. static_cast<int>(response_header.size()),
  14061. #else
  14062. response_header.c_str(), response_header.size(),
  14063. #endif
  14064. 0);
  14065. std::string chunk(64 * 1024, 'A');
  14066. size_t total_sent = 0;
  14067. while (total_sent < DATA_SIZE) {
  14068. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14069. auto sent = ::send(cli,
  14070. #ifdef _WIN32
  14071. static_cast<const char *>(chunk.c_str()),
  14072. static_cast<int>(to_send),
  14073. #else
  14074. chunk.c_str(), to_send,
  14075. #endif
  14076. 0);
  14077. if (sent <= 0) break;
  14078. total_sent += static_cast<size_t>(sent);
  14079. }
  14080. detail::close_socket(cli);
  14081. }
  14082. detail::close_socket(srv);
  14083. });
  14084. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14085. size_t total_received = 0;
  14086. {
  14087. Client cli("127.0.0.1", PORT + 2);
  14088. cli.set_read_timeout(10, 0);
  14089. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  14090. auto res =
  14091. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14092. total_received += data_length;
  14093. return true;
  14094. });
  14095. // Should fail because 200MB exceeds the explicit 150MB limit
  14096. EXPECT_FALSE(res);
  14097. }
  14098. server_thread.join();
  14099. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  14100. << "Client with content_receiver should respect the explicit "
  14101. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  14102. << total_received << " bytes.";
  14103. }
  14104. // Verify that an explicit set_payload_max_length larger than the response
  14105. // allows the content_receiver to read all data successfully.
  14106. TEST(ClientVulnerabilityTest,
  14107. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  14108. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  14109. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  14110. #ifndef _WIN32
  14111. signal(SIGPIPE, SIG_IGN);
  14112. #endif
  14113. auto server_thread = std::thread([] {
  14114. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14115. default_socket_options(srv);
  14116. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14117. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14118. sockaddr_in addr{};
  14119. addr.sin_family = AF_INET;
  14120. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  14121. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14122. int opt = 1;
  14123. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14124. #ifdef _WIN32
  14125. reinterpret_cast<const char *>(&opt),
  14126. #else
  14127. &opt,
  14128. #endif
  14129. sizeof(opt));
  14130. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14131. ::listen(srv, 1);
  14132. sockaddr_in cli_addr{};
  14133. socklen_t cli_len = sizeof(cli_addr);
  14134. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14135. if (cli != INVALID_SOCKET) {
  14136. char buf[4096];
  14137. ::recv(cli, buf, sizeof(buf), 0);
  14138. auto content_length = std::to_string(DATA_SIZE);
  14139. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14140. "Content-Length: " +
  14141. content_length +
  14142. "\r\n"
  14143. "Connection: close\r\n"
  14144. "\r\n";
  14145. ::send(cli,
  14146. #ifdef _WIN32
  14147. static_cast<const char *>(response_header.c_str()),
  14148. static_cast<int>(response_header.size()),
  14149. #else
  14150. response_header.c_str(), response_header.size(),
  14151. #endif
  14152. 0);
  14153. std::string chunk(64 * 1024, 'A');
  14154. size_t total_sent = 0;
  14155. while (total_sent < DATA_SIZE) {
  14156. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14157. auto sent = ::send(cli,
  14158. #ifdef _WIN32
  14159. static_cast<const char *>(chunk.c_str()),
  14160. static_cast<int>(to_send),
  14161. #else
  14162. chunk.c_str(), to_send,
  14163. #endif
  14164. 0);
  14165. if (sent <= 0) break;
  14166. total_sent += static_cast<size_t>(sent);
  14167. }
  14168. #ifdef _WIN32
  14169. ::shutdown(cli, SD_SEND);
  14170. #else
  14171. ::shutdown(cli, SHUT_WR);
  14172. #endif
  14173. char drain[1024];
  14174. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  14175. detail::close_socket(cli);
  14176. }
  14177. detail::close_socket(srv);
  14178. });
  14179. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14180. size_t total_received = 0;
  14181. {
  14182. Client cli("127.0.0.1", PORT + 2);
  14183. cli.set_read_timeout(10, 0);
  14184. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  14185. auto res =
  14186. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14187. total_received += data_length;
  14188. return true;
  14189. });
  14190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14191. EXPECT_EQ(StatusCode::OK_200, res->status);
  14192. }
  14193. server_thread.join();
  14194. EXPECT_EQ(total_received, DATA_SIZE)
  14195. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  14196. << " bytes (larger than " << DATA_SIZE
  14197. << " bytes response), content_receiver should read all data, but only "
  14198. "read "
  14199. << total_received << " bytes.";
  14200. }
  14201. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  14202. // Regression test for "zip bomb" attack on the client side: a malicious server
  14203. // sends a small gzip-compressed response that decompresses to a huge payload.
  14204. // The client must enforce payload_max_length on the decompressed size.
  14205. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  14206. constexpr size_t DECOMPRESSED_SIZE =
  14207. 10 * 1024 * 1024; // 10MB after decompression
  14208. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  14209. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  14210. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  14211. std::string compressed;
  14212. {
  14213. httplib::detail::gzip_compressor compressor;
  14214. bool ok =
  14215. compressor.compress(uncompressed.data(), uncompressed.size(),
  14216. /*last=*/true, [&](const char *buf, size_t len) {
  14217. compressed.append(buf, len);
  14218. return true;
  14219. });
  14220. ASSERT_TRUE(ok);
  14221. }
  14222. // Sanity: compressed data should be much smaller than the decompressed size
  14223. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  14224. #ifndef _WIN32
  14225. signal(SIGPIPE, SIG_IGN);
  14226. #endif
  14227. // Set up the listening socket in the main thread so the server is guaranteed
  14228. // to be ready before the client connects (eliminates race condition).
  14229. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14230. default_socket_options(srv);
  14231. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14232. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14233. sockaddr_in addr{};
  14234. addr.sin_family = AF_INET;
  14235. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14236. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14237. int opt = 1;
  14238. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14239. #ifdef _WIN32
  14240. reinterpret_cast<const char *>(&opt),
  14241. #else
  14242. &opt,
  14243. #endif
  14244. sizeof(opt));
  14245. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14246. ASSERT_EQ(0, ::listen(srv, 1));
  14247. auto server_thread = std::thread([&compressed, srv] {
  14248. sockaddr_in cli_addr{};
  14249. socklen_t cli_len = sizeof(cli_addr);
  14250. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14251. if (cli != INVALID_SOCKET) {
  14252. // Read the full HTTP request (until \r\n\r\n)
  14253. char buf[4096];
  14254. size_t total = 0;
  14255. while (total < sizeof(buf)) {
  14256. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14257. if (n <= 0) break;
  14258. total += static_cast<size_t>(n);
  14259. // Check for end of headers
  14260. if (total >= 4) {
  14261. std::string req(buf, total);
  14262. if (req.find("\r\n\r\n") != std::string::npos) break;
  14263. }
  14264. }
  14265. // Malicious response: gzip-compressed body, no Content-Length
  14266. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14267. "Content-Encoding: gzip\r\n"
  14268. "Connection: close\r\n"
  14269. "\r\n";
  14270. ::send(cli,
  14271. #ifdef _WIN32
  14272. static_cast<const char *>(response_header.c_str()),
  14273. static_cast<int>(response_header.size()),
  14274. #else
  14275. response_header.c_str(), response_header.size(),
  14276. #endif
  14277. 0);
  14278. // Send the compressed payload (small on the wire, huge when decompressed)
  14279. size_t total_sent = 0;
  14280. while (total_sent < compressed.size()) {
  14281. auto to_send = std::min(compressed.size() - total_sent,
  14282. static_cast<size_t>(64 * 1024));
  14283. auto sent =
  14284. ::send(cli,
  14285. #ifdef _WIN32
  14286. static_cast<const char *>(compressed.c_str() + total_sent),
  14287. static_cast<int>(to_send),
  14288. #else
  14289. compressed.c_str() + total_sent, to_send,
  14290. #endif
  14291. 0);
  14292. if (sent <= 0) break;
  14293. total_sent += static_cast<size_t>(sent);
  14294. }
  14295. detail::close_socket(cli);
  14296. }
  14297. });
  14298. auto se = detail::scope_exit([&] {
  14299. detail::close_socket(srv);
  14300. server_thread.join();
  14301. });
  14302. size_t total_decompressed = 0;
  14303. {
  14304. Client cli("127.0.0.1", PORT + 3);
  14305. cli.set_read_timeout(5, 0);
  14306. cli.set_decompress(true);
  14307. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14308. auto stream = cli.open_stream("GET", "/zipbomb");
  14309. ASSERT_TRUE(stream.is_valid());
  14310. char buffer[64 * 1024];
  14311. ssize_t n;
  14312. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14313. total_decompressed += static_cast<size_t>(n);
  14314. }
  14315. }
  14316. // The decompressed size must be capped by payload_max_length. Without
  14317. // protection, the client would decompress the full 10MB from a tiny
  14318. // compressed payload, enabling a zip bomb DoS attack.
  14319. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14320. << "Client decompressed " << total_decompressed
  14321. << " bytes from a gzip response. The decompressed size should be "
  14322. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14323. }
  14324. #endif
  14325. TEST(HostAndPortPropertiesTest, NoSSL) {
  14326. httplib::Client cli("www.google.com", 1234);
  14327. ASSERT_EQ("www.google.com", cli.host());
  14328. ASSERT_EQ(1234, cli.port());
  14329. }
  14330. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14331. httplib::Client cli("www.google.com:1234");
  14332. ASSERT_EQ("www.google.com", cli.host());
  14333. ASSERT_EQ(1234, cli.port());
  14334. }
  14335. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14336. // Port number that overflows int — should not crash, client becomes invalid
  14337. httplib::Client cli("http://www.google.com:99999999999999999999");
  14338. ASSERT_FALSE(cli.is_valid());
  14339. }
  14340. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14341. // Port 99999 exceeds valid range (1-65535) — should not crash
  14342. httplib::Client cli("http://www.google.com:99999");
  14343. ASSERT_FALSE(cli.is_valid());
  14344. auto res = cli.Get("/");
  14345. EXPECT_FALSE(res);
  14346. EXPECT_EQ(Error::Connection, res.error());
  14347. }
  14348. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14349. httplib::Client cli("http://user:pass@localhost:1234");
  14350. ASSERT_FALSE(cli.is_valid());
  14351. EXPECT_FALSE(cli.Get("/"));
  14352. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14353. }
  14354. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14355. httplib::Client cli("http://www.google.com:80abc");
  14356. ASSERT_FALSE(cli.is_valid());
  14357. }
  14358. #ifdef CPPHTTPLIB_SSL_ENABLED
  14359. TEST(HostAndPortPropertiesTest, SSL) {
  14360. httplib::SSLClient cli("www.google.com");
  14361. ASSERT_EQ("www.google.com", cli.host());
  14362. ASSERT_EQ(443, cli.port());
  14363. }
  14364. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14365. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14366. std::string cert;
  14367. read_file(CA_CERT_FILE, cert);
  14368. httplib::SSLClient httplib_client("www.google.com");
  14369. // Load CA store first time
  14370. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14371. // Load CA store second time (update)
  14372. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14373. // Verify client is still valid and can make connections
  14374. httplib_client.enable_server_certificate_verification(true);
  14375. auto res = httplib_client.Get("/");
  14376. // Any status: Google may redirect or rate-limit CI runners.
  14377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14378. }
  14379. TEST(SSLClientTest, ServerNameIndication_Online) {
  14380. auto host = "httpbingo.org";
  14381. auto path = std::string{"/get"};
  14382. SSLClient cli(host, 443);
  14383. auto res = retry_service_failures([&] { return cli.Get(path); });
  14384. SKIP_ON_SERVICE_FAILURE(res);
  14385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14386. ASSERT_EQ(StatusCode::OK_200, res->status);
  14387. }
  14388. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14389. // Use a site that will cause SSL verification failure due to self-signed cert
  14390. SSLClient cli("self-signed.badssl.com", 443);
  14391. cli.enable_server_certificate_verification(true);
  14392. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14393. SKIP_ON_SERVICE_FAILURE(res);
  14394. ASSERT_TRUE(!res);
  14395. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14396. // Verify backend error is captured for SSLServerVerification
  14397. // This occurs when certificate verification fails
  14398. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14399. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14400. EXPECT_NE(0UL, res.ssl_backend_error());
  14401. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14402. res.ssl_error());
  14403. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14404. #if !defined(_WIN32) || \
  14405. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14406. // On non-Windows or when Windows Schannel is disabled, the error comes
  14407. // from OpenSSL's verification
  14408. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14409. res.ssl_backend_error());
  14410. #endif
  14411. #endif
  14412. }
  14413. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14414. // Use a site where hostname doesn't match the certificate
  14415. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14416. SSLClient cli("wrong.host.badssl.com", 443);
  14417. cli.enable_server_certificate_verification(true);
  14418. cli.enable_server_hostname_verification(true);
  14419. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14420. SKIP_ON_SERVICE_FAILURE(res);
  14421. ASSERT_TRUE(!res);
  14422. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14423. // Verify backend error is captured for hostname verification failure
  14424. EXPECT_NE(0UL, res.ssl_backend_error());
  14425. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14426. res.ssl_error());
  14427. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14428. #if !defined(_WIN32) || \
  14429. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14430. // On non-Windows or when Windows Schannel is disabled, the error comes
  14431. // from OpenSSL's hostname verification
  14432. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14433. res.ssl_backend_error());
  14434. #endif
  14435. #endif
  14436. }
  14437. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14438. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14439. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14440. SSLClient cli("www.google.com", 443);
  14441. cli.enable_server_certificate_verification(true);
  14442. auto res = cli.Get("/");
  14443. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14444. }
  14445. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14446. SSLClient cli("www.google.com", 443);
  14447. cli.enable_server_certificate_verification(true);
  14448. cli.enable_windows_certificate_verification(false);
  14449. auto res = cli.Get("/");
  14450. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14451. }
  14452. // The server sends an intermediate cross-signed by a root Windows trusts,
  14453. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14454. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14455. SSLClient cli("accounts.spotify.com", 443);
  14456. auto res = cli.Get("/");
  14457. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14458. << " ssl_backend_error=" << res.ssl_backend_error();
  14459. }
  14460. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14461. // policy status, which no backend reports for a self-signed certificate.
  14462. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14463. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14464. ASSERT_TRUE(svr.is_valid());
  14465. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14466. auto se = detail::scope_exit([&] {
  14467. svr.stop();
  14468. t.join();
  14469. ASSERT_FALSE(svr.is_running());
  14470. });
  14471. svr.wait_until_ready();
  14472. SSLClient cli("127.0.0.1", PORT);
  14473. cli.set_connection_timeout(30);
  14474. auto res = cli.Get("/");
  14475. ASSERT_FALSE(res);
  14476. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14477. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14478. }
  14479. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14480. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14481. ASSERT_TRUE(svr.is_valid());
  14482. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14483. auto se = detail::scope_exit([&] {
  14484. svr.stop();
  14485. t.join();
  14486. ASSERT_FALSE(svr.is_running());
  14487. });
  14488. svr.wait_until_ready();
  14489. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14490. {
  14491. ws::WebSocketClient client(url);
  14492. auto res = client.connect();
  14493. ASSERT_FALSE(res);
  14494. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14495. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14496. res.ssl_backend_error());
  14497. }
  14498. {
  14499. ws::WebSocketClient client(url);
  14500. client.enable_windows_certificate_verification(false);
  14501. auto res = client.connect();
  14502. ASSERT_FALSE(res);
  14503. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14504. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14505. res.ssl_backend_error());
  14506. }
  14507. }
  14508. #endif
  14509. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14510. Client cli("https://google.com");
  14511. auto res = cli.Get("/");
  14512. // Any status: Google may redirect or rate-limit CI runners.
  14513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14514. }
  14515. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14516. SSLClient cli("google.com");
  14517. cli.set_ca_cert_path(CA_CERT_FILE);
  14518. auto res = cli.Get("/");
  14519. // Any status: Google may redirect or rate-limit CI runners.
  14520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14521. }
  14522. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14523. SSLClient cli("google.com");
  14524. cli.enable_server_certificate_verification(true);
  14525. cli.set_ca_cert_path("hello");
  14526. auto res = cli.Get("/");
  14527. ASSERT_TRUE(!res);
  14528. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14529. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14530. // should be set
  14531. EXPECT_EQ(0, res.ssl_error());
  14532. // Verify backend error is captured for SSLLoadingCerts
  14533. // This error occurs when loading CA certificates fails
  14534. EXPECT_NE(0UL, res.ssl_backend_error());
  14535. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14536. // OpenSSL specific error codes:
  14537. // > openssl errstr 0x80000002
  14538. // error:80000002:system library::No such file or directory
  14539. // > openssl errstr 0xA000126
  14540. // error:0A000126:SSL routines::unexpected eof while reading
  14541. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14542. res.ssl_backend_error() == 0xA000126);
  14543. #endif
  14544. }
  14545. TEST(SSLClientTest, ServerCertificateVerification4) {
  14546. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14547. ASSERT_TRUE(svr.is_valid());
  14548. svr.Get("/test", [&](const Request &, Response &res) {
  14549. res.set_content("test", "text/plain");
  14550. svr.stop();
  14551. ASSERT_TRUE(true);
  14552. });
  14553. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14554. auto se = detail::scope_exit([&] {
  14555. t.join();
  14556. ASSERT_FALSE(svr.is_running());
  14557. });
  14558. svr.wait_until_ready();
  14559. SSLClient cli("127.0.0.1", PORT);
  14560. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14561. cli.enable_server_certificate_verification(true);
  14562. cli.set_connection_timeout(30);
  14563. auto res = cli.Get("/test");
  14564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14565. ASSERT_EQ(StatusCode::OK_200, res->status);
  14566. }
  14567. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14568. std::string cert;
  14569. read_file(CA_CERT_FILE, cert);
  14570. SSLClient cli("google.com");
  14571. cli.load_ca_cert_store(cert.data(), cert.size());
  14572. const auto res = cli.Get("/");
  14573. // Any status: Google may redirect or rate-limit CI runners.
  14574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14575. }
  14576. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14577. // clang-format off
  14578. static constexpr char cert[] =
  14579. "GlobalSign Root CA\n"
  14580. "==================\n"
  14581. "-----BEGIN CERTIFICATE-----\n"
  14582. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14583. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14584. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14585. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14586. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14587. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14588. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14589. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14590. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14591. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14592. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14593. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14594. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14595. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14596. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14597. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14598. "-----END CERTIFICATE-----\n";
  14599. // clang-format on
  14600. SSLClient cli("google.com");
  14601. cli.load_ca_cert_store(cert, sizeof(cert));
  14602. const auto res = cli.Get("/");
  14603. // Any status: Google may redirect or rate-limit CI runners.
  14604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14605. }
  14606. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14607. SSLClient cli("www.youtube.com");
  14608. cli.set_ca_cert_path(CA_CERT_FILE);
  14609. cli.enable_server_certificate_verification(true);
  14610. cli.set_follow_location(true);
  14611. auto res = cli.Get("/");
  14612. // Any status: Google may redirect or rate-limit CI runners.
  14613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14614. }
  14615. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14616. SSLClient cli("wWw.YouTube.Com");
  14617. cli.set_ca_cert_path(CA_CERT_FILE);
  14618. cli.enable_server_certificate_verification(true);
  14619. cli.enable_server_hostname_verification(true);
  14620. cli.set_follow_location(true);
  14621. auto res = cli.Get("/");
  14622. // Any status: Google may redirect or rate-limit CI runners.
  14623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14624. }
  14625. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14626. SSLClient cli("gOoGlE.COm");
  14627. cli.enable_server_certificate_verification(true);
  14628. cli.enable_server_hostname_verification(true);
  14629. cli.set_follow_location(true);
  14630. auto res = cli.Get("/");
  14631. // Any status: Google may redirect or rate-limit CI runners.
  14632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14633. }
  14634. TEST(SSLClientTest, Issue2004_Online) {
  14635. Client client("https://google.com");
  14636. client.set_follow_location(true);
  14637. auto res = client.Get("/");
  14638. // Any status: Google may redirect or rate-limit CI runners.
  14639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14640. }
  14641. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14642. // Create SSLClient with invalid cert/key to make is_valid() return false
  14643. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14644. "nonexistent_key.pem");
  14645. // is_valid() should be false due to cert loading failure
  14646. ASSERT_FALSE(cli.is_valid());
  14647. auto res = cli.Get("/");
  14648. ASSERT_FALSE(res);
  14649. EXPECT_EQ(Error::SSLConnection, res.error());
  14650. }
  14651. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14652. // Test for Issue #2251: SSL error not properly reported when client cert
  14653. // and key paths are swapped or mismatched
  14654. // This simulates the scenario where user accidentally swaps the cert and key
  14655. // files
  14656. // Using client cert file as private key and vice versa (completely wrong)
  14657. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14658. // Should fail validation due to cert/key mismatch
  14659. ASSERT_FALSE(cli.is_valid());
  14660. // Attempt to make a request should fail with proper error
  14661. auto res = cli.Get("/");
  14662. ASSERT_FALSE(res);
  14663. EXPECT_EQ(Error::SSLConnection, res.error());
  14664. // SSL error should be recorded in the Result object (this is the key fix for
  14665. // Issue #2251)
  14666. auto backend_error = res.ssl_backend_error();
  14667. EXPECT_NE(0u, backend_error);
  14668. }
  14669. // Tests cert/key mismatch detection at the TLS context level
  14670. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14671. // Test that using mismatched cert/key causes connection failure.
  14672. // We verify this at the SSLClient level rather than through internal
  14673. // TLS API functions.
  14674. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14675. cli.enable_server_certificate_verification(false);
  14676. cli.set_connection_timeout(2);
  14677. // The mismatch should cause a connection or handshake error
  14678. auto res = cli.Get("/test");
  14679. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14680. // Either way, the request should fail
  14681. EXPECT_FALSE(res);
  14682. }
  14683. #endif
  14684. #if 0
  14685. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14686. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14687. ASSERT_TRUE(cli != nullptr);
  14688. cli->set_address_family(AF_INET6);
  14689. cli->set_interface("en0");
  14690. auto res = cli->Get("/get");
  14691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14692. ASSERT_EQ(StatusCode::OK_200, res->status);
  14693. }
  14694. #endif
  14695. // Client certificate tests - work with all TLS backends
  14696. #ifdef CPPHTTPLIB_SSL_ENABLED
  14697. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14698. void ClientCertPresent(
  14699. const std::string &client_cert_file,
  14700. const std::string &client_private_key_file,
  14701. const std::string &client_encrypted_private_key_pass = std::string(),
  14702. const ClientCertServerSetup &setup = nullptr) {
  14703. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14704. ASSERT_TRUE(svr.is_valid());
  14705. if (setup) { setup(svr); }
  14706. svr.Get("/test", [&](const Request &req, Response &res) {
  14707. res.set_content("test", "text/plain");
  14708. auto cert = req.peer_cert();
  14709. ASSERT_TRUE(static_cast<bool>(cert));
  14710. std::string common_name = cert.subject_cn();
  14711. EXPECT_EQ("Common Name", common_name);
  14712. });
  14713. auto port = svr.bind_to_any_port(HOST);
  14714. ASSERT_LT(0, port);
  14715. thread t = thread([&]() { svr.listen_after_bind(); });
  14716. auto se = detail::scope_exit([&] {
  14717. svr.stop();
  14718. t.join();
  14719. ASSERT_FALSE(svr.is_running());
  14720. });
  14721. svr.wait_until_ready();
  14722. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14723. client_encrypted_private_key_pass);
  14724. cli.enable_server_certificate_verification(false);
  14725. cli.set_connection_timeout(30);
  14726. auto res = cli.Get("/test");
  14727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14728. ASSERT_EQ(StatusCode::OK_200, res->status);
  14729. }
  14730. TEST(SSLClientServerTest, ClientCertPresent) {
  14731. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14732. }
  14733. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14734. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14735. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14736. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14737. }
  14738. // Expects svr, which must require client certificates, to reject a client
  14739. // that has none
  14740. void RejectsClientWithoutCert(SSLServer &svr) {
  14741. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14742. auto port = svr.bind_to_any_port(HOST);
  14743. ASSERT_LT(0, port);
  14744. thread t = thread([&]() { svr.listen_after_bind(); });
  14745. auto se = detail::scope_exit([&] {
  14746. svr.stop();
  14747. t.join();
  14748. ASSERT_FALSE(svr.is_running());
  14749. });
  14750. svr.wait_until_ready();
  14751. SSLClient cli(HOST, port);
  14752. cli.set_connection_timeout(30);
  14753. // Skip the server certificate check, so that the request fails because the
  14754. // client certificate is missing rather than because cert.pem is not trusted
  14755. cli.enable_server_certificate_verification(false);
  14756. auto res = cli.Get("/test");
  14757. ASSERT_FALSE(res);
  14758. // The server rejects the client during the handshake, or on TLS 1.3 right
  14759. // after it, which the client notices on its first write or read
  14760. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14761. res.error() == Error::Write || res.error() == Error::Read)
  14762. << to_string(res.error());
  14763. if (res.error() == Error::SSLConnection) {
  14764. EXPECT_NE(0UL, res.ssl_backend_error());
  14765. }
  14766. // A rejection noticed on the write keeps the TLS error the write hit
  14767. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14768. }
  14769. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14770. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14771. ASSERT_TRUE(svr.is_valid());
  14772. if (setup) { setup(svr); }
  14773. RejectsClientWithoutCert(svr);
  14774. }
  14775. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14776. // A server that requires client certificates must keep requiring them after
  14777. // setup changes it, and keep accepting a client that has one
  14778. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14779. ClientCertMissing(setup);
  14780. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14781. setup);
  14782. }
  14783. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14784. ClientCertStillRequired([](SSLServer &svr) {
  14785. ASSERT_TRUE(tls::set_verify_callback(
  14786. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14787. });
  14788. }
  14789. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14790. ClientCertStillRequired([](SSLServer &svr) {
  14791. ASSERT_TRUE(tls::set_verify_callback(
  14792. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14793. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14794. });
  14795. }
  14796. // The client verifies the server certificate during the handshake, so a
  14797. // server that fails the check never gets the client certificate, even when a
  14798. // verifier of the client's own accepts it
  14799. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14800. struct Case {
  14801. const char *trusted_ca;
  14802. const char *host;
  14803. Error error;
  14804. };
  14805. // cert2.pem names localhost: the first client does not trust it, and the
  14806. // second trusts it but asks for another name
  14807. for (const auto &c :
  14808. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14809. Case{SERVER_CERT2_FILE, "example.com",
  14810. Error::SSLServerHostnameVerification}}) {
  14811. for (auto with_verifier : {false, true}) {
  14812. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14813. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14814. CLIENT_CA_CERT_FILE);
  14815. ASSERT_TRUE(svr.is_valid());
  14816. std::atomic<bool> got_client_cert{false};
  14817. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14818. [&](const tls::VerifyContext &) {
  14819. got_client_cert = true;
  14820. return true;
  14821. }));
  14822. auto port = svr.bind_to_any_port("127.0.0.1");
  14823. ASSERT_LT(0, port);
  14824. thread t = thread([&] { svr.listen_after_bind(); });
  14825. svr.wait_until_ready();
  14826. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14827. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14828. cli.set_ca_cert_path(c.trusted_ca);
  14829. if (with_verifier) {
  14830. cli.set_server_certificate_verifier(
  14831. [](const tls::VerifyContext &) { return true; });
  14832. }
  14833. auto res = cli.Get("/");
  14834. EXPECT_FALSE(res);
  14835. EXPECT_EQ(c.error, res.error());
  14836. svr.stop();
  14837. t.join();
  14838. EXPECT_FALSE(got_client_cert);
  14839. }
  14840. }
  14841. }
  14842. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14843. std::string cert_pem, key_pem, ca_pem;
  14844. read_file(SERVER_CERT_FILE, cert_pem);
  14845. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14846. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14847. ASSERT_TRUE(
  14848. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14849. }
  14850. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14851. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14852. ASSERT_TRUE(svr.is_valid());
  14853. UpdateCertsPemWithClientCA(svr);
  14854. RejectsClientWithoutCert(svr);
  14855. }
  14856. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14857. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14858. }
  14859. // A TLS error from one request must not show up in a later request's Result
  14860. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14861. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14862. ASSERT_TRUE(svr.is_valid());
  14863. svr.Get("/test", [](const Request &, Response &res) {
  14864. res.set_content("test", "text/plain");
  14865. });
  14866. auto port = svr.bind_to_any_port(HOST);
  14867. ASSERT_LT(0, port);
  14868. thread t = thread([&]() { svr.listen_after_bind(); });
  14869. auto se = detail::scope_exit([&] {
  14870. svr.stop();
  14871. t.join();
  14872. ASSERT_FALSE(svr.is_running());
  14873. });
  14874. svr.wait_until_ready();
  14875. SSLClient cli(HOST, port);
  14876. cli.set_connection_timeout(30);
  14877. cli.enable_server_hostname_verification(false);
  14878. // cert.pem is not trusted, so the handshake fails
  14879. ASSERT_FALSE(cli.Get("/test"));
  14880. cli.enable_server_certificate_verification(false);
  14881. auto res = cli.Get("/test");
  14882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14883. EXPECT_EQ(0, res.ssl_error());
  14884. EXPECT_EQ(0UL, res.ssl_backend_error());
  14885. }
  14886. // PEM memory-based constructor tests (works with all TLS backends).
  14887. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14888. // terminator after it.
  14889. void PemMemoryClientCertPresent(
  14890. const std::string &client_cert_file,
  14891. const std::string &client_private_key_file,
  14892. const std::string &client_encrypted_private_key_pass = std::string(),
  14893. bool exact_size = false) {
  14894. // Read PEM files into memory
  14895. std::string server_cert_pem, server_key_pem;
  14896. std::string client_ca_pem;
  14897. std::string client_cert_pem, client_key_pem;
  14898. read_file(SERVER_CERT_FILE, server_cert_pem);
  14899. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14900. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14901. read_file(client_cert_file, client_cert_pem);
  14902. read_file(client_private_key_file, client_key_pem);
  14903. std::list<std::vector<char>> exact_copies;
  14904. auto data = [&](const std::string &pem) -> const char * {
  14905. if (!exact_size) { return pem.c_str(); }
  14906. exact_copies.emplace_back(pem.begin(), pem.end());
  14907. return exact_copies.back().data();
  14908. };
  14909. // Create server with PEM memory
  14910. SSLServer::PemMemory server_pem = {
  14911. data(server_cert_pem),
  14912. server_cert_pem.size(),
  14913. data(server_key_pem),
  14914. server_key_pem.size(),
  14915. data(client_ca_pem),
  14916. client_ca_pem.size(),
  14917. nullptr // no password for server key
  14918. };
  14919. SSLServer svr(server_pem);
  14920. ASSERT_TRUE(svr.is_valid());
  14921. svr.Get("/test", [&](const Request &req, Response &res) {
  14922. res.set_content("test", "text/plain");
  14923. auto cert = req.peer_cert();
  14924. ASSERT_TRUE(static_cast<bool>(cert));
  14925. EXPECT_EQ("Common Name", cert.subject_cn());
  14926. });
  14927. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14928. auto se = detail::scope_exit([&] {
  14929. svr.stop();
  14930. t.join();
  14931. ASSERT_FALSE(svr.is_running());
  14932. });
  14933. svr.wait_until_ready();
  14934. // Create client with PEM memory
  14935. const char *password = client_encrypted_private_key_pass.empty()
  14936. ? nullptr
  14937. : client_encrypted_private_key_pass.c_str();
  14938. SSLClient::PemMemory client_pem = {
  14939. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14940. client_key_pem.size(), password};
  14941. SSLClient cli(HOST, PORT, client_pem);
  14942. cli.enable_server_certificate_verification(false);
  14943. cli.set_connection_timeout(30);
  14944. auto res = cli.Get("/test");
  14945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14946. ASSERT_EQ(StatusCode::OK_200, res->status);
  14947. }
  14948. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14949. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14950. }
  14951. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14952. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14953. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14954. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14955. }
  14956. // A server built from PEM memory with a client CA requires client certificates,
  14957. // also when the CA is a NUL-terminated string passed with a length of 0
  14958. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14959. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14960. read_file(SERVER_CERT_FILE, server_cert_pem);
  14961. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14962. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14963. SSLServer::PemMemory server_pem = {
  14964. server_cert_pem.c_str(),
  14965. server_cert_pem.size(),
  14966. server_key_pem.c_str(),
  14967. server_key_pem.size(),
  14968. client_ca_pem.c_str(),
  14969. client_ca_pem.size(),
  14970. nullptr // no password for server key
  14971. };
  14972. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14973. SCOPED_TRACE(client_ca_pem_len);
  14974. server_pem.client_ca_pem_len = client_ca_pem_len;
  14975. SSLServer svr(server_pem);
  14976. ASSERT_TRUE(svr.is_valid());
  14977. RejectsClientWithoutCert(svr);
  14978. }
  14979. // An empty CA fails to load instead of turning the check off
  14980. server_pem.client_ca_pem = "";
  14981. server_pem.client_ca_pem_len = 0;
  14982. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14983. }
  14984. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14985. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14986. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14987. true);
  14988. }
  14989. // A length shorter than the PEM cuts it short, so it no longer loads
  14990. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14991. std::string cert, key;
  14992. read_file(SERVER_CERT_FILE, cert);
  14993. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14994. for (auto cut_cert : {true, false}) {
  14995. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14996. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14997. SSLServer::PemMemory server_pem = {
  14998. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14999. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  15000. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  15001. key_len, nullptr};
  15002. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  15003. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  15004. key.c_str(), key_len, nullptr};
  15005. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  15006. }
  15007. }
  15008. TEST(SSLClientServerTest, SSLConnectTimeout) {
  15009. class NoListenSSLServer : public SSLServer {
  15010. public:
  15011. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  15012. const char *client_ca_cert_file_path,
  15013. const char *client_ca_cert_dir_path = nullptr)
  15014. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  15015. client_ca_cert_dir_path),
  15016. stop_(false) {}
  15017. std::atomic_bool stop_;
  15018. private:
  15019. bool process_and_close_socket(socket_t /*sock*/) override {
  15020. // Don't create SSL context
  15021. while (!stop_.load()) {
  15022. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  15023. }
  15024. return true;
  15025. }
  15026. };
  15027. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15028. CLIENT_CA_CERT_FILE);
  15029. ASSERT_TRUE(svr.is_valid());
  15030. // Keep-alive parking would bypass the override.
  15031. svr.set_keep_alive_parking(false);
  15032. svr.Get("/test", [&](const Request &, Response &res) {
  15033. res.set_content("test", "text/plain");
  15034. });
  15035. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15036. auto se = detail::scope_exit([&] {
  15037. svr.stop_ = true;
  15038. svr.stop();
  15039. t.join();
  15040. ASSERT_FALSE(svr.is_running());
  15041. });
  15042. svr.wait_until_ready();
  15043. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15044. cli.enable_server_certificate_verification(false);
  15045. cli.set_connection_timeout(1);
  15046. auto res = cli.Get("/test");
  15047. ASSERT_TRUE(!res);
  15048. EXPECT_EQ(Error::SSLConnection, res.error());
  15049. // Timeout results in WantRead error code (maps to backend-specific value)
  15050. EXPECT_NE(0, res.ssl_error());
  15051. }
  15052. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  15053. // Test SSLServer with client certificate verification using the standard
  15054. // constructor (ContextSetupCallback is tested by backend-specific tests)
  15055. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  15056. CLIENT_CA_CERT_DIR);
  15057. ASSERT_TRUE(svr.is_valid());
  15058. svr.Get("/test", [&](const Request &req, Response &res) {
  15059. res.set_content("test", "text/plain");
  15060. auto cert = req.peer_cert();
  15061. ASSERT_TRUE(static_cast<bool>(cert));
  15062. auto common_name = cert.subject_cn();
  15063. EXPECT_EQ("Common Name", common_name);
  15064. });
  15065. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15066. auto se = detail::scope_exit([&] {
  15067. svr.stop();
  15068. t.join();
  15069. ASSERT_FALSE(svr.is_running());
  15070. });
  15071. svr.wait_until_ready();
  15072. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15073. cli.enable_server_certificate_verification(false);
  15074. cli.set_connection_timeout(30);
  15075. auto res = cli.Get("/test");
  15076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15077. ASSERT_EQ(StatusCode::OK_200, res->status);
  15078. }
  15079. // Test verify_hostname on every backend: a host is named by a SAN only
  15080. TEST(SSLClientServerTest, TlsVerifyHostname) {
  15081. using namespace httplib::tls;
  15082. // We need a running server to test against
  15083. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15084. ASSERT_TRUE(svr.is_valid());
  15085. svr.Get("/test", [](const Request &, Response &res) {
  15086. res.set_content("ok", "text/plain");
  15087. });
  15088. thread t([&]() { svr.listen(HOST, PORT); });
  15089. auto se = detail::scope_exit([&] {
  15090. svr.stop();
  15091. t.join();
  15092. });
  15093. svr.wait_until_ready();
  15094. bool verify_callback_called = false;
  15095. bool verify_result_wrong = false;
  15096. SSLClient cli(HOST, PORT);
  15097. cli.enable_server_certificate_verification(true);
  15098. cli.set_ca_cert_path(CA_CERT_FILE);
  15099. cli.set_connection_timeout(5);
  15100. // Note: Test certificate has CN="Common Name", not "localhost"
  15101. bool verify_result_cn = false;
  15102. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15103. verify_callback_called = true;
  15104. if (!ctx.cert) return false;
  15105. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  15106. verify_result_cn = ctx.check_hostname("Common Name");
  15107. // Test 2: wrong hostname should not match
  15108. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  15109. return true; // Accept for the purpose of this test
  15110. });
  15111. auto res = cli.Get("/test");
  15112. // The request may succeed or fail depending on cert configuration
  15113. // but the callback should have been called
  15114. ASSERT_TRUE(verify_callback_called)
  15115. << "Verify callback should have been called";
  15116. EXPECT_FALSE(verify_result_cn)
  15117. << "verify_hostname must not match the certificate CN (no SAN)";
  15118. // Wrong hostname should not match
  15119. EXPECT_FALSE(verify_result_wrong)
  15120. << "verify_hostname should not match 'wronghost.example.com'";
  15121. }
  15122. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  15123. // backend verifies it.
  15124. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  15125. // Certificate CN is "localhost" and it carries no SAN.
  15126. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15127. ASSERT_TRUE(svr.is_valid());
  15128. svr.Get("/test", [](const Request &, Response &res) {
  15129. res.set_content("ok", "text/plain");
  15130. });
  15131. auto port = svr.bind_to_any_port(HOST);
  15132. thread t([&]() { svr.listen_after_bind(); });
  15133. auto se = detail::scope_exit([&] {
  15134. svr.stop();
  15135. t.join();
  15136. });
  15137. svr.wait_until_ready();
  15138. SSLClient cli("localhost", port);
  15139. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  15140. cli.enable_server_certificate_verification(true);
  15141. cli.set_connection_timeout(5);
  15142. auto res = cli.Get("/test");
  15143. ASSERT_FALSE(res);
  15144. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  15145. // The same certificate is accepted once host name verification is off, so the
  15146. // failure above is the host name and not the chain.
  15147. cli.enable_server_hostname_verification(false);
  15148. res = cli.Get("/test");
  15149. ASSERT_TRUE(res) << to_string(res.error());
  15150. EXPECT_EQ(StatusCode::OK_200, res->status);
  15151. }
  15152. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  15153. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  15154. // X509_check_ip behavior and must hold for every backend.
  15155. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  15156. using namespace httplib::tls;
  15157. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  15158. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15159. ASSERT_TRUE(svr.is_valid());
  15160. svr.Get("/test", [](const Request &, Response &res) {
  15161. res.set_content("ok", "text/plain");
  15162. });
  15163. thread t([&]() { svr.listen(HOST, PORT); });
  15164. auto se = detail::scope_exit([&] {
  15165. svr.stop();
  15166. t.join();
  15167. });
  15168. svr.wait_until_ready();
  15169. bool verify_callback_called = false;
  15170. bool ip_matched_via_cn = true;
  15171. SSLClient cli(HOST, PORT);
  15172. cli.enable_server_certificate_verification(true);
  15173. cli.set_ca_cert_path(CA_CERT_FILE);
  15174. cli.set_connection_timeout(5);
  15175. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15176. verify_callback_called = true;
  15177. if (!ctx.cert) return false;
  15178. // The IP appears only in the CN, so it must NOT be accepted.
  15179. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  15180. return true; // Accept for the purpose of this test
  15181. });
  15182. cli.Get("/test");
  15183. ASSERT_TRUE(verify_callback_called)
  15184. << "Verify callback should have been called";
  15185. EXPECT_FALSE(ip_matched_via_cn)
  15186. << "An IP host must not be authenticated via the certificate CN";
  15187. }
  15188. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  15189. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  15190. using namespace httplib::tls;
  15191. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  15192. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  15193. ASSERT_TRUE(svr.is_valid());
  15194. svr.Get("/test", [](const Request &, Response &res) {
  15195. res.set_content("ok", "text/plain");
  15196. });
  15197. thread t([&]() { svr.listen(HOST, PORT); });
  15198. auto se = detail::scope_exit([&] {
  15199. svr.stop();
  15200. t.join();
  15201. });
  15202. svr.wait_until_ready();
  15203. bool verify_callback_called = false;
  15204. bool san_matched = false;
  15205. bool wrong_ipv6_matched = true;
  15206. bool cn_ipv6_matched = true;
  15207. SSLClient cli(HOST, PORT);
  15208. cli.enable_server_certificate_verification(true);
  15209. cli.set_ca_cert_path(CA_CERT_FILE);
  15210. cli.set_connection_timeout(5);
  15211. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15212. verify_callback_called = true;
  15213. if (!ctx.cert) return false;
  15214. // Matches the IPv6 iPAddress SAN.
  15215. san_matched = ctx.check_hostname("2001:db8::1");
  15216. // A different IPv6 address must not match.
  15217. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  15218. // "::1" lives only in the CN, so it must not be accepted.
  15219. cn_ipv6_matched = ctx.check_hostname("::1");
  15220. return true; // Accept for the purpose of this test
  15221. });
  15222. cli.Get("/test");
  15223. ASSERT_TRUE(verify_callback_called)
  15224. << "Verify callback should have been called";
  15225. EXPECT_TRUE(san_matched)
  15226. << "verify_hostname should match an IPv6 iPAddress SAN";
  15227. EXPECT_FALSE(wrong_ipv6_matched)
  15228. << "verify_hostname should not match a non-matching IPv6 address";
  15229. EXPECT_FALSE(cn_ipv6_matched)
  15230. << "An IPv6 host must not be authenticated via the certificate CN";
  15231. }
  15232. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  15233. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  15234. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15235. using namespace httplib::tls;
  15236. // SANs: DNS:a.zz, IP:42.46.122.122
  15237. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15238. ASSERT_TRUE(svr.is_valid());
  15239. svr.Get("/test", [](const Request &, Response &res) {
  15240. res.set_content("ok", "text/plain");
  15241. });
  15242. auto port = svr.bind_to_any_port(HOST);
  15243. thread t([&]() { svr.listen_after_bind(); });
  15244. auto se = detail::scope_exit([&] {
  15245. svr.stop();
  15246. t.join();
  15247. });
  15248. svr.wait_until_ready();
  15249. bool verify_callback_called = false;
  15250. bool dns_san_matched = false;
  15251. bool ip_san_matched = false;
  15252. bool ip_matched_via_dns_san = true;
  15253. bool dns_matched_via_ip_san = true;
  15254. bool cn_matched_next_to_dns_san = true;
  15255. SSLClient cli(HOST, port);
  15256. cli.enable_server_certificate_verification(true);
  15257. cli.set_ca_cert_path(CA_CERT_FILE);
  15258. cli.set_connection_timeout(5);
  15259. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15260. verify_callback_called = true;
  15261. if (!ctx.cert) return false;
  15262. dns_san_matched = ctx.check_hostname("a.zz");
  15263. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15264. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15265. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15266. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15267. return true; // Accept for the purpose of this test
  15268. });
  15269. cli.Get("/test");
  15270. ASSERT_TRUE(verify_callback_called)
  15271. << "Verify callback should have been called";
  15272. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15273. EXPECT_TRUE(ip_san_matched)
  15274. << "verify_hostname should match an iPAddress SAN";
  15275. EXPECT_FALSE(ip_matched_via_dns_san)
  15276. << "An IP host must not be authenticated via a dNSName SAN";
  15277. EXPECT_FALSE(dns_matched_via_ip_san)
  15278. << "A DNS host must not be authenticated via an iPAddress SAN";
  15279. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15280. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15281. }
  15282. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15283. // "www.*.example.test" names one host and not every host under example.test.
  15284. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15285. using namespace httplib::tls;
  15286. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15287. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15288. ASSERT_TRUE(svr.is_valid());
  15289. svr.Get("/test", [](const Request &, Response &res) {
  15290. res.set_content("ok", "text/plain");
  15291. });
  15292. auto port = svr.bind_to_any_port(HOST);
  15293. thread t([&]() { svr.listen_after_bind(); });
  15294. auto se = detail::scope_exit([&] {
  15295. svr.stop();
  15296. t.join();
  15297. });
  15298. svr.wait_until_ready();
  15299. bool verify_callback_called = false;
  15300. bool leftmost_wildcard_matched = false;
  15301. bool wildcard_spanned_labels = true;
  15302. bool inner_wildcard_matched = true;
  15303. SSLClient cli(HOST, port);
  15304. cli.enable_server_certificate_verification(true);
  15305. cli.set_ca_cert_path(CA_CERT_FILE);
  15306. cli.set_connection_timeout(5);
  15307. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15308. verify_callback_called = true;
  15309. if (!ctx.cert) return false;
  15310. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15311. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15312. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15313. return true; // Accept for the purpose of this test
  15314. });
  15315. cli.Get("/test");
  15316. ASSERT_TRUE(verify_callback_called)
  15317. << "Verify callback should have been called";
  15318. EXPECT_TRUE(leftmost_wildcard_matched)
  15319. << "A leftmost wildcard should match a single label";
  15320. EXPECT_FALSE(wildcard_spanned_labels)
  15321. << "A wildcard label must not match more than one label";
  15322. EXPECT_FALSE(inner_wildcard_matched)
  15323. << "A wildcard outside the leftmost label must not be honoured";
  15324. }
  15325. // sans() must report each SAN entry under its own type.
  15326. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15327. using namespace httplib::tls;
  15328. // SANs: DNS:a.zz, IP:42.46.122.122
  15329. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15330. ASSERT_TRUE(svr.is_valid());
  15331. svr.Get("/test", [](const Request &, Response &res) {
  15332. res.set_content("ok", "text/plain");
  15333. });
  15334. auto port = svr.bind_to_any_port(HOST);
  15335. thread t([&]() { svr.listen_after_bind(); });
  15336. auto se = detail::scope_exit([&] {
  15337. svr.stop();
  15338. t.join();
  15339. });
  15340. svr.wait_until_ready();
  15341. bool verify_callback_called = false;
  15342. std::vector<SanEntry> sans;
  15343. SSLClient cli(HOST, port);
  15344. cli.enable_server_certificate_verification(true);
  15345. cli.set_ca_cert_path(CA_CERT_FILE);
  15346. cli.set_connection_timeout(5);
  15347. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15348. verify_callback_called = true;
  15349. if (!ctx.cert) return false;
  15350. sans = ctx.sans();
  15351. return true; // Accept for the purpose of this test
  15352. });
  15353. cli.Get("/test");
  15354. ASSERT_TRUE(verify_callback_called)
  15355. << "Verify callback should have been called";
  15356. auto has_san = [&](SanType type, const std::string &value) {
  15357. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15358. return san.type == type && san.value == value;
  15359. });
  15360. };
  15361. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15362. << "sans() should report the dNSName SAN";
  15363. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15364. << "sans() should report the iPAddress SAN";
  15365. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15366. << "sans() must not report the dNSName SAN as an address";
  15367. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15368. << "sans() must not report the iPAddress SAN as a DNS name";
  15369. }
  15370. #endif
  15371. // mbedTLS-specific callback constructor test
  15372. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15373. #ifdef CPPHTTPLIB_SSL_ENABLED
  15374. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15375. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15376. ASSERT_TRUE(svr.is_valid());
  15377. // Set up a handler to verify client certificate is present
  15378. bool client_cert_verified = false;
  15379. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15380. // Verify that client certificate was provided
  15381. client_cert_verified = true;
  15382. res.set_content("success", "text/plain");
  15383. });
  15384. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15385. auto se = detail::scope_exit([&] {
  15386. svr.stop();
  15387. t.join();
  15388. ASSERT_FALSE(svr.is_running());
  15389. });
  15390. svr.wait_until_ready();
  15391. // Client with certificate
  15392. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15393. cli.enable_server_certificate_verification(false);
  15394. cli.set_connection_timeout(30);
  15395. auto res = cli.Get("/test");
  15396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15397. ASSERT_EQ(StatusCode::OK_200, res->status);
  15398. ASSERT_TRUE(client_cert_verified);
  15399. EXPECT_EQ("success", res->body);
  15400. }
  15401. #endif
  15402. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15403. // backends
  15404. #ifdef CPPHTTPLIB_SSL_ENABLED
  15405. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15406. using namespace httplib::tls;
  15407. // Test that when client CA cert file is provided,
  15408. // the server properly requests and validates client certificates
  15409. // Create a server with client authentication
  15410. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15411. ASSERT_TRUE(svr.is_valid());
  15412. bool handler_called = false;
  15413. svr.Get("/test", [&](const Request &req, Response &res) {
  15414. handler_called = true;
  15415. // Verify that a client certificate was provided
  15416. auto cert = req.peer_cert();
  15417. ASSERT_TRUE(static_cast<bool>(cert));
  15418. // Get the issuer name
  15419. std::string issuer_str = cert.issuer_name();
  15420. ASSERT_FALSE(issuer_str.empty());
  15421. // The client certificate should be issued by our test CA
  15422. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15423. res.set_content("authenticated", "text/plain");
  15424. });
  15425. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15426. auto se = detail::scope_exit([&] {
  15427. svr.stop();
  15428. t.join();
  15429. ASSERT_FALSE(svr.is_running());
  15430. });
  15431. svr.wait_until_ready();
  15432. // Connect with a client certificate issued by the CA
  15433. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15434. cli.enable_server_certificate_verification(false);
  15435. cli.set_connection_timeout(30);
  15436. auto res = cli.Get("/test");
  15437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15438. ASSERT_EQ(StatusCode::OK_200, res->status);
  15439. ASSERT_TRUE(handler_called);
  15440. EXPECT_EQ("authenticated", res->body);
  15441. }
  15442. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15443. using namespace httplib::tls;
  15444. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15445. ASSERT_TRUE(svr.is_valid());
  15446. svr.Get("/test", [](const Request &, Response &res) {
  15447. res.set_content("ok", "text/plain");
  15448. });
  15449. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15450. auto se = detail::scope_exit([&] {
  15451. svr.stop();
  15452. t.join();
  15453. });
  15454. svr.wait_until_ready();
  15455. SSLClient cli(HOST, PORT);
  15456. cli.enable_server_certificate_verification(false);
  15457. cli.set_connection_timeout(30);
  15458. bool cert_checked = false;
  15459. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15460. if (ctx.cert) {
  15461. auto sans = ctx.sans();
  15462. // Test certificate may or may not have SANs - just verify the API
  15463. // works If SANs exist, verify the types are valid
  15464. for (const auto &san : sans) {
  15465. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15466. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15467. san.type == SanType::OTHER);
  15468. EXPECT_FALSE(san.value.empty());
  15469. }
  15470. cert_checked = true;
  15471. }
  15472. return true;
  15473. });
  15474. auto res = cli.Get("/test");
  15475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15476. EXPECT_TRUE(cert_checked);
  15477. }
  15478. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15479. using namespace httplib::tls;
  15480. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15481. ASSERT_TRUE(svr.is_valid());
  15482. svr.Get("/test", [](const Request &, Response &res) {
  15483. res.set_content("ok", "text/plain");
  15484. });
  15485. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15486. auto se = detail::scope_exit([&] {
  15487. svr.stop();
  15488. t.join();
  15489. });
  15490. svr.wait_until_ready();
  15491. SSLClient cli(HOST, PORT);
  15492. cli.enable_server_certificate_verification(false);
  15493. cli.set_connection_timeout(30);
  15494. bool validity_checked = false;
  15495. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15496. if (ctx.cert) {
  15497. time_t not_before = 0, not_after = 0;
  15498. bool result = ctx.validity(not_before, not_after);
  15499. EXPECT_TRUE(result);
  15500. // Verify that not_before < now < not_after for a valid cert
  15501. time_t now = time(nullptr);
  15502. EXPECT_LT(not_before, now);
  15503. EXPECT_GT(not_after, now);
  15504. validity_checked = true;
  15505. }
  15506. return true;
  15507. });
  15508. auto res = cli.Get("/test");
  15509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15510. EXPECT_TRUE(validity_checked);
  15511. }
  15512. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15513. using namespace httplib::tls;
  15514. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15515. ASSERT_TRUE(svr.is_valid());
  15516. svr.Get("/test", [](const Request &, Response &res) {
  15517. res.set_content("ok", "text/plain");
  15518. });
  15519. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15520. auto se = detail::scope_exit([&] {
  15521. svr.stop();
  15522. t.join();
  15523. });
  15524. svr.wait_until_ready();
  15525. SSLClient cli(HOST, PORT);
  15526. cli.enable_server_certificate_verification(false);
  15527. cli.set_connection_timeout(30);
  15528. bool serial_checked = false;
  15529. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15530. if (ctx.cert) {
  15531. std::string serial = ctx.serial();
  15532. EXPECT_FALSE(serial.empty());
  15533. // Serial should be a hex string
  15534. for (char c : serial) {
  15535. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15536. (c >= 'a' && c <= 'f'));
  15537. }
  15538. serial_checked = true;
  15539. }
  15540. return true;
  15541. });
  15542. auto res = cli.Get("/test");
  15543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15544. EXPECT_TRUE(serial_checked);
  15545. }
  15546. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15547. // Test 1: Valid CA file - no error should be recorded
  15548. {
  15549. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15550. CLIENT_CA_CERT_FILE);
  15551. ASSERT_TRUE(svr.is_valid());
  15552. // With valid setup, last_ssl_error should be 0
  15553. EXPECT_EQ(0, svr.ssl_last_error());
  15554. }
  15555. // Test 2: Invalid CA file content
  15556. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15557. {
  15558. // Create a temporary file with completely invalid content
  15559. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15560. {
  15561. std::ofstream ofs(temp_invalid_ca);
  15562. ofs << "This is not a certificate file at all\n";
  15563. ofs << "Just plain text content\n";
  15564. }
  15565. // Create server with invalid CA file
  15566. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15567. // Clean up temporary file
  15568. std::remove(temp_invalid_ca);
  15569. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15570. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15571. // Note: SSL_CTX_load_verify_locations typically fails first,
  15572. // but our error handling code path is still exercised
  15573. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15574. }
  15575. }
  15576. TEST(VerifyCallbackTest, VerifyContextFields) {
  15577. using namespace httplib::tls;
  15578. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15579. ASSERT_TRUE(svr.is_valid());
  15580. svr.Get("/test", [](const Request &, Response &res) {
  15581. res.set_content("ok", "text/plain");
  15582. });
  15583. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15584. auto se = detail::scope_exit([&] {
  15585. svr.stop();
  15586. t.join();
  15587. });
  15588. svr.wait_until_ready();
  15589. SSLClient cli(HOST, PORT);
  15590. cli.enable_server_certificate_verification(false);
  15591. cli.set_connection_timeout(30);
  15592. int callback_count = 0;
  15593. bool saw_leaf_cert = false;
  15594. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15595. if (ctx.cert) {
  15596. callback_count++;
  15597. // We should see at least one certificate (the leaf)
  15598. std::string cn = ctx.subject_cn();
  15599. if (!cn.empty()) { saw_leaf_cert = true; }
  15600. // Verify context fields are populated
  15601. EXPECT_NE(ctx.session, nullptr);
  15602. EXPECT_GE(ctx.depth, 0);
  15603. }
  15604. return true;
  15605. });
  15606. auto res = cli.Get("/test");
  15607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15608. EXPECT_GT(callback_count, 0);
  15609. EXPECT_TRUE(saw_leaf_cert);
  15610. }
  15611. // A verifier that accepts runs alongside the built-in verification, and is the
  15612. // only check once that is turned off.
  15613. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15614. using namespace httplib::tls;
  15615. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15616. ASSERT_TRUE(svr.is_valid());
  15617. svr.Get("/test", [](const Request &, Response &res) {
  15618. res.set_content("ok", "text/plain");
  15619. });
  15620. auto port = svr.bind_to_any_port(HOST);
  15621. thread t([&]() { svr.listen_after_bind(); });
  15622. auto se = detail::scope_exit([&] {
  15623. svr.stop();
  15624. t.join();
  15625. });
  15626. svr.wait_until_ready();
  15627. SSLClient cli(HOST, port);
  15628. cli.enable_server_hostname_verification(false);
  15629. auto calls = 0;
  15630. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15631. calls++;
  15632. return true;
  15633. });
  15634. // cert.pem is not trusted
  15635. auto res = cli.Get("/test");
  15636. ASSERT_FALSE(res);
  15637. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15638. EXPECT_GT(calls, 0);
  15639. cli.enable_server_certificate_verification(false);
  15640. res = cli.Get("/test");
  15641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15642. EXPECT_EQ("ok", res->body);
  15643. }
  15644. // A verifier belongs to the client that set it, not to the thread that set it.
  15645. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15646. using namespace httplib::tls;
  15647. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15648. ASSERT_TRUE(svr.is_valid());
  15649. svr.Get("/test", [](const Request &, Response &res) {
  15650. res.set_content("ok", "text/plain");
  15651. });
  15652. auto port = svr.bind_to_any_port(HOST);
  15653. thread t([&]() { svr.listen_after_bind(); });
  15654. auto se = detail::scope_exit([&] {
  15655. svr.stop();
  15656. t.join();
  15657. });
  15658. svr.wait_until_ready();
  15659. auto rejecting_calls = 0;
  15660. SSLClient rejecting(HOST, port);
  15661. rejecting.enable_server_certificate_verification(false);
  15662. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15663. rejecting_calls++;
  15664. return false;
  15665. });
  15666. auto accepting_calls = 0;
  15667. SSLClient accepting(HOST, port);
  15668. accepting.enable_server_certificate_verification(false);
  15669. // Set on another thread than the requests below.
  15670. thread([&]() {
  15671. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15672. accepting_calls++;
  15673. return true;
  15674. });
  15675. }).join();
  15676. // Requested on another thread than the verifier was set on.
  15677. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15678. EXPECT_GT(rejecting_calls, 0);
  15679. auto res = accepting.Get("/test");
  15680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15681. EXPECT_GT(accepting_calls, 0);
  15682. }
  15683. // A verifier replaced while a handshake runs it lives until it returns.
  15684. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15685. using namespace httplib::tls;
  15686. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15687. ASSERT_TRUE(svr.is_valid());
  15688. svr.Get("/test", [](const Request &, Response &res) {
  15689. res.set_content("ok", "text/plain");
  15690. });
  15691. auto port = svr.bind_to_any_port(HOST);
  15692. thread t([&]() { svr.listen_after_bind(); });
  15693. auto se = detail::scope_exit([&] {
  15694. svr.stop();
  15695. t.join();
  15696. });
  15697. svr.wait_until_ready();
  15698. SSLClient cli(HOST, port);
  15699. cli.enable_server_certificate_verification(false);
  15700. std::promise<void> entered;
  15701. std::promise<void> replaced;
  15702. auto replaced_future = replaced.get_future();
  15703. auto first_call = true;
  15704. // Long enough to live on the heap
  15705. std::string expected(64, 'v');
  15706. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15707. if (first_call) {
  15708. first_call = false;
  15709. entered.set_value();
  15710. replaced_future.wait();
  15711. }
  15712. return expected == std::string(64, 'v');
  15713. });
  15714. thread request([&]() {
  15715. auto res = cli.Get("/test");
  15716. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15717. });
  15718. entered.get_future().wait();
  15719. cli.set_server_certificate_verifier(
  15720. [](const VerifyContext &) { return true; });
  15721. replaced.set_value();
  15722. request.join();
  15723. }
  15724. // VerifyContext::session is the same handle the other tls:: functions take.
  15725. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15726. using namespace httplib::tls;
  15727. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15728. ASSERT_TRUE(svr.is_valid());
  15729. svr.Get("/test", [](const Request &, Response &res) {
  15730. res.set_content("ok", "text/plain");
  15731. });
  15732. auto port = svr.bind_to_any_port(HOST);
  15733. thread t([&]() { svr.listen_after_bind(); });
  15734. auto se = detail::scope_exit([&] {
  15735. svr.stop();
  15736. t.join();
  15737. });
  15738. svr.wait_until_ready();
  15739. SSLClient cli(HOST, port);
  15740. cli.enable_server_certificate_verification(false);
  15741. session_t verifier_session = nullptr;
  15742. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15743. verifier_session = ctx.session;
  15744. return true;
  15745. });
  15746. session_t session_verifier_session = nullptr;
  15747. cli.set_session_verifier([&](session_t session) {
  15748. session_verifier_session = session;
  15749. return SSLVerifierResponse::NoDecisionMade;
  15750. });
  15751. auto res = cli.Get("/test");
  15752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15753. EXPECT_NE(nullptr, verifier_session);
  15754. EXPECT_EQ(session_verifier_session, verifier_session);
  15755. }
  15756. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15757. using httplib::tls::TlsError;
  15758. // Test that verify_error_to_string returns empty for success
  15759. std::string success_str = TlsError::verify_error_to_string(0);
  15760. EXPECT_TRUE(success_str.empty());
  15761. // Test that verify_error_to_string returns non-empty for error codes
  15762. // Using a common error code (certificate expired)
  15763. std::string error_str =
  15764. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15765. EXPECT_FALSE(error_str.empty());
  15766. }
  15767. TEST(SessionVerifierTest, CertificateAccepted) {
  15768. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15769. ASSERT_TRUE(svr.is_valid());
  15770. svr.Get("/test", [](const Request &, Response &res) {
  15771. res.set_content("ok", "text/plain");
  15772. });
  15773. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15774. auto se = detail::scope_exit([&] {
  15775. svr.stop();
  15776. t.join();
  15777. });
  15778. svr.wait_until_ready();
  15779. SSLClient cli(HOST, PORT);
  15780. cli.enable_server_certificate_verification(false);
  15781. cli.set_connection_timeout(30);
  15782. bool callback_called = false;
  15783. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15784. EXPECT_NE(session, nullptr);
  15785. callback_called = true;
  15786. return SSLVerifierResponse::CertificateAccepted;
  15787. });
  15788. auto res = cli.Get("/test");
  15789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15790. EXPECT_EQ(200, res->status);
  15791. EXPECT_TRUE(callback_called);
  15792. }
  15793. TEST(SessionVerifierTest, CertificateRejected) {
  15794. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15795. ASSERT_TRUE(svr.is_valid());
  15796. svr.Get("/test", [](const Request &, Response &res) {
  15797. res.set_content("ok", "text/plain");
  15798. });
  15799. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15800. auto se = detail::scope_exit([&] {
  15801. svr.stop();
  15802. t.join();
  15803. });
  15804. svr.wait_until_ready();
  15805. SSLClient cli(HOST, PORT);
  15806. cli.enable_server_certificate_verification(false);
  15807. cli.set_connection_timeout(30);
  15808. bool callback_called = false;
  15809. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15810. EXPECT_NE(session, nullptr);
  15811. callback_called = true;
  15812. return SSLVerifierResponse::CertificateRejected;
  15813. });
  15814. auto res = cli.Get("/test");
  15815. EXPECT_FALSE(res);
  15816. EXPECT_TRUE(callback_called);
  15817. }
  15818. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15819. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15820. ASSERT_TRUE(svr.is_valid());
  15821. svr.Get("/test", [](const Request &, Response &res) {
  15822. res.set_content("ok", "text/plain");
  15823. });
  15824. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15825. auto se = detail::scope_exit([&] {
  15826. svr.stop();
  15827. t.join();
  15828. });
  15829. svr.wait_until_ready();
  15830. // NoDecisionMade with verification disabled should succeed (no default check)
  15831. SSLClient cli(HOST, PORT);
  15832. cli.enable_server_certificate_verification(false);
  15833. cli.set_connection_timeout(30);
  15834. bool callback_called = false;
  15835. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15836. EXPECT_NE(session, nullptr);
  15837. callback_called = true;
  15838. return SSLVerifierResponse::NoDecisionMade;
  15839. });
  15840. auto res = cli.Get("/test");
  15841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15842. EXPECT_EQ(200, res->status);
  15843. EXPECT_TRUE(callback_called);
  15844. }
  15845. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15846. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15847. ASSERT_TRUE(svr.is_valid());
  15848. svr.Get("/test", [](const Request &, Response &res) {
  15849. res.set_content("ok", "text/plain");
  15850. });
  15851. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15852. auto se = detail::scope_exit([&] {
  15853. svr.stop();
  15854. t.join();
  15855. });
  15856. svr.wait_until_ready();
  15857. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15858. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15859. // so we only check that the request fails, not whether the callback was
  15860. // called.
  15861. SSLClient cli(HOST, PORT);
  15862. cli.enable_server_certificate_verification(true);
  15863. cli.set_connection_timeout(30);
  15864. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15865. EXPECT_NE(session, nullptr);
  15866. return SSLVerifierResponse::NoDecisionMade;
  15867. });
  15868. auto res = cli.Get("/test");
  15869. EXPECT_FALSE(res);
  15870. }
  15871. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15872. // Test SSL server using PemMemory constructor with client CA certificates
  15873. // Read PEM files
  15874. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15875. read_file(SERVER_CERT_FILE, server_cert_pem);
  15876. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15877. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15878. // Create SSLServer with PemMemory constructor including client CA
  15879. SSLServer::PemMemory server_pem = {
  15880. server_cert_pem.c_str(),
  15881. server_cert_pem.size(),
  15882. server_key_pem.c_str(),
  15883. server_key_pem.size(),
  15884. client_ca_pem.c_str(),
  15885. client_ca_pem.size(),
  15886. nullptr // no password for server key
  15887. };
  15888. SSLServer svr(server_pem);
  15889. ASSERT_TRUE(svr.is_valid());
  15890. // No SSL error should be recorded for valid setup
  15891. EXPECT_EQ(0, svr.ssl_last_error());
  15892. // Set up server endpoints
  15893. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15894. res.set_content("ok", "text/plain");
  15895. });
  15896. // Start server in a thread
  15897. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15898. svr.wait_until_ready();
  15899. // Connect with client certificate (using constructor with paths)
  15900. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15901. cli.enable_server_certificate_verification(false);
  15902. auto res = cli.Get("/test-pem-ca");
  15903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15904. EXPECT_EQ(200, res->status);
  15905. EXPECT_EQ("ok", res->body);
  15906. svr.stop();
  15907. server_thread.join();
  15908. }
  15909. #endif
  15910. #ifdef _WIN32
  15911. TEST(CleanupTest, WSACleanup) {
  15912. int ret = WSACleanup();
  15913. ASSERT_EQ(0, ret);
  15914. }
  15915. #endif
  15916. #ifndef CPPHTTPLIB_SSL_ENABLED
  15917. TEST(NoSSLSupport, SimpleInterface) {
  15918. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15919. }
  15920. #endif
  15921. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15922. TEST(InvalidScheme, SimpleInterface) {
  15923. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15924. }
  15925. #endif
  15926. TEST(NoScheme, SimpleInterface) {
  15927. Client cli("yahoo.com:80");
  15928. ASSERT_TRUE(cli.is_valid());
  15929. }
  15930. TEST(SendAPI, SimpleInterface_Online) {
  15931. Client cli("http://yahoo.com");
  15932. Request req;
  15933. req.method = "GET";
  15934. req.path = "/";
  15935. auto res = cli.send(req);
  15936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15937. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15938. }
  15939. TEST(SendAPI, WithParamsInRequest) {
  15940. Server svr;
  15941. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15942. EXPECT_TRUE(req.has_param("test"));
  15943. EXPECT_EQ("test_value", req.get_param_value("test"));
  15944. });
  15945. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15946. auto se = detail::scope_exit([&] {
  15947. svr.stop();
  15948. t.join();
  15949. ASSERT_FALSE(svr.is_running());
  15950. });
  15951. svr.wait_until_ready();
  15952. Client cli(HOST, PORT);
  15953. {
  15954. Request req;
  15955. req.method = "GET";
  15956. req.path = "/";
  15957. req.params.emplace("test", "test_value");
  15958. auto res = cli.send(req);
  15959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15960. }
  15961. {
  15962. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15964. }
  15965. }
  15966. TEST(ClientImplMethods, GetSocketTest) {
  15967. httplib::Server svr;
  15968. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15969. res.status = StatusCode::OK_200;
  15970. });
  15971. auto port = svr.bind_to_any_port("127.0.0.1");
  15972. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15973. auto se = detail::scope_exit([&] {
  15974. svr.stop();
  15975. thread.join();
  15976. ASSERT_FALSE(svr.is_running());
  15977. });
  15978. svr.wait_until_ready();
  15979. {
  15980. httplib::Client cli("127.0.0.1", port);
  15981. cli.set_keep_alive(true);
  15982. // Use the behavior of cpp-httplib of opening the connection
  15983. // only when the first request happens. If that changes,
  15984. // this test would be obsolete.
  15985. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15986. // This also implicitly tests the server. But other tests would fail much
  15987. // earlier than this one to be considered.
  15988. auto res = cli.Get("/");
  15989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15990. EXPECT_EQ(StatusCode::OK_200, res->status);
  15991. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15992. }
  15993. }
  15994. #ifdef CPPHTTPLIB_SSL_ENABLED
  15995. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15996. Client cli("http://yahoo.com");
  15997. auto res = cli.Get("/");
  15998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15999. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  16000. cli.set_follow_location(true);
  16001. res = cli.Get("/");
  16002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16003. EXPECT_EQ(StatusCode::OK_200, res->status);
  16004. EXPECT_EQ("https://www.yahoo.com/", res->location);
  16005. }
  16006. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  16007. Client cli("https://yahoo.com");
  16008. auto res = cli.Get("/");
  16009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16010. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  16011. cli.set_follow_location(true);
  16012. res = cli.Get("/");
  16013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16014. EXPECT_EQ(StatusCode::OK_200, res->status);
  16015. EXPECT_EQ("https://www.yahoo.com/", res->location);
  16016. }
  16017. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  16018. Client cli("https://yahoo.com");
  16019. auto res = cli.Get("/");
  16020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16021. ASSERT_FALSE(!res);
  16022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16023. ASSERT_FALSE(res == nullptr);
  16024. ASSERT_TRUE(res != nullptr);
  16025. EXPECT_EQ(Error::Success, res.error());
  16026. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  16027. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  16028. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  16029. cli.set_follow_location(true);
  16030. res = cli.Get("/");
  16031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16032. EXPECT_EQ(Error::Success, res.error());
  16033. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  16034. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  16035. EXPECT_EQ(StatusCode::OK_200, res->status);
  16036. EXPECT_EQ("https://www.yahoo.com/", res->location);
  16037. }
  16038. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  16039. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  16040. Client cli("https://cdnjs.cloudflare.com");
  16041. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  16042. Headers{{"Accept-Encoding", "br"}});
  16043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16044. EXPECT_EQ(StatusCode::OK_200, res->status);
  16045. EXPECT_EQ(287630U, res->body.size());
  16046. EXPECT_EQ("application/javascript; charset=utf-8",
  16047. res->get_header_value("Content-Type"));
  16048. }
  16049. #endif
  16050. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  16051. #undef REDIR_HOST // Silence compiler warning
  16052. #define REDIR_HOST "https://httpbingo.org"
  16053. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  16054. Client cli(REDIR_HOST);
  16055. cli.set_follow_location(true);
  16056. auto res = retry_service_failures([&] {
  16057. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  16058. });
  16059. SKIP_ON_SERVICE_FAILURE(res);
  16060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16061. EXPECT_EQ(StatusCode::OK_200, res->status);
  16062. }
  16063. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  16064. Client cli(REDIR_HOST);
  16065. cli.set_follow_location(true);
  16066. Params params;
  16067. params.emplace("url", "http://example.com");
  16068. params.emplace("status_code", "302");
  16069. auto res = retry_service_failures(
  16070. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  16071. SKIP_ON_SERVICE_FAILURE(res);
  16072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16073. EXPECT_EQ(StatusCode::OK_200, res->status);
  16074. }
  16075. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  16076. Client cli(REDIR_HOST);
  16077. cli.set_follow_location(true);
  16078. Params params;
  16079. params.emplace("url", "http://example.com");
  16080. auto res = retry_service_failures([&] {
  16081. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  16082. });
  16083. SKIP_ON_SERVICE_FAILURE(res);
  16084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16085. EXPECT_EQ(StatusCode::OK_200, res->status);
  16086. }
  16087. TEST(HttpToHttpsRedirectTest, CertFile) {
  16088. auto ssl_port = PORT + 1;
  16089. Server svr;
  16090. ASSERT_TRUE(svr.is_valid());
  16091. svr.Get("/index", [&](const Request &, Response &res) {
  16092. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16093. "/index");
  16094. svr.stop();
  16095. });
  16096. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16097. ASSERT_TRUE(ssl_svr.is_valid());
  16098. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  16099. res.set_content("test", "text/plain");
  16100. ssl_svr.stop();
  16101. });
  16102. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16103. thread t2 =
  16104. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  16105. auto se = detail::scope_exit([&] {
  16106. t2.join();
  16107. t.join();
  16108. ASSERT_FALSE(svr.is_running());
  16109. });
  16110. svr.wait_until_ready();
  16111. ssl_svr.wait_until_ready();
  16112. Client cli("127.0.0.1", PORT);
  16113. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16114. cli.enable_server_certificate_verification(true);
  16115. cli.set_follow_location(true);
  16116. cli.set_connection_timeout(30);
  16117. auto res = cli.Get("/index");
  16118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16119. ASSERT_EQ(StatusCode::OK_200, res->status);
  16120. }
  16121. TEST(UppercaseSchemeTest, UsesTLS) {
  16122. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16123. ASSERT_TRUE(ssl_svr.is_valid());
  16124. ssl_svr.Get("/index", [](const Request &, Response &res) {
  16125. res.set_content("test", "text/plain");
  16126. });
  16127. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  16128. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  16129. Server svr;
  16130. svr.Get("/index", [&](const Request &, Response &res) {
  16131. res.set_redirect(https_url + "/index");
  16132. });
  16133. auto port = svr.bind_to_any_port("127.0.0.1");
  16134. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  16135. auto t2 = thread([&] { svr.listen_after_bind(); });
  16136. auto se = detail::scope_exit([&] {
  16137. svr.stop();
  16138. ssl_svr.stop();
  16139. t2.join();
  16140. t.join();
  16141. });
  16142. ssl_svr.wait_until_ready();
  16143. svr.wait_until_ready();
  16144. {
  16145. Client cli(https_url);
  16146. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16147. auto res = cli.Get("/index");
  16148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16149. EXPECT_EQ("test", res->body);
  16150. }
  16151. {
  16152. Client cli("127.0.0.1", port);
  16153. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16154. cli.set_follow_location(true);
  16155. auto res = cli.Get("/index");
  16156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16157. EXPECT_EQ("test", res->body);
  16158. }
  16159. }
  16160. TEST(SSLClientRedirectTest, CertFile) {
  16161. auto ssl_port = PORT + 1;
  16162. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16163. ASSERT_TRUE(ssl_svr1.is_valid());
  16164. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16165. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16166. "/index");
  16167. ssl_svr1.stop();
  16168. });
  16169. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16170. ASSERT_TRUE(ssl_svr2.is_valid());
  16171. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16172. res.set_content("test", "text/plain");
  16173. ssl_svr2.stop();
  16174. });
  16175. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16176. thread t2 =
  16177. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16178. auto se = detail::scope_exit([&] {
  16179. t2.join();
  16180. t.join();
  16181. ASSERT_FALSE(ssl_svr1.is_running());
  16182. });
  16183. ssl_svr1.wait_until_ready();
  16184. ssl_svr2.wait_until_ready();
  16185. SSLClient cli("127.0.0.1", PORT);
  16186. std::string cert;
  16187. read_file(SERVER_CERT2_FILE, cert);
  16188. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16189. cli.enable_server_certificate_verification(true);
  16190. cli.set_follow_location(true);
  16191. cli.set_connection_timeout(30);
  16192. auto res = cli.Get("/index");
  16193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16194. ASSERT_EQ(StatusCode::OK_200, res->status);
  16195. }
  16196. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  16197. // another port, so the client follows it with a new client.
  16198. static Result GetThroughTlsRedirectToDifferentPort(
  16199. const std::function<void(SSLClient &)> &setup,
  16200. const char *target_cert = SERVER_CERT2_FILE,
  16201. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  16202. auto ssl_port = PORT + 1;
  16203. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16204. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16205. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16206. "/index");
  16207. });
  16208. SSLServer ssl_svr2(target_cert, target_key);
  16209. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16210. res.set_content("test", "text/plain");
  16211. });
  16212. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  16213. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  16214. auto se = detail::scope_exit([&] {
  16215. ssl_svr2.stop();
  16216. ssl_svr1.stop();
  16217. t2.join();
  16218. t.join();
  16219. });
  16220. ssl_svr1.wait_until_ready();
  16221. ssl_svr2.wait_until_ready();
  16222. SSLClient cli("127.0.0.1", PORT);
  16223. cli.set_follow_location(true);
  16224. cli.set_connection_timeout(30);
  16225. setup(cli);
  16226. return cli.Get("/index");
  16227. }
  16228. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  16229. auto calls = 0;
  16230. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  16231. cli.enable_server_certificate_verification(false);
  16232. // Accept the first server only.
  16233. cli.set_session_verifier([&](tls::session_t) {
  16234. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  16235. : SSLVerifierResponse::CertificateRejected;
  16236. });
  16237. });
  16238. ASSERT_FALSE(res);
  16239. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16240. EXPECT_EQ(2, calls);
  16241. }
  16242. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16243. std::string pinned;
  16244. auto res = GetThroughTlsRedirectToDifferentPort(
  16245. [&](SSLClient &cli) {
  16246. cli.enable_server_certificate_verification(false);
  16247. // Pin the first certificate seen.
  16248. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16249. if (pinned.empty()) { pinned = ctx.serial(); }
  16250. return ctx.serial() == pinned;
  16251. });
  16252. },
  16253. // A certificate other than the first server's.
  16254. SERVER_CERT_FILE);
  16255. EXPECT_FALSE(res);
  16256. EXPECT_FALSE(pinned.empty());
  16257. }
  16258. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16259. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16260. std::string cert;
  16261. read_file(SERVER_CERT2_FILE, cert);
  16262. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16263. });
  16264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16265. EXPECT_EQ(StatusCode::OK_200, res->status);
  16266. }
  16267. // The target's certificate is signed by the root CA, which the first server's
  16268. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16269. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16270. auto res = GetThroughTlsRedirectToDifferentPort(
  16271. [](SSLClient &cli) {
  16272. std::string root_ca, cert;
  16273. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16274. read_file(SERVER_CERT2_FILE, cert);
  16275. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16276. cli.load_ca_cert_store(cert.data(), cert.size());
  16277. cli.enable_server_hostname_verification(false);
  16278. },
  16279. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16281. EXPECT_EQ(StatusCode::OK_200, res->status);
  16282. }
  16283. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16284. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16285. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16286. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16287. auto res = GetThroughTlsRedirectToDifferentPort(
  16288. [](SSLClient &cli) {
  16289. std::string root_ca, cert;
  16290. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16291. read_file(SERVER_CERT2_FILE, cert);
  16292. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16293. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16294. cli.enable_server_hostname_verification(false);
  16295. },
  16296. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16297. ASSERT_FALSE(res);
  16298. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16299. }
  16300. #endif
  16301. #endif
  16302. #ifdef CPPHTTPLIB_SSL_ENABLED
  16303. // Test that set_ca_cert_store() skips system certs (consistent with
  16304. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16305. // should be trusted - system certs should NOT be loaded.
  16306. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16307. // Load a specific cert that is NOT a system CA cert
  16308. std::string cert;
  16309. read_file(SERVER_CERT2_FILE, cert);
  16310. SSLClient cli("google.com");
  16311. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16312. cli.enable_server_certificate_verification(true);
  16313. // This should FAIL because:
  16314. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16315. // 2. System certs should NOT be loaded when custom store is set
  16316. // If system certs WERE loaded, this would succeed
  16317. auto res = cli.Get("/");
  16318. ASSERT_FALSE(res);
  16319. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16320. }
  16321. // Same as above, but through the native store handle path. Regression test:
  16322. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16323. // merged system certs into the user-provided store.
  16324. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16325. std::string cert;
  16326. read_file(SERVER_CERT2_FILE, cert);
  16327. SSLClient cli("google.com");
  16328. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16329. cli.enable_server_certificate_verification(true);
  16330. auto res = cli.Get("/");
  16331. ASSERT_FALSE(res);
  16332. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16333. }
  16334. // A custom store set via the native handle must still verify a server whose
  16335. // cert it does contain.
  16336. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16337. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16338. ASSERT_TRUE(svr.is_valid());
  16339. svr.Get("/test", [&](const Request &, Response &res) {
  16340. res.set_content("test", "text/plain");
  16341. });
  16342. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16343. auto se = detail::scope_exit([&] {
  16344. svr.stop();
  16345. t.join();
  16346. ASSERT_FALSE(svr.is_running());
  16347. });
  16348. svr.wait_until_ready();
  16349. SSLClient cli("127.0.0.1", PORT);
  16350. std::string cert;
  16351. read_file(SERVER_CERT2_FILE, cert);
  16352. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16353. cli.enable_server_certificate_verification(true);
  16354. cli.set_connection_timeout(30);
  16355. auto res = cli.Get("/test");
  16356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16357. ASSERT_EQ(StatusCode::OK_200, res->status);
  16358. }
  16359. // CA certs loaded through the universal Client must be transferred to the
  16360. // client created internally for following an HTTPS redirect. Regression test:
  16361. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16362. // the CA data for redirect transfer.
  16363. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16364. auto ssl_port = PORT + 1;
  16365. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16366. ASSERT_TRUE(ssl_svr1.is_valid());
  16367. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16368. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16369. "/index");
  16370. });
  16371. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16372. ASSERT_TRUE(ssl_svr2.is_valid());
  16373. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16374. res.set_content("test", "text/plain");
  16375. });
  16376. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16377. thread t2 =
  16378. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16379. auto se = detail::scope_exit([&] {
  16380. ssl_svr2.stop();
  16381. ssl_svr1.stop();
  16382. t2.join();
  16383. t.join();
  16384. ASSERT_FALSE(ssl_svr1.is_running());
  16385. });
  16386. ssl_svr1.wait_until_ready();
  16387. ssl_svr2.wait_until_ready();
  16388. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16389. std::string cert;
  16390. read_file(SERVER_CERT2_FILE, cert);
  16391. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16392. cli.enable_server_certificate_verification(true);
  16393. cli.set_follow_location(true);
  16394. cli.set_connection_timeout(30);
  16395. auto res = cli.Get("/index");
  16396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16397. ASSERT_EQ(StatusCode::OK_200, res->status);
  16398. }
  16399. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16400. // so a host signed by a system CA verifies even though a custom CA is set
  16401. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16402. std::string cert;
  16403. read_file(SERVER_CERT2_FILE, cert);
  16404. SSLClient cli("google.com");
  16405. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16406. cli.enable_system_ca(true);
  16407. cli.enable_server_certificate_verification(true);
  16408. auto res = cli.Get("/");
  16409. // Any status: Google may redirect or rate-limit CI runners.
  16410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16411. }
  16412. // The custom CA remains effective when combined with the system CA
  16413. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16414. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16415. ASSERT_TRUE(svr.is_valid());
  16416. svr.Get("/test", [&](const Request &, Response &res) {
  16417. res.set_content("test", "text/plain");
  16418. });
  16419. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16420. auto se = detail::scope_exit([&] {
  16421. svr.stop();
  16422. t.join();
  16423. ASSERT_FALSE(svr.is_running());
  16424. });
  16425. svr.wait_until_ready();
  16426. SSLClient cli("127.0.0.1", PORT);
  16427. std::string cert;
  16428. read_file(SERVER_CERT2_FILE, cert);
  16429. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16430. cli.enable_system_ca(true);
  16431. cli.enable_server_certificate_verification(true);
  16432. cli.set_connection_timeout(30);
  16433. auto res = cli.Get("/test");
  16434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16435. ASSERT_EQ(StatusCode::OK_200, res->status);
  16436. }
  16437. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16438. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16439. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16440. static CFDictionaryRef
  16441. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16442. const SecTrustSettingsResult *result) {
  16443. auto constraint =
  16444. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16445. &kCFTypeDictionaryValueCallBacks);
  16446. if (policy) {
  16447. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16448. }
  16449. if (policy_string) {
  16450. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16451. kCFStringEncodingUTF8);
  16452. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16453. CFRelease(str);
  16454. }
  16455. if (result) {
  16456. auto number_value = static_cast<SInt32>(*result);
  16457. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16458. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16459. CFRelease(number);
  16460. }
  16461. return constraint;
  16462. }
  16463. static SecTrustSettingsResult
  16464. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16465. auto trust_settings =
  16466. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16467. for (auto constraint : constraints) {
  16468. CFArrayAppendValue(trust_settings, constraint);
  16469. CFRelease(constraint);
  16470. }
  16471. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16472. CFRelease(trust_settings);
  16473. return result;
  16474. }
  16475. // The system CA loader takes a Keychain certificate as a trusted root only
  16476. // when its Trust Settings say so for SSL, not merely because it has some.
  16477. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16478. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16479. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16480. const auto deny = kSecTrustSettingsResultDeny;
  16481. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16482. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16483. auto x509_policy = SecPolicyCreateBasicX509();
  16484. // "Always Trust", which stores no constraint at all
  16485. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16486. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16487. ssl_trust_settings_result(
  16488. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16489. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16490. ssl_trust_settings_result(
  16491. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16492. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16493. ssl_trust_settings_result(
  16494. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16495. // "Never Trust", for everything or for SSL
  16496. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16497. ssl_trust_settings_result(
  16498. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16499. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16500. ssl_trust_settings_result(
  16501. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16502. // Trusted for another policy, for one host, or not at all
  16503. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16504. ssl_trust_settings_result(
  16505. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16506. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16507. ssl_trust_settings_result({make_usage_constraint(
  16508. ssl_policy, "www.example.com", &trust_root)}));
  16509. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16510. ssl_trust_settings_result(
  16511. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16512. // The first constraint that applies to SSL decides
  16513. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16514. ssl_trust_settings_result(
  16515. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16516. make_usage_constraint(nullptr, nullptr, &deny)}));
  16517. CFRelease(x509_policy);
  16518. CFRelease(ssl_policy);
  16519. }
  16520. #endif
  16521. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16522. // skip chain verification entirely (only the certificate identity was
  16523. // checked), so a server presenting an untrusted certificate with a matching
  16524. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16525. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16526. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16527. ASSERT_TRUE(svr.is_valid());
  16528. svr.Get("/test", [&](const Request &, Response &res) {
  16529. res.set_content("test", "text/plain");
  16530. });
  16531. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16532. auto se = detail::scope_exit([&] {
  16533. svr.stop();
  16534. t.join();
  16535. ASSERT_FALSE(svr.is_running());
  16536. });
  16537. svr.wait_until_ready();
  16538. SSLClient cli("127.0.0.1", PORT);
  16539. std::string cert;
  16540. // A trusted CA that did not sign the server certificate. The server cert
  16541. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16542. // this connection.
  16543. read_file(CLIENT_CA_CERT_FILE, cert);
  16544. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16545. cli.enable_server_certificate_verification(true);
  16546. cli.set_connection_timeout(30);
  16547. auto res = cli.Get("/test");
  16548. ASSERT_FALSE(res);
  16549. }
  16550. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16551. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16552. // CA that failed to come through fails verification instead of trusting them.
  16553. // (wolfSSL does not list the system CAs it loaded.)
  16554. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16555. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16556. ASSERT_TRUE(svr.is_valid());
  16557. auto port = svr.bind_to_any_port("127.0.0.1");
  16558. ASSERT_LT(0, port);
  16559. thread t = thread([&] { svr.listen_after_bind(); });
  16560. auto se = detail::scope_exit([&] {
  16561. svr.stop();
  16562. t.join();
  16563. ASSERT_FALSE(svr.is_running());
  16564. });
  16565. svr.wait_until_ready();
  16566. // The CAs a client trusts once its first request has loaded them
  16567. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16568. Client cli("https://127.0.0.1:" + std::to_string(port));
  16569. setup(cli);
  16570. cli.Get("/");
  16571. return tls::get_ca_names(cli.tls_context()).size();
  16572. };
  16573. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16574. EXPECT_EQ(0u,
  16575. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16576. }
  16577. #endif
  16578. // A TLS setting changed between requests applies to the next one, not just to
  16579. // the next connection
  16580. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16581. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16582. ASSERT_TRUE(svr.is_valid());
  16583. svr.Get("/", [](const Request &req, Response &res) {
  16584. res.set_content(std::to_string(req.remote_port), "text/plain");
  16585. });
  16586. auto port = svr.bind_to_any_port("127.0.0.1");
  16587. ASSERT_LT(0, port);
  16588. thread t = thread([&] { svr.listen_after_bind(); });
  16589. auto se = detail::scope_exit([&] {
  16590. svr.stop();
  16591. t.join();
  16592. ASSERT_FALSE(svr.is_running());
  16593. });
  16594. svr.wait_until_ready();
  16595. SSLClient cli("127.0.0.1", port);
  16596. cli.set_keep_alive(true);
  16597. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16598. cli.enable_server_certificate_verification(false);
  16599. // The port the request went out from, so a new one means a new connection
  16600. auto client_port = [&] {
  16601. auto res = cli.Get("/");
  16602. return res ? res->body : std::string();
  16603. };
  16604. auto last = client_port();
  16605. ASSERT_FALSE(last.empty());
  16606. // Setting a value it already has keeps the connection
  16607. cli.enable_server_certificate_verification(false);
  16608. cli.enable_server_hostname_verification(true);
  16609. EXPECT_EQ(last, client_port());
  16610. cli.enable_server_certificate_verification(true);
  16611. auto res = cli.Get("/");
  16612. EXPECT_FALSE(res);
  16613. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16614. std::string ca;
  16615. read_file(SERVER_CERT2_FILE, ca);
  16616. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16617. last = client_port();
  16618. ASSERT_FALSE(last.empty());
  16619. std::vector<std::function<void()>> setters = {
  16620. [&] { cli.enable_server_hostname_verification(false); },
  16621. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16622. [&] {
  16623. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16624. },
  16625. [&] {
  16626. cli.set_server_certificate_verifier(
  16627. [](const tls::VerifyContext &) { return true; });
  16628. },
  16629. [&] {
  16630. cli.set_session_verifier(
  16631. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16632. },
  16633. };
  16634. for (const auto &setter : setters) {
  16635. setter();
  16636. auto next = client_port();
  16637. ASSERT_FALSE(next.empty());
  16638. EXPECT_NE(last, next);
  16639. last = next;
  16640. }
  16641. cli.set_session_verifier(
  16642. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16643. auto handle = cli.open_stream("GET", "/");
  16644. EXPECT_FALSE(handle.is_valid());
  16645. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16646. }
  16647. // A PEM given to create_ca_store() needs no NUL after it
  16648. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16649. std::string pem;
  16650. read_file(SERVER_CERT2_FILE, pem);
  16651. auto buf = pem + "X";
  16652. auto store = tls::create_ca_store(buf.data(), pem.size());
  16653. EXPECT_TRUE(store != nullptr);
  16654. SSLClient cli("localhost");
  16655. cli.set_ca_cert_store(store);
  16656. }
  16657. // enable_system_ca(false) prevents system CA loading entirely
  16658. TEST(SSLClientTest, DisableSystemCa_Online) {
  16659. SSLClient cli("google.com");
  16660. cli.enable_system_ca(false);
  16661. cli.enable_server_certificate_verification(true);
  16662. auto res = cli.Get("/");
  16663. ASSERT_FALSE(res);
  16664. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16665. // itself when the CA chain is empty
  16666. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16667. res.error() == Error::SSLConnection);
  16668. }
  16669. // The universal Client forwards enable_system_ca()
  16670. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16671. std::string cert;
  16672. read_file(SERVER_CERT2_FILE, cert);
  16673. Client cli("https://google.com");
  16674. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16675. cli.enable_system_ca(true);
  16676. cli.enable_server_certificate_verification(true);
  16677. auto res = cli.Get("/");
  16678. // Any status: Google may redirect or rate-limit CI runners.
  16679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16680. }
  16681. // The system CA policy must carry over to the client created internally for
  16682. // following a cross-host HTTPS redirect
  16683. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16684. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16685. ASSERT_TRUE(svr.is_valid());
  16686. svr.Get("/index", [&](const Request &, Response &res) {
  16687. res.set_redirect("https://www.google.com/");
  16688. });
  16689. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16690. auto se = detail::scope_exit([&] {
  16691. svr.stop();
  16692. t.join();
  16693. ASSERT_FALSE(svr.is_running());
  16694. });
  16695. svr.wait_until_ready();
  16696. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16697. std::string cert;
  16698. read_file(SERVER_CERT2_FILE, cert);
  16699. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16700. cli.enable_system_ca(true);
  16701. cli.enable_server_certificate_verification(true);
  16702. cli.set_follow_location(true);
  16703. cli.set_connection_timeout(30);
  16704. // Receiving any response proves the redirect client completed the TLS
  16705. // handshake with a system-CA-signed host
  16706. auto res = cli.Get("/index");
  16707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16708. }
  16709. TEST(MultipartFormDataTest, LargeData) {
  16710. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16711. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16712. const ContentReader &content_reader) {
  16713. if (req.is_multipart_form_data()) {
  16714. std::vector<FormData> items;
  16715. content_reader(
  16716. [&](const FormData &file) {
  16717. items.push_back(file);
  16718. return true;
  16719. },
  16720. [&](const char *data, size_t data_length) {
  16721. items.back().content.append(data, data_length);
  16722. return true;
  16723. });
  16724. EXPECT_TRUE(std::string(items[0].name) == "document");
  16725. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16726. EXPECT_TRUE(items[0].filename == "2MB_data");
  16727. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16728. EXPECT_TRUE(items[1].name == "hello");
  16729. EXPECT_TRUE(items[1].content == "world");
  16730. EXPECT_TRUE(items[1].filename == "");
  16731. EXPECT_TRUE(items[1].content_type == "");
  16732. } else {
  16733. std::string body;
  16734. content_reader([&](const char *data, size_t data_length) {
  16735. body.append(data, data_length);
  16736. return true;
  16737. });
  16738. }
  16739. });
  16740. auto port = svr.bind_to_any_port(HOST);
  16741. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16742. auto se = detail::scope_exit([&] {
  16743. svr.stop();
  16744. t.join();
  16745. ASSERT_FALSE(svr.is_running());
  16746. });
  16747. svr.wait_until_ready();
  16748. {
  16749. std::string data(1024 * 1024 * 2, '.');
  16750. std::stringstream buffer;
  16751. buffer << data;
  16752. SSLClient cli(HOST, port);
  16753. cli.enable_server_certificate_verification(false);
  16754. UploadFormDataItems items{
  16755. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16756. {"hello", "world", "", ""},
  16757. };
  16758. auto res = cli.Post("/post", items);
  16759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16760. ASSERT_EQ(StatusCode::OK_200, res->status);
  16761. }
  16762. }
  16763. TEST(MultipartFormDataTest, DataProviderItems) {
  16764. std::random_device seed_gen;
  16765. std::mt19937 random(seed_gen());
  16766. std::string rand1;
  16767. rand1.resize(1000);
  16768. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16769. std::string rand2;
  16770. rand2.resize(3000);
  16771. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16772. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16773. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16774. const ContentReader &content_reader) {
  16775. ASSERT_FALSE(req.is_multipart_form_data());
  16776. std::string body;
  16777. content_reader([&](const char *data, size_t data_length) {
  16778. body.append(data, data_length);
  16779. return true;
  16780. });
  16781. EXPECT_EQ(body, "");
  16782. });
  16783. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16784. const ContentReader &content_reader) {
  16785. ASSERT_TRUE(req.is_multipart_form_data());
  16786. std::vector<FormData> items;
  16787. content_reader(
  16788. [&](const FormData &file) {
  16789. items.push_back(file);
  16790. return true;
  16791. },
  16792. [&](const char *data, size_t data_length) {
  16793. items.back().content.append(data, data_length);
  16794. return true;
  16795. });
  16796. ASSERT_TRUE(items.size() == 2);
  16797. EXPECT_EQ(std::string(items[0].name), "name1");
  16798. EXPECT_EQ(items[0].content, "Testing123");
  16799. EXPECT_EQ(items[0].filename, "filename1");
  16800. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16801. EXPECT_EQ(items[1].name, "name2");
  16802. EXPECT_EQ(items[1].content, "Testing456");
  16803. EXPECT_EQ(items[1].filename, "");
  16804. EXPECT_EQ(items[1].content_type, "");
  16805. });
  16806. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16807. const ContentReader &content_reader) {
  16808. ASSERT_TRUE(req.is_multipart_form_data());
  16809. std::vector<FormData> items;
  16810. content_reader(
  16811. [&](const FormData &file) {
  16812. items.push_back(file);
  16813. return true;
  16814. },
  16815. [&](const char *data, size_t data_length) {
  16816. items.back().content.append(data, data_length);
  16817. return true;
  16818. });
  16819. ASSERT_TRUE(items.size() == 2);
  16820. EXPECT_EQ(items[0].name, "name3");
  16821. EXPECT_EQ(items[0].content, rand1);
  16822. EXPECT_EQ(items[0].filename, "filename3");
  16823. EXPECT_EQ(items[0].content_type, "");
  16824. EXPECT_EQ(items[1].name, "name4");
  16825. EXPECT_EQ(items[1].content, rand2);
  16826. EXPECT_EQ(items[1].filename, "filename4");
  16827. EXPECT_EQ(items[1].content_type, "");
  16828. });
  16829. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16830. const ContentReader &content_reader) {
  16831. ASSERT_TRUE(req.is_multipart_form_data());
  16832. std::vector<FormData> items;
  16833. content_reader(
  16834. [&](const FormData &file) {
  16835. items.push_back(file);
  16836. return true;
  16837. },
  16838. [&](const char *data, size_t data_length) {
  16839. items.back().content.append(data, data_length);
  16840. return true;
  16841. });
  16842. ASSERT_TRUE(items.size() == 4);
  16843. EXPECT_EQ(std::string(items[0].name), "name1");
  16844. EXPECT_EQ(items[0].content, "Testing123");
  16845. EXPECT_EQ(items[0].filename, "filename1");
  16846. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16847. EXPECT_EQ(items[1].name, "name2");
  16848. EXPECT_EQ(items[1].content, "Testing456");
  16849. EXPECT_EQ(items[1].filename, "");
  16850. EXPECT_EQ(items[1].content_type, "");
  16851. EXPECT_EQ(items[2].name, "name3");
  16852. EXPECT_EQ(items[2].content, rand1);
  16853. EXPECT_EQ(items[2].filename, "filename3");
  16854. EXPECT_EQ(items[2].content_type, "");
  16855. EXPECT_EQ(items[3].name, "name4");
  16856. EXPECT_EQ(items[3].content, rand2);
  16857. EXPECT_EQ(items[3].filename, "filename4");
  16858. EXPECT_EQ(items[3].content_type, "");
  16859. });
  16860. auto port = svr.bind_to_any_port("localhost");
  16861. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16862. auto se = detail::scope_exit([&] {
  16863. svr.stop();
  16864. t.join();
  16865. ASSERT_FALSE(svr.is_running());
  16866. });
  16867. svr.wait_until_ready();
  16868. {
  16869. SSLClient cli("localhost", port);
  16870. cli.enable_server_certificate_verification(false);
  16871. UploadFormDataItems items{
  16872. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16873. {"name2", "Testing456", "", ""}, // not a file
  16874. };
  16875. {
  16876. auto res = cli.Post("/post-none", {}, {}, {});
  16877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16878. ASSERT_EQ(StatusCode::OK_200, res->status);
  16879. }
  16880. FormDataProviderItems providers;
  16881. {
  16882. auto res =
  16883. cli.Post("/post-items", {}, items, providers); // empty providers
  16884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16885. ASSERT_EQ(StatusCode::OK_200, res->status);
  16886. }
  16887. providers.push_back({"name3",
  16888. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16889. // test the offset is given correctly at each step
  16890. if (!offset)
  16891. sink.os.write(rand1.data(), 30);
  16892. else if (offset == 30)
  16893. sink.os.write(rand1.data() + 30, 300);
  16894. else if (offset == 330)
  16895. sink.os.write(rand1.data() + 330, 670);
  16896. else if (offset == rand1.size())
  16897. sink.done();
  16898. return true;
  16899. },
  16900. "filename3",
  16901. {}});
  16902. providers.push_back({"name4",
  16903. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16904. // test the offset is given correctly at each step
  16905. if (!offset)
  16906. sink.os.write(rand2.data(), 2000);
  16907. else if (offset == 2000)
  16908. sink.os.write(rand2.data() + 2000, 1);
  16909. else if (offset == 2001)
  16910. sink.os.write(rand2.data() + 2001, 999);
  16911. else if (offset == rand2.size())
  16912. sink.done();
  16913. return true;
  16914. },
  16915. "filename4",
  16916. {}});
  16917. {
  16918. auto res = cli.Post("/post-providers", {}, {}, providers);
  16919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16920. ASSERT_EQ(StatusCode::OK_200, res->status);
  16921. }
  16922. {
  16923. auto res = cli.Post("/post-both", {}, items, providers);
  16924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16925. ASSERT_EQ(StatusCode::OK_200, res->status);
  16926. }
  16927. }
  16928. }
  16929. TEST(MultipartFormDataTest, BadHeader) {
  16930. Server svr;
  16931. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16932. res.set_content("ok", "text/plain");
  16933. });
  16934. thread t = thread([&] { svr.listen(HOST, PORT); });
  16935. auto se = detail::scope_exit([&] {
  16936. svr.stop();
  16937. t.join();
  16938. ASSERT_FALSE(svr.is_running());
  16939. });
  16940. svr.wait_until_ready();
  16941. const std::string body =
  16942. "This is the preamble. It is to be ignored, though it\r\n"
  16943. "is a handy place for composition agents to include an\r\n"
  16944. "explanatory note to non-MIME conformant readers.\r\n"
  16945. "\r\n"
  16946. "\r\n"
  16947. "--simple boundary\r\n"
  16948. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16949. ": BAD...\r\n"
  16950. "\r\n"
  16951. "value1\r\n"
  16952. "--simple boundary\r\n"
  16953. "Content-Disposition: form-data; name=\"field2\"; "
  16954. "filename=\"example.txt\"\r\n"
  16955. "\r\n"
  16956. "value2\r\n"
  16957. "--simple boundary--\r\n"
  16958. "This is the epilogue. It is also to be ignored.\r\n";
  16959. std::string content_type =
  16960. R"(multipart/form-data; boundary="simple boundary")";
  16961. Client cli(HOST, PORT);
  16962. auto res = cli.Post("/post", body, content_type.c_str());
  16963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16964. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16965. }
  16966. TEST(MultipartFormDataTest, WithPreamble) {
  16967. Server svr;
  16968. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16969. res.set_content("ok", "text/plain");
  16970. });
  16971. thread t = thread([&] { svr.listen(HOST, PORT); });
  16972. auto se = detail::scope_exit([&] {
  16973. svr.stop();
  16974. t.join();
  16975. ASSERT_FALSE(svr.is_running());
  16976. });
  16977. svr.wait_until_ready();
  16978. const std::string body =
  16979. "This is the preamble. It is to be ignored, though it\r\n"
  16980. "is a handy place for composition agents to include an\r\n"
  16981. "explanatory note to non-MIME conformant readers.\r\n"
  16982. "\r\n"
  16983. "\r\n"
  16984. "--simple boundary\r\n"
  16985. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16986. "\r\n"
  16987. "value1\r\n"
  16988. "--simple boundary\r\n"
  16989. "Content-Disposition: form-data; name=\"field2\"; "
  16990. "filename=\"example.txt\"\r\n"
  16991. "\r\n"
  16992. "value2\r\n"
  16993. "--simple boundary--\r\n"
  16994. "This is the epilogue. It is also to be ignored.\r\n";
  16995. std::string content_type =
  16996. R"(multipart/form-data; boundary="simple boundary")";
  16997. Client cli(HOST, PORT);
  16998. auto res = cli.Post("/post", body, content_type.c_str());
  16999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17000. EXPECT_EQ(StatusCode::OK_200, res->status);
  17001. }
  17002. TEST(MultipartFormDataTest, PostCustomBoundary) {
  17003. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17004. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  17005. const ContentReader &content_reader) {
  17006. if (req.is_multipart_form_data()) {
  17007. std::vector<FormData> items;
  17008. content_reader(
  17009. [&](const FormData &file) {
  17010. items.push_back(file);
  17011. return true;
  17012. },
  17013. [&](const char *data, size_t data_length) {
  17014. items.back().content.append(data, data_length);
  17015. return true;
  17016. });
  17017. EXPECT_TRUE(std::string(items[0].name) == "document");
  17018. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17019. EXPECT_TRUE(items[0].filename == "2MB_data");
  17020. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17021. EXPECT_TRUE(items[1].name == "hello");
  17022. EXPECT_TRUE(items[1].content == "world");
  17023. EXPECT_TRUE(items[1].filename == "");
  17024. EXPECT_TRUE(items[1].content_type == "");
  17025. } else {
  17026. std::string body;
  17027. content_reader([&](const char *data, size_t data_length) {
  17028. body.append(data, data_length);
  17029. return true;
  17030. });
  17031. }
  17032. });
  17033. auto port = svr.bind_to_any_port("localhost");
  17034. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17035. auto se = detail::scope_exit([&] {
  17036. svr.stop();
  17037. t.join();
  17038. ASSERT_FALSE(svr.is_running());
  17039. });
  17040. svr.wait_until_ready();
  17041. {
  17042. std::string data(1024 * 1024 * 2, '.');
  17043. std::stringstream buffer;
  17044. buffer << data;
  17045. SSLClient cli("localhost", port);
  17046. cli.enable_server_certificate_verification(false);
  17047. UploadFormDataItems items{
  17048. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17049. {"hello", "world", "", ""},
  17050. };
  17051. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  17052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17053. ASSERT_EQ(StatusCode::OK_200, res->status);
  17054. }
  17055. }
  17056. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  17057. std::string data(1024 * 1024 * 2, '&');
  17058. std::stringstream buffer;
  17059. buffer << data;
  17060. Client cli("https://localhost:8080");
  17061. UploadFormDataItems items{
  17062. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17063. {"hello", "world", "", ""},
  17064. };
  17065. for (const char &c : " \t\r\n") {
  17066. auto res =
  17067. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  17068. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17069. ASSERT_FALSE(res);
  17070. }
  17071. }
  17072. TEST(MultipartFormDataTest, PutFormData) {
  17073. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17074. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  17075. const ContentReader &content_reader) {
  17076. if (req.is_multipart_form_data()) {
  17077. std::vector<FormData> items;
  17078. content_reader(
  17079. [&](const FormData &file) {
  17080. items.push_back(file);
  17081. return true;
  17082. },
  17083. [&](const char *data, size_t data_length) {
  17084. items.back().content.append(data, data_length);
  17085. return true;
  17086. });
  17087. EXPECT_TRUE(std::string(items[0].name) == "document");
  17088. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17089. EXPECT_TRUE(items[0].filename == "2MB_data");
  17090. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17091. EXPECT_TRUE(items[1].name == "hello");
  17092. EXPECT_TRUE(items[1].content == "world");
  17093. EXPECT_TRUE(items[1].filename == "");
  17094. EXPECT_TRUE(items[1].content_type == "");
  17095. } else {
  17096. std::string body;
  17097. content_reader([&](const char *data, size_t data_length) {
  17098. body.append(data, data_length);
  17099. return true;
  17100. });
  17101. }
  17102. });
  17103. auto port = svr.bind_to_any_port("localhost");
  17104. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17105. auto se = detail::scope_exit([&] {
  17106. svr.stop();
  17107. t.join();
  17108. ASSERT_FALSE(svr.is_running());
  17109. });
  17110. svr.wait_until_ready();
  17111. {
  17112. std::string data(1024 * 1024 * 2, '&');
  17113. std::stringstream buffer;
  17114. buffer << data;
  17115. SSLClient cli("localhost", port);
  17116. cli.enable_server_certificate_verification(false);
  17117. UploadFormDataItems items{
  17118. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17119. {"hello", "world", "", ""},
  17120. };
  17121. auto res = cli.Put("/put", items);
  17122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17123. ASSERT_EQ(StatusCode::OK_200, res->status);
  17124. }
  17125. }
  17126. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  17127. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17128. svr.Put("/put_customboundary",
  17129. [&](const Request &req, const Response & /*res*/,
  17130. const ContentReader &content_reader) {
  17131. if (req.is_multipart_form_data()) {
  17132. std::vector<FormData> items;
  17133. content_reader(
  17134. [&](const FormData &file) {
  17135. items.push_back(file);
  17136. return true;
  17137. },
  17138. [&](const char *data, size_t data_length) {
  17139. items.back().content.append(data, data_length);
  17140. return true;
  17141. });
  17142. EXPECT_TRUE(std::string(items[0].name) == "document");
  17143. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17144. EXPECT_TRUE(items[0].filename == "2MB_data");
  17145. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17146. EXPECT_TRUE(items[1].name == "hello");
  17147. EXPECT_TRUE(items[1].content == "world");
  17148. EXPECT_TRUE(items[1].filename == "");
  17149. EXPECT_TRUE(items[1].content_type == "");
  17150. } else {
  17151. std::string body;
  17152. content_reader([&](const char *data, size_t data_length) {
  17153. body.append(data, data_length);
  17154. return true;
  17155. });
  17156. }
  17157. });
  17158. auto port = svr.bind_to_any_port("localhost");
  17159. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17160. auto se = detail::scope_exit([&] {
  17161. svr.stop();
  17162. t.join();
  17163. ASSERT_FALSE(svr.is_running());
  17164. });
  17165. svr.wait_until_ready();
  17166. {
  17167. std::string data(1024 * 1024 * 2, '&');
  17168. std::stringstream buffer;
  17169. buffer << data;
  17170. SSLClient cli("localhost", port);
  17171. cli.enable_server_certificate_verification(false);
  17172. UploadFormDataItems items{
  17173. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17174. {"hello", "world", "", ""},
  17175. };
  17176. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  17177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17178. ASSERT_EQ(StatusCode::OK_200, res->status);
  17179. }
  17180. }
  17181. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  17182. std::string data(1024 * 1024 * 2, '&');
  17183. std::stringstream buffer;
  17184. buffer << data;
  17185. Client cli("https://localhost:8080");
  17186. cli.enable_server_certificate_verification(false);
  17187. UploadFormDataItems items{
  17188. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17189. {"hello", "world", "", ""},
  17190. };
  17191. for (const char &c : " \t\r\n") {
  17192. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  17193. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17194. ASSERT_FALSE(res);
  17195. }
  17196. }
  17197. TEST(MultipartFormDataTest, AlternateFilename) {
  17198. auto handled = false;
  17199. Server svr;
  17200. svr.Post("/test", [&](const Request &req, Response &res) {
  17201. ASSERT_EQ(2u, req.form.files.size());
  17202. ASSERT_EQ(1u, req.form.fields.size());
  17203. // Test files
  17204. const auto &file1 = req.form.get_file("file1");
  17205. ASSERT_EQ("file1", file1.name);
  17206. ASSERT_EQ("A.txt", file1.filename);
  17207. ASSERT_EQ("text/plain", file1.content_type);
  17208. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  17209. const auto &file2 = req.form.get_file("file2");
  17210. ASSERT_EQ("file2", file2.name);
  17211. ASSERT_EQ("a.html", file2.filename);
  17212. ASSERT_EQ("text/html", file2.content_type);
  17213. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  17214. file2.content);
  17215. // Test text field
  17216. const auto &text = req.form.get_field("text");
  17217. ASSERT_EQ("text default", text);
  17218. res.set_content("ok", "text/plain");
  17219. handled = true;
  17220. });
  17221. thread t = thread([&] { svr.listen(HOST, PORT); });
  17222. auto se = detail::scope_exit([&] {
  17223. svr.stop();
  17224. t.join();
  17225. ASSERT_FALSE(svr.is_running());
  17226. ASSERT_TRUE(handled);
  17227. });
  17228. svr.wait_until_ready();
  17229. auto req = "POST /test HTTP/1.1\r\n"
  17230. "Host: localhost\r\n"
  17231. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17232. "Content-Length: 399\r\n"
  17233. "\r\n"
  17234. "----------\r\n"
  17235. "Content-Disposition: form-data; name=\"text\"\r\n"
  17236. "\r\n"
  17237. "text default\r\n"
  17238. "----------\r\n"
  17239. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  17240. "filename=\"a.txt\"; name=\"file1\"\r\n"
  17241. "Content-Type: text/plain\r\n"
  17242. "\r\n"
  17243. "Content of a.txt.\r\n"
  17244. "\r\n"
  17245. "----------\r\n"
  17246. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17247. "\"a.html\"\r\n"
  17248. "Content-Type: text/html\r\n"
  17249. "\r\n"
  17250. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17251. "\r\n"
  17252. "------------\r\n";
  17253. ASSERT_TRUE(send_request(1, req));
  17254. }
  17255. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17256. auto handled = false;
  17257. Server svr;
  17258. svr.Post("/test", [&](const Request &req, Response &res) {
  17259. // Case-insensitive "utf-8''" prefix with a long value
  17260. const auto &file = req.form.get_file("file1");
  17261. ASSERT_EQ("file1", file.name);
  17262. // 8000 chars exercises both the Content-Disposition parser and the
  17263. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17264. // Prior to the fix, std::regex_match on this header would cause O(N)
  17265. // stack recursion in libstdc++, leading to SIGSEGV.
  17266. std::string expected_filename(8000, 'A');
  17267. ASSERT_EQ(expected_filename, file.filename);
  17268. res.set_content("ok", "text/plain");
  17269. handled = true;
  17270. });
  17271. thread t = thread([&] { svr.listen(HOST, PORT); });
  17272. auto se = detail::scope_exit([&] {
  17273. svr.stop();
  17274. t.join();
  17275. ASSERT_FALSE(svr.is_running());
  17276. ASSERT_TRUE(handled);
  17277. });
  17278. svr.wait_until_ready();
  17279. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17280. // Regression test for GHSA-qq6v-r583-3h69
  17281. std::string long_filename(8000, 'A');
  17282. std::string body = "----------\r\n"
  17283. "Content-Disposition: form-data; name=\"file1\"; "
  17284. "filename*=\"Utf-8''" +
  17285. long_filename +
  17286. "\"\r\n"
  17287. "\r\n"
  17288. "hello\r\n"
  17289. "------------\r\n";
  17290. auto req = "POST /test HTTP/1.1\r\n"
  17291. "Host: localhost\r\n"
  17292. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17293. "Content-Length: " +
  17294. std::to_string(body.size()) + "\r\n\r\n" + body;
  17295. ASSERT_TRUE(send_request(1, req));
  17296. }
  17297. TEST(MultipartFormDataTest, AlternateFilenameWithLanguageTag) {
  17298. auto handled = false;
  17299. Server svr;
  17300. svr.Post("/test", [&](const Request &req, Response &res) {
  17301. ASSERT_EQ("A.txt", req.form.get_file("file1").filename);
  17302. ASSERT_EQ("na\xC3\xAFve.txt", req.form.get_file("file2").filename);
  17303. res.set_content("ok", "text/plain");
  17304. handled = true;
  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. ASSERT_TRUE(handled);
  17312. });
  17313. svr.wait_until_ready();
  17314. std::string body = "----------\r\n"
  17315. "Content-Disposition: form-data; name=\"file1\"; "
  17316. "filename*=UTF-8'en'%41.txt\r\n"
  17317. "\r\n"
  17318. "hello\r\n"
  17319. "----------\r\n"
  17320. "Content-Disposition: form-data; name=\"file2\"; "
  17321. "filename*=utf-8'fr-CA'na%C3%AFve.txt\r\n"
  17322. "\r\n"
  17323. "bonjour\r\n"
  17324. "------------\r\n";
  17325. auto req = "POST /test HTTP/1.1\r\n"
  17326. "Host: localhost\r\n"
  17327. "Connection: close\r\n"
  17328. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17329. "Content-Length: " +
  17330. std::to_string(body.size()) + "\r\n\r\n" + body;
  17331. ASSERT_TRUE(send_request(1, req));
  17332. }
  17333. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17334. auto handled = false;
  17335. Server svr;
  17336. svr.Post("/test", [&](const Request &req, Response &) {
  17337. ASSERT_EQ(2u, req.form.fields.size());
  17338. const auto &text1 = req.form.get_field("text1");
  17339. ASSERT_EQ("text1", text1);
  17340. const auto &text2 = req.form.get_field("text2");
  17341. ASSERT_EQ("text2", text2);
  17342. handled = true;
  17343. });
  17344. thread t = thread([&] { svr.listen(HOST, PORT); });
  17345. auto se = detail::scope_exit([&] {
  17346. svr.stop();
  17347. t.join();
  17348. ASSERT_FALSE(svr.is_running());
  17349. ASSERT_TRUE(handled);
  17350. });
  17351. svr.wait_until_ready();
  17352. auto req = "POST /test HTTP/1.1\r\n"
  17353. "Host: localhost\r\n"
  17354. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17355. "Content-Length: 146\r\n"
  17356. "\r\n----------\r\n"
  17357. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17358. "\r\n"
  17359. "text1"
  17360. "\r\n----------\r\n"
  17361. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17362. "\r\n"
  17363. "text2"
  17364. "\r\n------------";
  17365. std::string response;
  17366. ASSERT_TRUE(send_request(1, req, &response));
  17367. ASSERT_EQ("200", response.substr(9, 3));
  17368. }
  17369. TEST(MultipartFormDataTest, ContentLength) {
  17370. auto handled = false;
  17371. Server svr;
  17372. svr.Post("/test", [&](const Request &req, Response &) {
  17373. ASSERT_EQ(2u, req.form.fields.size());
  17374. const auto &text1 = req.form.get_field("text1");
  17375. ASSERT_EQ("text1", text1);
  17376. const auto &text2 = req.form.get_field("text2");
  17377. ASSERT_EQ("text2", text2);
  17378. handled = true;
  17379. });
  17380. thread t = thread([&] { svr.listen(HOST, PORT); });
  17381. auto se = detail::scope_exit([&] {
  17382. svr.stop();
  17383. t.join();
  17384. ASSERT_FALSE(svr.is_running());
  17385. ASSERT_TRUE(handled);
  17386. });
  17387. svr.wait_until_ready();
  17388. auto req = "POST /test HTTP/1.1\r\n"
  17389. "Host: localhost\r\n"
  17390. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17391. "Content-Length: 167\r\n"
  17392. "\r\n----------\r\n"
  17393. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17394. "Content-Length: 5\r\n"
  17395. "\r\n"
  17396. "text1"
  17397. "\r\n----------\r\n"
  17398. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17399. "\r\n"
  17400. "text2"
  17401. "\r\n------------\r\n";
  17402. std::string response;
  17403. ASSERT_TRUE(send_request(1, req, &response));
  17404. ASSERT_EQ("200", response.substr(9, 3));
  17405. }
  17406. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17407. auto handled = false;
  17408. Server svr;
  17409. svr.Post("/test", [&](const Request &req, Response &) {
  17410. ASSERT_EQ(2u, req.form.fields.size());
  17411. const auto &text1 = req.form.get_field("text1");
  17412. ASSERT_EQ("text1", text1);
  17413. // TODO: Add header access for text fields if needed
  17414. const auto &text2 = req.form.get_field("text2");
  17415. ASSERT_EQ("text2", text2);
  17416. // TODO: Header access for text fields needs to be implemented
  17417. // auto &headers = it->second.headers;
  17418. // ASSERT_EQ(3U, headers.size());
  17419. // auto custom_header = headers.find("x-whatever");
  17420. // ASSERT_TRUE(custom_header != headers.end());
  17421. // ASSERT_NE("customvalue", custom_header->second);
  17422. // ASSERT_EQ("CustomValue", custom_header->second);
  17423. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17424. handled = true;
  17425. });
  17426. thread t = thread([&] { svr.listen(HOST, PORT); });
  17427. auto se = detail::scope_exit([&] {
  17428. svr.stop();
  17429. t.join();
  17430. ASSERT_FALSE(svr.is_running());
  17431. ASSERT_TRUE(handled);
  17432. });
  17433. svr.wait_until_ready();
  17434. auto req = "POST /test HTTP/1.1\r\n"
  17435. "Host: localhost\r\n"
  17436. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17437. "Content-Length: 232\r\n"
  17438. "\r\n----------\r\n"
  17439. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17440. "Content-Length: 5\r\n"
  17441. "X-Test: 1\r\n"
  17442. "\r\n"
  17443. "text1"
  17444. "\r\n----------\r\n"
  17445. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17446. "Content-Type: text/plain\r\n"
  17447. "X-Whatever: CustomValue\r\n"
  17448. "\r\n"
  17449. "text2"
  17450. "\r\n------------\r\n"
  17451. "That should be disregarded. Not even read";
  17452. std::string response;
  17453. ASSERT_TRUE(send_request(1, req, &response));
  17454. ASSERT_EQ("200", response.substr(9, 3));
  17455. }
  17456. TEST(MultipartFormDataTest, LargeHeader) {
  17457. auto handled = false;
  17458. Server svr;
  17459. svr.Post("/test", [&](const Request &req, Response &) {
  17460. ASSERT_EQ(1u, req.form.fields.size());
  17461. const auto &text = req.form.get_field("name1");
  17462. ASSERT_EQ("text1", text);
  17463. handled = true;
  17464. });
  17465. thread t = thread([&] { svr.listen(HOST, PORT); });
  17466. auto se = detail::scope_exit([&] {
  17467. svr.stop();
  17468. t.join();
  17469. ASSERT_FALSE(svr.is_running());
  17470. ASSERT_TRUE(handled);
  17471. });
  17472. svr.wait_until_ready();
  17473. auto boundary = std::string("cpp-httplib-multipart-data");
  17474. std::string content = "--" + boundary +
  17475. "\r\n"
  17476. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17477. "\r\n"
  17478. "text1\r\n"
  17479. "--" +
  17480. boundary + "--\r\n";
  17481. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17482. "Host: localhost\r\n"
  17483. "Content-Type: multipart/form-data;boundary=" +
  17484. boundary +
  17485. "\r\n"
  17486. "Content-Length: " +
  17487. std::to_string(content.size()) +
  17488. "\r\n"
  17489. "Dummy-Header: ";
  17490. std::string header_suffix = "\r\n"
  17491. "\r\n";
  17492. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17493. size_t header_dummy_size =
  17494. read_buff_size -
  17495. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17496. auto header_dummy = std::string(header_dummy_size, '@');
  17497. auto req = header_prefix + header_dummy + header_suffix + content;
  17498. std::string response;
  17499. ASSERT_TRUE(send_request(1, req, &response));
  17500. ASSERT_EQ("200", response.substr(9, 3));
  17501. }
  17502. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17503. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17504. // (not chunked Transfer-Encoding) after the streaming refactor.
  17505. auto handled = false;
  17506. Server svr;
  17507. svr.Post("/upload", [&](const Request &req, Response &res) {
  17508. auto cl_it = req.headers.find("Content-Length");
  17509. EXPECT_TRUE(cl_it != req.headers.end());
  17510. auto te_it = req.headers.find("Transfer-Encoding");
  17511. EXPECT_TRUE(te_it == req.headers.end());
  17512. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17513. res.set_content("ok", "text/plain");
  17514. handled = true;
  17515. });
  17516. auto port = svr.bind_to_any_port(HOST);
  17517. auto t = thread([&] { svr.listen_after_bind(); });
  17518. auto se = detail::scope_exit([&] {
  17519. svr.stop();
  17520. t.join();
  17521. ASSERT_FALSE(svr.is_running());
  17522. ASSERT_TRUE(handled);
  17523. });
  17524. svr.wait_until_ready();
  17525. UploadFormDataItems items = {
  17526. {"field1", "hello", "", "text/plain"},
  17527. {"file1", "world", "test.txt", "application/octet-stream"},
  17528. };
  17529. Client cli(HOST, port);
  17530. auto res = cli.Post("/upload", {}, items);
  17531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17532. EXPECT_EQ(StatusCode::OK_200, res->status);
  17533. }
  17534. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17535. // Verify that make_multipart_content_provider coalesces many small segments
  17536. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17537. constexpr size_t kItemCount = 1000;
  17538. UploadFormDataItems items;
  17539. items.reserve(kItemCount);
  17540. for (size_t i = 0; i < kItemCount; i++) {
  17541. items.push_back(
  17542. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17543. }
  17544. const std::string boundary = "----test-boundary";
  17545. auto content_length = detail::get_multipart_content_length(items, boundary);
  17546. auto provider = detail::make_multipart_content_provider(items, boundary);
  17547. // Drive the provider the same way write_content_with_progress does
  17548. size_t write_count = 0;
  17549. size_t total_bytes = 0;
  17550. DataSink sink;
  17551. size_t offset = 0;
  17552. sink.write = [&](const char *d, size_t l) -> bool {
  17553. (void)d;
  17554. write_count++;
  17555. total_bytes += l;
  17556. offset += l;
  17557. return true;
  17558. };
  17559. sink.is_writable = []() -> bool { return true; };
  17560. while (offset < content_length) {
  17561. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17562. }
  17563. EXPECT_EQ(content_length, total_bytes);
  17564. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17565. // With buffering into 64KB blocks, write_count should be much smaller.
  17566. auto segment_count = 3 * kItemCount + 1;
  17567. EXPECT_LT(write_count, segment_count / 10);
  17568. }
  17569. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17570. // Integration test: send many UploadFormDataItems and verify the server
  17571. // receives all of them correctly (#2410).
  17572. constexpr size_t kItemCount = 500;
  17573. auto handled = false;
  17574. Server svr;
  17575. svr.Post("/upload", [&](const Request &req, Response &res) {
  17576. EXPECT_EQ(kItemCount, req.form.fields.size());
  17577. for (size_t i = 0; i < kItemCount; i++) {
  17578. auto key = "field" + std::to_string(i);
  17579. auto val = "value" + std::to_string(i);
  17580. auto it = req.form.fields.find(key);
  17581. if (it != req.form.fields.end()) {
  17582. EXPECT_EQ(val, it->second.content);
  17583. } else {
  17584. ADD_FAILURE() << "Missing field: " << key;
  17585. }
  17586. }
  17587. res.set_content("ok", "text/plain");
  17588. handled = true;
  17589. });
  17590. auto port = svr.bind_to_any_port(HOST);
  17591. auto t = thread([&] { svr.listen_after_bind(); });
  17592. auto se = detail::scope_exit([&] {
  17593. svr.stop();
  17594. t.join();
  17595. ASSERT_FALSE(svr.is_running());
  17596. ASSERT_TRUE(handled);
  17597. });
  17598. svr.wait_until_ready();
  17599. UploadFormDataItems items;
  17600. items.reserve(kItemCount);
  17601. for (size_t i = 0; i < kItemCount; i++) {
  17602. items.push_back(
  17603. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17604. }
  17605. Client cli(HOST, port);
  17606. auto res = cli.Post("/upload", items);
  17607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17608. EXPECT_EQ(StatusCode::OK_200, res->status);
  17609. }
  17610. TEST(MultipartFormDataTest, MakeFileProvider) {
  17611. // Verify make_file_provider sends a file's contents correctly.
  17612. const std::string file_content(4096, 'Z');
  17613. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17614. {
  17615. std::ofstream ofs(tmp_path, std::ios::binary);
  17616. ofs.write(file_content.data(),
  17617. static_cast<std::streamsize>(file_content.size()));
  17618. }
  17619. auto handled = false;
  17620. Server svr;
  17621. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17622. const ContentReader &content_reader) {
  17623. ASSERT_TRUE(req.is_multipart_form_data());
  17624. std::vector<FormData> items;
  17625. content_reader(
  17626. [&](const FormData &file) {
  17627. items.push_back(file);
  17628. return true;
  17629. },
  17630. [&](const char *data, size_t data_length) {
  17631. items.back().content.append(data, data_length);
  17632. return true;
  17633. });
  17634. ASSERT_EQ(1u, items.size());
  17635. EXPECT_EQ("myfile", items[0].name);
  17636. EXPECT_EQ("data.bin", items[0].filename);
  17637. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17638. EXPECT_EQ(file_content, items[0].content);
  17639. handled = true;
  17640. });
  17641. auto port = svr.bind_to_any_port(HOST);
  17642. auto t = thread([&] { svr.listen_after_bind(); });
  17643. auto se = detail::scope_exit([&] {
  17644. svr.stop();
  17645. t.join();
  17646. ASSERT_FALSE(svr.is_running());
  17647. ASSERT_TRUE(handled);
  17648. std::remove(tmp_path.c_str());
  17649. });
  17650. svr.wait_until_ready();
  17651. FormDataProviderItems providers;
  17652. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17653. "application/octet-stream"));
  17654. Client cli(HOST, port);
  17655. auto res = cli.Post("/upload", {}, {}, providers);
  17656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17657. EXPECT_EQ(StatusCode::OK_200, res->status);
  17658. }
  17659. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17660. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17661. // (100) headers is rejected with a 400 Bad Request response.
  17662. Server svr;
  17663. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17664. res.set_content("ok", "text/plain");
  17665. });
  17666. thread t = thread([&] { svr.listen(HOST, PORT); });
  17667. auto se = detail::scope_exit([&] {
  17668. svr.stop();
  17669. t.join();
  17670. ASSERT_FALSE(svr.is_running());
  17671. });
  17672. svr.wait_until_ready();
  17673. // Build a multipart part with 101 custom headers (exceeding
  17674. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17675. std::stringstream body;
  17676. body << "--simpleboundary\r\n"
  17677. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17678. for (int i = 0; i < 101; i++) {
  17679. body << "X-Custom-Header-" << i << ": value\r\n";
  17680. }
  17681. body << "\r\n"
  17682. << "value1\r\n"
  17683. << "--simpleboundary--\r\n";
  17684. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17685. Client cli(HOST, PORT);
  17686. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17687. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17688. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17689. }
  17690. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17691. // A body that never contains the declared boundary must not be accumulated
  17692. // while the parser waits for it. Buffering it would also make every read
  17693. // rescan everything seen so far, which is quadratic in the body size.
  17694. Server svr;
  17695. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17696. res.set_content("ok", "text/plain");
  17697. });
  17698. auto port = svr.bind_to_any_port(HOST);
  17699. thread t = thread([&] { svr.listen_after_bind(); });
  17700. auto se = detail::scope_exit([&] {
  17701. svr.stop();
  17702. t.join();
  17703. ASSERT_FALSE(svr.is_running());
  17704. });
  17705. svr.wait_until_ready();
  17706. Client cli(HOST, port);
  17707. cli.set_read_timeout(60, 0);
  17708. cli.set_write_timeout(60, 0);
  17709. // '-' is the worst case: it matches the first character of the boundary, so
  17710. // every position has to be checked against it.
  17711. auto post_dashes = [&](size_t size) {
  17712. const std::string body(size, '-');
  17713. auto start = std::chrono::steady_clock::now();
  17714. auto res =
  17715. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17716. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17717. std::chrono::steady_clock::now() - start)
  17718. .count();
  17719. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17720. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17721. return ms;
  17722. };
  17723. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17724. // Windows.
  17725. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17726. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17727. // Comparing the two sizes rather than checking an absolute duration keeps
  17728. // this meaningful across build types and CI load, both of which move the
  17729. // absolute numbers by more than an order of magnitude. Four times the bytes
  17730. // costs about four times the time when parsing is linear, and about sixteen
  17731. // times when the body is buffered and rescanned.
  17732. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17733. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17734. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17735. << "ms, which suggests the body is being buffered and rescanned";
  17736. }
  17737. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17738. // A boundary can only be followed by CRLF or by "--", so anything else is
  17739. // malformed no matter what comes next. The parser must say so right away
  17740. // instead of buffering the rest of the declared body.
  17741. Server svr;
  17742. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17743. res.set_content("ok", "text/plain");
  17744. });
  17745. auto port = svr.bind_to_any_port(HOST);
  17746. thread t = thread([&] { svr.listen_after_bind(); });
  17747. auto se = detail::scope_exit([&] {
  17748. svr.stop();
  17749. t.join();
  17750. ASSERT_FALSE(svr.is_running());
  17751. });
  17752. svr.wait_until_ready();
  17753. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17754. // buffers instead of failing would still be waiting for the remaining bytes.
  17755. const std::string body = "--zzzz\r\n"
  17756. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17757. "\r\n"
  17758. "text1"
  17759. "\r\n--zzzzXX";
  17760. const std::string req = "POST /post HTTP/1.1\r\n"
  17761. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17762. "Content-Length: 1048576\r\n"
  17763. "\r\n" +
  17764. body;
  17765. std::string response;
  17766. ASSERT_TRUE(send_request(3, req, &response, port));
  17767. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17768. EXPECT_EQ("400", response.substr(9, 3));
  17769. }
  17770. // Posts a multipart body split into two writes, so that the server sees the
  17771. // split at whatever offset the caller chose, and expects the single "text1"
  17772. // field to come through.
  17773. static void expect_split_multipart_ok(const std::string &body1,
  17774. const std::string &body2) {
  17775. auto handled = false;
  17776. Server svr;
  17777. svr.Post("/post", [&](const Request &req, Response &) {
  17778. EXPECT_EQ(1u, req.form.fields.size());
  17779. EXPECT_EQ("text1", req.form.get_field("text1"));
  17780. handled = true;
  17781. });
  17782. auto port = svr.bind_to_any_port(HOST);
  17783. thread t = thread([&] { svr.listen_after_bind(); });
  17784. auto se = detail::scope_exit([&] {
  17785. svr.stop();
  17786. t.join();
  17787. ASSERT_FALSE(svr.is_running());
  17788. ASSERT_TRUE(handled);
  17789. });
  17790. svr.wait_until_ready();
  17791. // "Connection: close" makes the server close once it has answered, so the
  17792. // response drain ends immediately instead of idling until the read timeout.
  17793. const std::string head =
  17794. "POST /post HTTP/1.1\r\n"
  17795. "Host: localhost\r\n"
  17796. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17797. "Connection: close\r\n"
  17798. "Content-Length: " +
  17799. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17800. std::string response;
  17801. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17802. ASSERT_GE(response.size(), 12u) << "no response";
  17803. EXPECT_EQ("200", response.substr(9, 3));
  17804. }
  17805. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17806. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17807. // ignored, including when it does not arrive in the same read as the
  17808. // close-delimiter itself.
  17809. expect_split_multipart_ok("--zzzz\r\n"
  17810. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17811. "\r\n"
  17812. "text1"
  17813. "\r\n--zzzz--",
  17814. "\r\nthis epilogue must be ignored\r\n");
  17815. }
  17816. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17817. // The initial boundary may be preceded by a preamble of any length and may
  17818. // straddle a read boundary. Discarding data while waiting for it must not
  17819. // throw away a partial boundary sitting at the end of the buffer.
  17820. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17821. "zz\r\n"
  17822. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17823. "\r\n"
  17824. "text1"
  17825. "\r\n--zzzz--\r\n");
  17826. }
  17827. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17828. // The received boundary was only checked for being non-empty, so it could be
  17829. // as long as a header is allowed to be. The parser scans the body for
  17830. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17831. // costs a nearly full comparison at nearly every position, making the
  17832. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17833. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17834. Server svr;
  17835. svr.Post("/post", [](const Request &req, Response &res) {
  17836. EXPECT_EQ(1u, req.form.fields.size());
  17837. EXPECT_EQ("text1", req.form.get_field("text1"));
  17838. res.set_content("ok", "text/plain");
  17839. });
  17840. auto port = svr.bind_to_any_port(HOST);
  17841. thread t = thread([&] { svr.listen_after_bind(); });
  17842. auto se = detail::scope_exit([&] {
  17843. svr.stop();
  17844. t.join();
  17845. ASSERT_FALSE(svr.is_running());
  17846. });
  17847. svr.wait_until_ready();
  17848. Client cli(HOST, port);
  17849. auto post_with_boundary_of_length = [&](size_t len) {
  17850. const std::string boundary(len, 'a');
  17851. const std::string body =
  17852. "--" + boundary +
  17853. "\r\n"
  17854. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17855. "\r\n"
  17856. "text1"
  17857. "\r\n--" +
  17858. boundary + "--\r\n";
  17859. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17860. };
  17861. auto res = post_with_boundary_of_length(70);
  17862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17863. EXPECT_EQ(StatusCode::OK_200, res->status);
  17864. res = post_with_boundary_of_length(71);
  17865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17866. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17867. }
  17868. TEST(MakeFileBodyTest, Basic) {
  17869. const std::string file_content(4096, 'Z');
  17870. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17871. {
  17872. std::ofstream ofs(tmp_path, std::ios::binary);
  17873. ofs.write(file_content.data(),
  17874. static_cast<std::streamsize>(file_content.size()));
  17875. }
  17876. auto handled = false;
  17877. Server svr;
  17878. svr.Post("/upload", [&](const Request &req, Response &res) {
  17879. EXPECT_EQ(file_content, req.body);
  17880. handled = true;
  17881. res.status = StatusCode::OK_200;
  17882. });
  17883. auto port = svr.bind_to_any_port(HOST);
  17884. auto t = thread([&] { svr.listen_after_bind(); });
  17885. auto se = detail::scope_exit([&] {
  17886. svr.stop();
  17887. t.join();
  17888. ASSERT_FALSE(svr.is_running());
  17889. ASSERT_TRUE(handled);
  17890. std::remove(tmp_path.c_str());
  17891. });
  17892. svr.wait_until_ready();
  17893. auto fb = make_file_body(tmp_path);
  17894. ASSERT_GT(fb.first, 0u);
  17895. Client cli(HOST, port);
  17896. auto res =
  17897. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17899. EXPECT_EQ(StatusCode::OK_200, res->status);
  17900. }
  17901. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17902. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17903. {
  17904. std::ofstream ofs(path, std::ios::binary);
  17905. const std::string content(100, 'A');
  17906. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17907. }
  17908. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17909. auto body = make_file_body(path);
  17910. ASSERT_EQ(100u, body.first);
  17911. ASSERT_TRUE(static_cast<bool>(body.second));
  17912. // Rewritten shorter after its length was measured - and, on a server, after
  17913. // that length has already gone out as Content-Length.
  17914. {
  17915. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17916. const std::string content(10, 'A');
  17917. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17918. }
  17919. std::string written;
  17920. DataSink sink;
  17921. sink.write = [&](const char *d, size_t l) {
  17922. written.append(d, l);
  17923. return true;
  17924. };
  17925. // The provider has to report failure. write_content_with_progress() advances
  17926. // its offset only by what was written, so a provider that returns true
  17927. // without completing the length it promised is called again straight away,
  17928. // and again.
  17929. EXPECT_FALSE(body.second(0, body.first, sink));
  17930. EXPECT_EQ(std::string(10, 'A'), written);
  17931. }
  17932. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17933. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17934. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17935. {
  17936. std::ofstream ofs(path, std::ios::binary);
  17937. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17938. }
  17939. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17940. auto body = make_file_body(path);
  17941. ASSERT_EQ(content.size(), body.first);
  17942. ASSERT_TRUE(static_cast<bool>(body.second));
  17943. std::string written;
  17944. DataSink sink;
  17945. sink.write = [&](const char *d, size_t l) {
  17946. written.append(d, l);
  17947. return true;
  17948. };
  17949. EXPECT_TRUE(body.second(0, body.first, sink));
  17950. EXPECT_EQ(content, written);
  17951. }
  17952. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17953. static constexpr unsigned int number_of_tasks{1000000};
  17954. std::atomic_uint count{0};
  17955. std::unique_ptr<TaskQueue> task_queue{
  17956. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17957. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17958. auto queued = task_queue->enqueue(
  17959. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17960. EXPECT_TRUE(queued);
  17961. }
  17962. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17963. task_queue->shutdown();
  17964. #else
  17965. EXPECT_NO_THROW(task_queue->shutdown());
  17966. #endif
  17967. EXPECT_EQ(number_of_tasks, count.load());
  17968. }
  17969. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17970. static constexpr unsigned int number_of_tasks{1000000};
  17971. static constexpr unsigned int qlimit{2};
  17972. unsigned int queued_count{0};
  17973. std::atomic_uint count{0};
  17974. std::unique_ptr<TaskQueue> task_queue{
  17975. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17976. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17977. if (task_queue->enqueue(
  17978. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17979. queued_count++;
  17980. }
  17981. }
  17982. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17983. task_queue->shutdown();
  17984. #else
  17985. EXPECT_NO_THROW(task_queue->shutdown());
  17986. #endif
  17987. EXPECT_EQ(queued_count, count.load());
  17988. EXPECT_TRUE(queued_count <= number_of_tasks);
  17989. EXPECT_TRUE(queued_count >= qlimit);
  17990. }
  17991. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17992. // Use a short idle timeout so a dynamic thread spawns, times out and
  17993. // exits during the test, and the pool keeps working afterwards.
  17994. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17995. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17996. /*idle_timeout_sec=*/1}};
  17997. std::atomic_uint count{0};
  17998. std::condition_variable cv;
  17999. std::mutex mtx;
  18000. bool release = false;
  18001. // Block the base thread so the second task spawns a dynamic thread.
  18002. EXPECT_TRUE(task_queue->enqueue([&] {
  18003. std::unique_lock<std::mutex> lock(mtx);
  18004. while (!release) {
  18005. cv.wait(lock);
  18006. }
  18007. count++;
  18008. }));
  18009. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  18010. // Let the dynamic thread finish its task and exceed the idle timeout.
  18011. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  18012. {
  18013. std::unique_lock<std::mutex> lock(mtx);
  18014. release = true;
  18015. }
  18016. cv.notify_all();
  18017. // The pool must still accept and run tasks after the dynamic thread exited.
  18018. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  18019. task_queue->shutdown();
  18020. EXPECT_EQ(3u, count.load());
  18021. }
  18022. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  18023. static constexpr size_t number_of_tasks{32};
  18024. std::unique_ptr<TaskQueue> task_queue{
  18025. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  18026. // Let the base threads go idle so the burst below finds them waiting.
  18027. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18028. std::mutex mtx;
  18029. std::condition_variable cv;
  18030. size_t running = 0;
  18031. bool release = false;
  18032. for (size_t i = 0; i < number_of_tasks; i++) {
  18033. EXPECT_TRUE(task_queue->enqueue([&] {
  18034. std::unique_lock<std::mutex> lock(mtx);
  18035. running++;
  18036. cv.notify_all();
  18037. cv.wait(lock, [&] { return release; });
  18038. }));
  18039. }
  18040. {
  18041. std::unique_lock<std::mutex> lock(mtx);
  18042. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  18043. [&] { return running == number_of_tasks; }));
  18044. release = true;
  18045. }
  18046. cv.notify_all();
  18047. task_queue->shutdown();
  18048. }
  18049. TEST(TaskQueueTest, MaxQueuedRequests) {
  18050. static constexpr unsigned int qlimit{3};
  18051. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  18052. std::condition_variable sem_cv;
  18053. std::mutex sem_mtx;
  18054. int credits = 0;
  18055. bool queued;
  18056. /* Fill up the queue with tasks that will block until we give them credits to
  18057. * complete. */
  18058. for (unsigned int n = 0; n <= qlimit;) {
  18059. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  18060. std::unique_lock<std::mutex> lock(sem_mtx);
  18061. while (credits <= 0) {
  18062. sem_cv.wait(lock);
  18063. }
  18064. /* Consume the credit and signal the test code if they are all gone. */
  18065. if (--credits == 0) { sem_cv.notify_one(); }
  18066. });
  18067. if (n < qlimit) {
  18068. /* The first qlimit enqueues must succeed. */
  18069. EXPECT_TRUE(queued);
  18070. } else {
  18071. /* The last one will succeed only when the worker thread
  18072. * starts and dequeues the first blocking task. Although
  18073. * not necessary for the correctness of this test, we sleep for
  18074. * a short while to avoid busy waiting. */
  18075. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18076. }
  18077. if (queued) { n++; }
  18078. }
  18079. /* Further enqueues must fail since the queue is full. */
  18080. for (auto i = 0; i < 4; i++) {
  18081. queued = task_queue->enqueue([] {});
  18082. EXPECT_FALSE(queued);
  18083. }
  18084. /* Give the credits to allow the previous tasks to complete. */
  18085. {
  18086. std::unique_lock<std::mutex> lock(sem_mtx);
  18087. credits += qlimit + 1;
  18088. }
  18089. sem_cv.notify_all();
  18090. /* Wait for all the credits to be consumed. */
  18091. {
  18092. std::unique_lock<std::mutex> lock(sem_mtx);
  18093. while (credits > 0) {
  18094. sem_cv.wait(lock);
  18095. }
  18096. }
  18097. /* Check that we are able again to enqueue at least qlimit tasks. */
  18098. for (unsigned int i = 0; i < qlimit; i++) {
  18099. queued = task_queue->enqueue([] {});
  18100. EXPECT_TRUE(queued);
  18101. }
  18102. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  18103. task_queue->shutdown();
  18104. #else
  18105. EXPECT_NO_THROW(task_queue->shutdown());
  18106. #endif
  18107. }
  18108. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  18109. Server svr;
  18110. std::string method;
  18111. std::string body;
  18112. auto has_content_length = false;
  18113. auto has_transfer_encoding = false;
  18114. std::atomic<int> bad_requests{0};
  18115. // Leftover body bytes get parsed as a malformed request and answered with
  18116. // 400
  18117. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  18118. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  18119. });
  18120. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  18121. res.set_redirect("/down", StatusCode::SeeOther_303);
  18122. });
  18123. svr.Get("/down", [&](const Request &req, Response &res) {
  18124. method = req.method;
  18125. body = req.body;
  18126. has_content_length = req.has_header("Content-Length");
  18127. has_transfer_encoding = req.has_header("Transfer-Encoding");
  18128. res.set_content("ok", "text/plain");
  18129. });
  18130. auto port = svr.bind_to_any_port(HOST);
  18131. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18132. auto se = detail::scope_exit([&] {
  18133. svr.stop();
  18134. thread.join();
  18135. ASSERT_FALSE(svr.is_running());
  18136. });
  18137. svr.wait_until_ready();
  18138. const std::string payload = "SECRET-BODY";
  18139. auto check = [&](Client &cli, const Result &res) {
  18140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18141. EXPECT_EQ(StatusCode::OK_200, res->status);
  18142. EXPECT_EQ("ok", res->body);
  18143. EXPECT_EQ("GET", method);
  18144. EXPECT_TRUE(body.empty());
  18145. EXPECT_FALSE(has_content_length);
  18146. EXPECT_FALSE(has_transfer_encoding);
  18147. // Nothing of the original body may be left on the connection
  18148. auto res2 = cli.Get("/down");
  18149. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18150. EXPECT_EQ(StatusCode::OK_200, res2->status);
  18151. EXPECT_EQ("ok", res2->body);
  18152. EXPECT_EQ(0, bad_requests);
  18153. };
  18154. // With content length
  18155. {
  18156. Client cli(HOST, port);
  18157. cli.set_keep_alive(true);
  18158. cli.set_follow_location(true);
  18159. auto res = cli.Post(
  18160. "/up", payload.size(),
  18161. [&](size_t offset, size_t length, DataSink &sink) {
  18162. return sink.write(payload.data() + offset, length);
  18163. },
  18164. "text/plain");
  18165. check(cli, res);
  18166. }
  18167. // Without content length (chunked)
  18168. {
  18169. Client cli(HOST, port);
  18170. cli.set_keep_alive(true);
  18171. cli.set_follow_location(true);
  18172. auto res = cli.Post(
  18173. "/up",
  18174. [&](size_t /*offset*/, DataSink &sink) {
  18175. sink.write(payload.data(), payload.size());
  18176. sink.done();
  18177. return true;
  18178. },
  18179. "text/plain");
  18180. check(cli, res);
  18181. }
  18182. }
  18183. TEST(RedirectTest, LocationPathIsNotDecoded) {
  18184. Server svr;
  18185. std::string target;
  18186. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  18187. // Echo the still-encoded name back in the Location
  18188. const std::string prefix = "/start/";
  18189. res.status = StatusCode::Found_302;
  18190. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  18191. });
  18192. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  18193. target = req.target;
  18194. res.set_content("ok", "text/plain");
  18195. });
  18196. auto port = svr.bind_to_any_port(HOST);
  18197. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18198. auto se = detail::scope_exit([&] {
  18199. svr.stop();
  18200. thread.join();
  18201. ASSERT_FALSE(svr.is_running());
  18202. });
  18203. svr.wait_until_ready();
  18204. // Decoding the Location path would turn the first four into a path
  18205. // separator, a query delimiter, a fragment delimiter and a different
  18206. // percent-encoded octet. The rest must keep reaching the server as they are.
  18207. const std::vector<std::string> names = {
  18208. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  18209. };
  18210. for (auto path_encode : {true, false}) {
  18211. Client cli(HOST, port);
  18212. cli.set_follow_location(true);
  18213. cli.set_path_encode(path_encode);
  18214. for (const auto &name : names) {
  18215. target.clear();
  18216. auto res = cli.Get("/start/" + name);
  18217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18218. EXPECT_EQ(StatusCode::OK_200, res->status);
  18219. EXPECT_EQ("/dest/" + name, target);
  18220. }
  18221. }
  18222. }
  18223. TEST(RedirectTest, NotModifiedIsReturned) {
  18224. Server svr;
  18225. svr.Get("/cached", [](const Request &, Response &res) {
  18226. res.status = StatusCode::NotModified_304;
  18227. });
  18228. auto port = svr.bind_to_any_port(HOST);
  18229. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18230. auto se = detail::scope_exit([&] {
  18231. svr.stop();
  18232. thread.join();
  18233. ASSERT_FALSE(svr.is_running());
  18234. });
  18235. svr.wait_until_ready();
  18236. Client cli(HOST, port);
  18237. cli.set_follow_location(true);
  18238. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  18239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18240. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  18241. }
  18242. TEST(RedirectTest, NoLocationIsReturned) {
  18243. Server svr;
  18244. svr.Get("/no-location", [](const Request &, Response &res) {
  18245. res.status = StatusCode::Found_302;
  18246. res.set_content("no location", "text/plain");
  18247. });
  18248. auto port = svr.bind_to_any_port(HOST);
  18249. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18250. auto se = detail::scope_exit([&] {
  18251. svr.stop();
  18252. thread.join();
  18253. ASSERT_FALSE(svr.is_running());
  18254. });
  18255. svr.wait_until_ready();
  18256. Client cli(HOST, port);
  18257. cli.set_follow_location(true);
  18258. auto res = cli.Get("/no-location");
  18259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18260. EXPECT_EQ(StatusCode::Found_302, res->status);
  18261. EXPECT_EQ("no location", res->body);
  18262. // The callbacks see the body of the response that is returned
  18263. auto handler_called = false;
  18264. auto progress_called = false;
  18265. std::string body;
  18266. auto res2 = cli.Get(
  18267. "/no-location",
  18268. [&](const Response &) {
  18269. handler_called = true;
  18270. return true;
  18271. },
  18272. [&](const char *data, size_t data_length) {
  18273. body.append(data, data_length);
  18274. return true;
  18275. },
  18276. [&](size_t, size_t) {
  18277. progress_called = true;
  18278. return true;
  18279. });
  18280. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18281. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18282. EXPECT_TRUE(handler_called);
  18283. EXPECT_TRUE(progress_called);
  18284. EXPECT_EQ("no location", body);
  18285. }
  18286. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18287. Server svr;
  18288. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18289. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18290. });
  18291. svr.Get("/hello", [](const Request &req, Response &res) {
  18292. res.set_content(req.get_param_value("key"), "text/plain");
  18293. });
  18294. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18295. auto se = detail::scope_exit([&] {
  18296. svr.stop();
  18297. thread.join();
  18298. ASSERT_FALSE(svr.is_running());
  18299. });
  18300. svr.wait_until_ready();
  18301. {
  18302. Client cli(HOST, PORT);
  18303. cli.set_follow_location(true);
  18304. auto res = cli.Get("/");
  18305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18306. EXPECT_EQ(StatusCode::OK_200, res->status);
  18307. EXPECT_EQ("val&key2=val2", res->body);
  18308. }
  18309. }
  18310. #endif
  18311. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18312. Server svr;
  18313. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18314. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18315. });
  18316. svr.Get("/hello", [](const Request &req, Response &res) {
  18317. res.set_content(req.get_param_value("key"), "text/plain");
  18318. });
  18319. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18320. auto se = detail::scope_exit([&] {
  18321. svr.stop();
  18322. thread.join();
  18323. ASSERT_FALSE(svr.is_running());
  18324. });
  18325. svr.wait_until_ready();
  18326. {
  18327. Client cli(HOST, PORT);
  18328. cli.set_follow_location(true);
  18329. auto res = cli.Get("/");
  18330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18331. EXPECT_EQ(StatusCode::OK_200, res->status);
  18332. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18333. }
  18334. }
  18335. TEST(RedirectTest, RedirectWithPlusInPath) {
  18336. Server svr;
  18337. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18338. res.set_redirect("/a+b");
  18339. });
  18340. // Route pattern uses regex; escape + as \\+
  18341. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18342. res.set_content(req.path, "text/plain");
  18343. });
  18344. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18345. auto se = detail::scope_exit([&] {
  18346. svr.stop();
  18347. thread.join();
  18348. ASSERT_FALSE(svr.is_running());
  18349. });
  18350. svr.wait_until_ready();
  18351. {
  18352. Client cli(HOST, PORT);
  18353. cli.set_follow_location(true);
  18354. auto res = cli.Get("/");
  18355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18356. EXPECT_EQ(StatusCode::OK_200, res->status);
  18357. EXPECT_EQ("/a+b", res->body);
  18358. }
  18359. }
  18360. TEST(RedirectTest, ResolveRelativeLocation) {
  18361. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18362. const std::vector<std::pair<std::string, std::string>> cases = {
  18363. {"g", "/b/c/g"},
  18364. {"./g", "/b/c/g"},
  18365. {"g/", "/b/c/g/"},
  18366. {"?y", "/b/c/d;p?y"},
  18367. {"g?y", "/b/c/g?y"},
  18368. {"#s", "/b/c/d;p?q#s"},
  18369. {"g#s", "/b/c/g#s"},
  18370. {"g?y#s", "/b/c/g?y#s"},
  18371. {";x", "/b/c/;x"},
  18372. {"g;x", "/b/c/g;x"},
  18373. {".", "/b/c/"},
  18374. {"./", "/b/c/"},
  18375. {"..", "/b/"},
  18376. {"../", "/b/"},
  18377. {"../g", "/b/g"},
  18378. {"../..", "/"},
  18379. {"../../", "/"},
  18380. {"../../g", "/g"},
  18381. {"../../../g", "/g"},
  18382. {"g.", "/b/c/g."},
  18383. {".g", "/b/c/.g"},
  18384. {"g..", "/b/c/g.."},
  18385. {"..g", "/b/c/..g"},
  18386. {"./../g", "/b/g"},
  18387. {"./g/.", "/b/c/g/"},
  18388. {"g/./h", "/b/c/g/h"},
  18389. {"g/../h", "/b/c/h"},
  18390. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18391. {"g;x=1/../y", "/b/c/y"},
  18392. {"g?y/./x", "/b/c/g?y/./x"},
  18393. {"g#s/../x", "/b/c/g#s/../x"},
  18394. // Not relative-path references, so left for parse_url.
  18395. {"/g", "/g"},
  18396. {"//g", "//g"},
  18397. {"http://g/x", "http://g/x"},
  18398. {"g:h", "g:h"},
  18399. };
  18400. for (const auto &c : cases) {
  18401. EXPECT_EQ(c.second,
  18402. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18403. << c.first;
  18404. }
  18405. // A result starting with "//" is still a path, not a network-path reference
  18406. EXPECT_EQ("/.//g",
  18407. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18408. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18409. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18410. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18411. }
  18412. TEST(RedirectTest, RemoveDotSegments) {
  18413. // RFC 3986 section 5.2.4
  18414. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18415. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18416. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18417. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18418. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18419. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18420. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18421. }
  18422. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18423. Server svr;
  18424. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18425. res.set_redirect("/dir/../target?x=1");
  18426. });
  18427. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18428. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18429. "/dir/./../target");
  18430. });
  18431. svr.Get("/target", [](const Request &req, Response &res) {
  18432. res.set_content(req.path, "text/plain");
  18433. });
  18434. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18435. auto se = detail::scope_exit([&] {
  18436. svr.stop();
  18437. th.join();
  18438. ASSERT_FALSE(svr.is_running());
  18439. });
  18440. svr.wait_until_ready();
  18441. Client cli("localhost", PORT);
  18442. cli.set_follow_location(true);
  18443. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18444. auto res = cli.Get(path);
  18445. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18446. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18447. EXPECT_EQ("/target", res->body) << path;
  18448. }
  18449. }
  18450. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18451. Server svr;
  18452. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18453. res.set_redirect(req.get_param_value("to"));
  18454. });
  18455. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18456. res.set_content(req.target, "text/plain");
  18457. });
  18458. svr.Get("/other", [](const Request &req, Response &res) {
  18459. res.set_content(req.target, "text/plain");
  18460. });
  18461. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18462. auto se = detail::scope_exit([&] {
  18463. svr.stop();
  18464. thread.join();
  18465. ASSERT_FALSE(svr.is_running());
  18466. });
  18467. svr.wait_until_ready();
  18468. const std::vector<std::pair<std::string, std::string>> cases = {
  18469. {"next", "/dir/next"},
  18470. {"./next?x=1", "/dir/next?x=1"},
  18471. {"next?source=https://example.com/catalog",
  18472. "/dir/next?source=https://example.com/catalog"},
  18473. {"../other", "/other"},
  18474. };
  18475. for (const auto &c : cases) {
  18476. Client cli(HOST, PORT);
  18477. cli.set_follow_location(true);
  18478. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18479. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18480. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18481. EXPECT_EQ(c.second, res->body) << c.first;
  18482. }
  18483. }
  18484. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18485. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18486. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18487. Server other;
  18488. std::atomic<int> other_hits{0};
  18489. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18490. other_hits++;
  18491. res.set_content("other", "text/plain");
  18492. });
  18493. auto other_port = other.bind_to_any_port("127.0.0.1");
  18494. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18495. Server svr;
  18496. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18497. res.set_redirect(req.get_param_value("to"));
  18498. });
  18499. svr.Get(".*", [](const Request &req, Response &res) {
  18500. res.set_content(req.path, "text/plain");
  18501. });
  18502. auto port = svr.bind_to_any_port(HOST);
  18503. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18504. auto se = detail::scope_exit([&] {
  18505. svr.stop();
  18506. thread.join();
  18507. other.stop();
  18508. other_thread.join();
  18509. ASSERT_FALSE(svr.is_running());
  18510. ASSERT_FALSE(other.is_running());
  18511. });
  18512. svr.wait_until_ready();
  18513. other.wait_until_ready();
  18514. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18515. for (const auto &to :
  18516. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18517. Client cli(HOST, port);
  18518. cli.set_follow_location(true);
  18519. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18520. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18521. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18522. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18523. }
  18524. EXPECT_EQ(0, other_hits.load());
  18525. }
  18526. #ifdef CPPHTTPLIB_SSL_ENABLED
  18527. TEST(RedirectTest, Issue2185_Online) {
  18528. SSLClient client("github.com");
  18529. client.set_follow_location(true);
  18530. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18531. "Coollab-Windows.zip");
  18532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18533. EXPECT_EQ(StatusCode::OK_200, res->status);
  18534. EXPECT_EQ(9920427U, res->body.size());
  18535. }
  18536. #endif
  18537. TEST(VulnerabilityTest, CRLFInjection) {
  18538. Server svr;
  18539. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18540. res.set_content("Hello 1", "text/plain");
  18541. });
  18542. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18543. res.set_content("Hello 2", "text/plain");
  18544. });
  18545. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18546. res.set_content("Hello 3", "text/plain");
  18547. });
  18548. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18549. res.set_content("Hello 4", "text/plain");
  18550. });
  18551. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18552. for (const auto &x : req.headers) {
  18553. auto key = x.first;
  18554. EXPECT_STRNE("evil", key.c_str());
  18555. }
  18556. });
  18557. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18558. auto se = detail::scope_exit([&] {
  18559. svr.stop();
  18560. thread.join();
  18561. ASSERT_FALSE(svr.is_running());
  18562. });
  18563. svr.wait_until_ready();
  18564. {
  18565. Client cli(HOST, PORT);
  18566. cli.Post("/test1", "A=B",
  18567. "application/x-www-form-urlencoded\r\nevil: hello1");
  18568. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18569. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18570. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18571. }
  18572. }
  18573. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18574. auto server_thread = std::thread([] {
  18575. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18576. default_socket_options(srv);
  18577. sockaddr_in addr{};
  18578. addr.sin_family = AF_INET;
  18579. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18580. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18581. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18582. ::listen(srv, 1);
  18583. sockaddr_in cli_addr{};
  18584. socklen_t cli_len = sizeof(cli_addr);
  18585. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18586. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18587. std::string buf_all;
  18588. char buf[2048];
  18589. ssize_t n;
  18590. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18591. buf_all.append(buf, static_cast<size_t>(n));
  18592. size_t pos;
  18593. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18594. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18595. auto e = request_block.find("\r\n");
  18596. if (e != std::string::npos) {
  18597. auto request_line = request_block.substr(0, e);
  18598. std::string msg =
  18599. "CRLF injection detected in request line: '" + request_line + "'";
  18600. EXPECT_FALSE(true) << msg;
  18601. }
  18602. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18603. ::send(cli,
  18604. #ifdef _WIN32
  18605. static_cast<const char *>(resp.c_str()),
  18606. static_cast<int>(resp.size()),
  18607. #else
  18608. resp.c_str(), resp.size(),
  18609. #endif
  18610. 0);
  18611. buf_all.erase(0, pos + 4);
  18612. }
  18613. }
  18614. detail::close_socket(cli);
  18615. detail::close_socket(srv);
  18616. });
  18617. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18618. auto cli = Client("127.0.0.1", PORT + 1);
  18619. auto headers = Headers{
  18620. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18621. {"Connection", "keep-alive"}};
  18622. auto res = cli.Get("/hi", headers);
  18623. EXPECT_FALSE(res);
  18624. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18625. server_thread.join();
  18626. }
  18627. // A request rejected before any byte reaches the socket must fail right away
  18628. // instead of waiting for a response the server will never send.
  18629. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18630. // The kernel completes the TCP handshake from the listen backlog, so the
  18631. // client connects, but nothing ever reads, responds or closes.
  18632. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18633. default_socket_options(srv);
  18634. sockaddr_in addr{};
  18635. addr.sin_family = AF_INET;
  18636. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18637. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18638. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18639. ASSERT_EQ(0, ::listen(srv, 8));
  18640. auto cli = Client("127.0.0.1", PORT + 1);
  18641. cli.set_read_timeout(10, 0);
  18642. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18643. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18644. std::chrono::steady_clock::now() - start)
  18645. .count();
  18646. };
  18647. {
  18648. Request req;
  18649. req.method = "GE T";
  18650. req.path = "/";
  18651. auto start = std::chrono::steady_clock::now();
  18652. auto res = cli.send(req);
  18653. EXPECT_FALSE(res);
  18654. EXPECT_EQ(Error::Write, res.error());
  18655. EXPECT_LT(elapsed_ms(start), 1000);
  18656. }
  18657. {
  18658. auto start = std::chrono::steady_clock::now();
  18659. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18660. EXPECT_FALSE(res);
  18661. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18662. EXPECT_LT(elapsed_ms(start), 1000);
  18663. }
  18664. EXPECT_FALSE(cli.is_socket_open());
  18665. detail::close_socket(srv);
  18666. }
  18667. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18668. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18669. default_socket_options(srv);
  18670. sockaddr_in addr{};
  18671. addr.sin_family = AF_INET;
  18672. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18673. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18674. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18675. ASSERT_EQ(0, ::listen(srv, 1));
  18676. std::string received;
  18677. auto server_thread = std::thread([&] {
  18678. auto sock = ::accept(srv, nullptr, nullptr);
  18679. if (sock == INVALID_SOCKET) { return; }
  18680. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18681. char buf[2048];
  18682. ssize_t n;
  18683. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18684. received.append(buf, static_cast<size_t>(n));
  18685. }
  18686. detail::close_socket(sock);
  18687. });
  18688. {
  18689. auto cli = Client("127.0.0.1", PORT + 1);
  18690. // "Z" sorts after the default headers, so writing straight to the socket
  18691. // would have sent the request line and those headers before the rejection.
  18692. auto handle =
  18693. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18694. EXPECT_FALSE(handle.is_valid());
  18695. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18696. }
  18697. server_thread.join();
  18698. detail::close_socket(srv);
  18699. EXPECT_TRUE(received.empty()) << received;
  18700. }
  18701. TEST(PathParamsTest, StaticMatch) {
  18702. const auto pattern = "/users/all";
  18703. detail::PathParamsMatcher matcher(pattern);
  18704. Request request;
  18705. request.path = "/users/all";
  18706. ASSERT_TRUE(matcher.match(request));
  18707. std::unordered_map<std::string, std::string> expected_params = {};
  18708. EXPECT_EQ(request.path_params, expected_params);
  18709. }
  18710. TEST(PathParamsTest, StaticMismatch) {
  18711. const auto pattern = "/users/all";
  18712. detail::PathParamsMatcher matcher(pattern);
  18713. Request request;
  18714. request.path = "/users/1";
  18715. ASSERT_FALSE(matcher.match(request));
  18716. }
  18717. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18718. const auto pattern = "/users/:id/subscriptions";
  18719. detail::PathParamsMatcher matcher(pattern);
  18720. Request request;
  18721. request.path = "/users/42/subscriptions";
  18722. ASSERT_TRUE(matcher.match(request));
  18723. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18724. EXPECT_EQ(request.path_params, expected_params);
  18725. }
  18726. TEST(PathParamsTest, SingleParamInTheEnd) {
  18727. const auto pattern = "/users/:id";
  18728. detail::PathParamsMatcher matcher(pattern);
  18729. Request request;
  18730. request.path = "/users/24";
  18731. ASSERT_TRUE(matcher.match(request));
  18732. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18733. EXPECT_EQ(request.path_params, expected_params);
  18734. }
  18735. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18736. const auto pattern = "/users/:id/";
  18737. detail::PathParamsMatcher matcher(pattern);
  18738. Request request;
  18739. request.path = "/users/42/";
  18740. ASSERT_TRUE(matcher.match(request));
  18741. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18742. EXPECT_EQ(request.path_params, expected_params);
  18743. }
  18744. TEST(PathParamsTest, EmptyParam) {
  18745. const auto pattern = "/users/:id/";
  18746. detail::PathParamsMatcher matcher(pattern);
  18747. Request request;
  18748. request.path = "/users//";
  18749. ASSERT_TRUE(matcher.match(request));
  18750. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18751. EXPECT_EQ(request.path_params, expected_params);
  18752. }
  18753. TEST(PathParamsTest, FragmentMismatch) {
  18754. const auto pattern = "/users/:id/";
  18755. detail::PathParamsMatcher matcher(pattern);
  18756. Request request;
  18757. request.path = "/admins/24/";
  18758. ASSERT_FALSE(matcher.match(request));
  18759. }
  18760. TEST(PathParamsTest, ExtraFragments) {
  18761. const auto pattern = "/users/:id";
  18762. detail::PathParamsMatcher matcher(pattern);
  18763. Request request;
  18764. request.path = "/users/42/subscriptions";
  18765. ASSERT_FALSE(matcher.match(request));
  18766. }
  18767. TEST(PathParamsTest, MissingTrailingParam) {
  18768. const auto pattern = "/users/:id";
  18769. detail::PathParamsMatcher matcher(pattern);
  18770. Request request;
  18771. request.path = "/users";
  18772. ASSERT_FALSE(matcher.match(request));
  18773. }
  18774. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18775. const auto pattern = "/users/:id/subscriptions";
  18776. detail::PathParamsMatcher matcher(pattern);
  18777. Request request;
  18778. request.path = "/users/subscriptions";
  18779. ASSERT_FALSE(matcher.match(request));
  18780. }
  18781. TEST(PathParamsTest, MultipleParams) {
  18782. const auto pattern = "/users/:userid/subscriptions/:subid";
  18783. detail::PathParamsMatcher matcher(pattern);
  18784. Request request;
  18785. request.path = "/users/42/subscriptions/2";
  18786. ASSERT_TRUE(matcher.match(request));
  18787. std::unordered_map<std::string, std::string> expected_params = {
  18788. {"userid", "42"}, {"subid", "2"}};
  18789. EXPECT_EQ(request.path_params, expected_params);
  18790. }
  18791. TEST(PathParamsTest, SequenceOfParams) {
  18792. const auto pattern = "/values/:x/:y/:z";
  18793. detail::PathParamsMatcher matcher(pattern);
  18794. Request request;
  18795. request.path = "/values/1/2/3";
  18796. ASSERT_TRUE(matcher.match(request));
  18797. std::unordered_map<std::string, std::string> expected_params = {
  18798. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18799. EXPECT_EQ(request.path_params, expected_params);
  18800. }
  18801. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18802. const auto pattern = "/prefix:suffix";
  18803. detail::PathParamsMatcher matcher(pattern);
  18804. Request request;
  18805. request.path = "/prefix:suffix";
  18806. ASSERT_TRUE(matcher.match(request));
  18807. const std::unordered_map<std::string, std::string> expected_params = {};
  18808. EXPECT_EQ(request.path_params, expected_params);
  18809. }
  18810. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18811. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18812. // calling thread's stack on a long enough path for a quantified pattern;
  18813. // RegexMatcher must refuse to run regex matching on paths beyond
  18814. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18815. detail::RegexMatcher matcher("/files/(.*)");
  18816. Request within_limit;
  18817. within_limit.path = "/files/" + std::string(10, 'A');
  18818. EXPECT_TRUE(matcher.match(within_limit));
  18819. Request over_limit;
  18820. over_limit.path =
  18821. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18822. EXPECT_FALSE(matcher.match(over_limit));
  18823. }
  18824. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18825. Server svr;
  18826. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18827. res.set_content("ok", "text/plain");
  18828. });
  18829. auto port = svr.bind_to_any_port(HOST);
  18830. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18831. auto se = detail::scope_exit([&] {
  18832. svr.stop();
  18833. thread.join();
  18834. ASSERT_FALSE(svr.is_running());
  18835. });
  18836. svr.wait_until_ready();
  18837. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18838. // request URI limit; this used to be able to crash the process.
  18839. std::string path =
  18840. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18841. std::string req = "GET " + path +
  18842. " HTTP/1.1\r\n"
  18843. "Host: " +
  18844. std::string(HOST) + ":" + std::to_string(port) +
  18845. "\r\n"
  18846. "Connection: close\r\n"
  18847. "\r\n";
  18848. std::string response;
  18849. ASSERT_TRUE(send_request(5, req, &response, port));
  18850. EXPECT_NE(std::string::npos, response.find("404"));
  18851. }
  18852. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18853. Server svr;
  18854. auto handler = [](const Request & /*req*/, Response &res) {
  18855. res.set_content("hit", "text/plain");
  18856. };
  18857. // No regex metacharacter, so this one is compared literally
  18858. svr.Get("/literal/route", handler);
  18859. // '.' is a regex metacharacter, so this one must keep regex semantics
  18860. svr.Get("/a.c", handler);
  18861. auto port = svr.bind_to_any_port(HOST);
  18862. std::thread t([&]() { svr.listen_after_bind(); });
  18863. auto se = detail::scope_exit([&] {
  18864. svr.stop();
  18865. t.join();
  18866. ASSERT_FALSE(svr.is_running());
  18867. });
  18868. svr.wait_until_ready();
  18869. Client cli(HOST, port);
  18870. struct {
  18871. const char *path;
  18872. int status;
  18873. } cases[] = {
  18874. {"/literal/route", StatusCode::OK_200},
  18875. {"/literal/routes", StatusCode::NotFound_404},
  18876. {"/literal/rout", StatusCode::NotFound_404},
  18877. {"/abc", StatusCode::OK_200},
  18878. {"/a.c", StatusCode::OK_200},
  18879. };
  18880. for (const auto &x : cases) {
  18881. auto res = cli.Get(x.path);
  18882. ASSERT_TRUE(res) << x.path;
  18883. EXPECT_EQ(x.status, res->status) << x.path;
  18884. }
  18885. }
  18886. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18887. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18888. // from exhausting the stack, so it must only constrain routes that actually
  18889. // run a regular expression. A literal route is matched by comparison and
  18890. // stays usable at any length.
  18891. Server svr;
  18892. const std::string pattern =
  18893. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18894. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18895. res.set_content("hit", "text/plain");
  18896. });
  18897. auto port = svr.bind_to_any_port(HOST);
  18898. std::thread t([&]() { svr.listen_after_bind(); });
  18899. auto se = detail::scope_exit([&] {
  18900. svr.stop();
  18901. t.join();
  18902. ASSERT_FALSE(svr.is_running());
  18903. });
  18904. svr.wait_until_ready();
  18905. Client cli(HOST, port);
  18906. auto res = cli.Get(pattern);
  18907. ASSERT_TRUE(res);
  18908. EXPECT_EQ(StatusCode::OK_200, res->status);
  18909. }
  18910. TEST(ParseUrlTest, VariousPatterns) {
  18911. {
  18912. detail::UrlComponents uc;
  18913. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18914. EXPECT_EQ("http", uc.scheme);
  18915. EXPECT_EQ("example.com", uc.host);
  18916. EXPECT_EQ("8080", uc.port);
  18917. EXPECT_EQ("/path", uc.path);
  18918. EXPECT_EQ("?q=1", uc.query);
  18919. }
  18920. {
  18921. detail::UrlComponents uc;
  18922. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18923. EXPECT_EQ("https", uc.scheme);
  18924. EXPECT_EQ("example.com", uc.host);
  18925. EXPECT_TRUE(uc.port.empty());
  18926. EXPECT_EQ("/path", uc.path);
  18927. }
  18928. {
  18929. detail::UrlComponents uc;
  18930. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18931. EXPECT_EQ("::1", uc.host);
  18932. EXPECT_EQ("8080", uc.port);
  18933. EXPECT_EQ("/path", uc.path);
  18934. }
  18935. {
  18936. detail::UrlComponents uc;
  18937. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18938. }
  18939. {
  18940. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18941. // the path while the connection still targets the bracketed host.
  18942. detail::UrlComponents uc;
  18943. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18944. }
  18945. {
  18946. detail::UrlComponents uc;
  18947. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18948. }
  18949. {
  18950. detail::UrlComponents uc;
  18951. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18952. EXPECT_EQ("::1", uc.host);
  18953. EXPECT_TRUE(uc.port.empty());
  18954. EXPECT_EQ("/path", uc.path);
  18955. }
  18956. {
  18957. detail::UrlComponents uc;
  18958. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18959. EXPECT_TRUE(uc.scheme.empty());
  18960. EXPECT_EQ("example.com", uc.host);
  18961. EXPECT_EQ("/path", uc.path);
  18962. EXPECT_EQ("?q=1", uc.query);
  18963. }
  18964. {
  18965. detail::UrlComponents uc;
  18966. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18967. EXPECT_TRUE(uc.host.empty());
  18968. EXPECT_EQ("/path", uc.path);
  18969. EXPECT_EQ("?q=1", uc.query);
  18970. }
  18971. {
  18972. detail::UrlComponents uc;
  18973. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18974. EXPECT_EQ("example.com", uc.host);
  18975. EXPECT_EQ("8080", uc.port);
  18976. }
  18977. {
  18978. // Unix socket path — must not be parsed as host
  18979. detail::UrlComponents uc;
  18980. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18981. EXPECT_TRUE(uc.host.empty());
  18982. }
  18983. {
  18984. detail::UrlComponents uc;
  18985. ASSERT_TRUE(detail::parse_url("", uc));
  18986. EXPECT_TRUE(uc.host.empty());
  18987. EXPECT_TRUE(uc.path.empty());
  18988. }
  18989. {
  18990. detail::UrlComponents uc;
  18991. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  18992. EXPECT_EQ("http", uc.scheme);
  18993. }
  18994. {
  18995. detail::UrlComponents uc;
  18996. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18997. }
  18998. {
  18999. // Accepted by parse_url; callers restrict to http/https
  19000. detail::UrlComponents uc;
  19001. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  19002. EXPECT_EQ("ftp", uc.scheme);
  19003. }
  19004. {
  19005. detail::UrlComponents uc;
  19006. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  19007. }
  19008. {
  19009. detail::UrlComponents uc;
  19010. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  19011. }
  19012. }
  19013. TEST(ParseUrlTest, FragmentHandling) {
  19014. {
  19015. detail::UrlComponents uc;
  19016. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  19017. EXPECT_EQ("/path", uc.path);
  19018. EXPECT_TRUE(uc.query.empty());
  19019. }
  19020. {
  19021. detail::UrlComponents uc;
  19022. ASSERT_TRUE(detail::parse_url("#frag", uc));
  19023. EXPECT_TRUE(uc.path.empty());
  19024. EXPECT_TRUE(uc.query.empty());
  19025. }
  19026. }
  19027. TEST(ParseUrlTest, UserinfoHandling) {
  19028. // userinfo, and a backslash some parsers take for '/', are rejected: such
  19029. // parsers would see evil.com as the host.
  19030. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  19031. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  19032. for (auto url : urls) {
  19033. detail::UrlComponents uc;
  19034. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  19035. }
  19036. }
  19037. TEST(ParseUrlTest, IPv6EdgeCases) {
  19038. {
  19039. detail::UrlComponents uc;
  19040. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  19041. EXPECT_TRUE(uc.scheme.empty());
  19042. EXPECT_EQ("::1", uc.host);
  19043. EXPECT_EQ("8080", uc.port);
  19044. }
  19045. {
  19046. // Zone ID '%25' is not in [a-fA-F0-9:]
  19047. detail::UrlComponents uc;
  19048. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  19049. }
  19050. }
  19051. TEST(ParseUrlTest, SchemeEdgeCases) {
  19052. {
  19053. detail::UrlComponents uc;
  19054. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  19055. }
  19056. {
  19057. detail::UrlComponents uc;
  19058. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  19059. }
  19060. {
  19061. detail::UrlComponents uc;
  19062. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  19063. }
  19064. {
  19065. detail::UrlComponents uc;
  19066. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  19067. EXPECT_EQ("https", uc.scheme);
  19068. }
  19069. {
  19070. detail::UrlComponents uc;
  19071. ASSERT_TRUE(detail::parse_url("/path?next=https://example.com/", uc));
  19072. EXPECT_TRUE(uc.scheme.empty());
  19073. EXPECT_TRUE(uc.host.empty());
  19074. EXPECT_EQ("/path", uc.path);
  19075. EXPECT_EQ("?next=https://example.com/", uc.query);
  19076. }
  19077. }
  19078. TEST(ParseUrlTest, PortEdgeCases) {
  19079. {
  19080. detail::UrlComponents uc;
  19081. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  19082. EXPECT_TRUE(uc.port.empty());
  19083. EXPECT_EQ("/path", uc.path);
  19084. }
  19085. {
  19086. // parse_url accepts any port string; validation is done by parse_port
  19087. detail::UrlComponents uc;
  19088. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  19089. EXPECT_EQ("abc", uc.port);
  19090. }
  19091. }
  19092. TEST(ParseUrlTest, WebSocketPatterns) {
  19093. {
  19094. detail::UrlComponents uc;
  19095. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  19096. EXPECT_EQ("ws", uc.scheme);
  19097. EXPECT_EQ("echo.example.com", uc.host);
  19098. EXPECT_EQ("8080", uc.port);
  19099. EXPECT_EQ("/ws", uc.path);
  19100. }
  19101. {
  19102. detail::UrlComponents uc;
  19103. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  19104. EXPECT_EQ("wss", uc.scheme);
  19105. EXPECT_EQ("echo.example.com", uc.host);
  19106. EXPECT_TRUE(uc.port.empty());
  19107. EXPECT_EQ("/ws", uc.path);
  19108. }
  19109. }
  19110. TEST(ParseUrlTest, QueryOnly) {
  19111. detail::UrlComponents uc;
  19112. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  19113. EXPECT_TRUE(uc.host.empty());
  19114. EXPECT_TRUE(uc.path.empty());
  19115. EXPECT_EQ("?q=1&r=2", uc.query);
  19116. }
  19117. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  19118. detail::UrlComponents uc;
  19119. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  19120. EXPECT_TRUE(uc.scheme.empty());
  19121. EXPECT_EQ("example.com", uc.host);
  19122. EXPECT_EQ("443", uc.port);
  19123. EXPECT_EQ("/path", uc.path);
  19124. }
  19125. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  19126. // If ipv6 regex working, regex match codepath is taken.
  19127. // else port will default to 80 in Client impl
  19128. int clientImplMagicPort = 80;
  19129. int port = 4321;
  19130. // above ports must be different to avoid false negative
  19131. EXPECT_NE(clientImplMagicPort, port);
  19132. std::string ipV6TestURL = "http://[ff06::c3]";
  19133. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  19134. CLIENT_PRIVATE_KEY_FILE);
  19135. EXPECT_EQ(cli.port(), port);
  19136. }
  19137. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  19138. auto file_path = "./www/dir/index.html";
  19139. auto dir_path = "./www/dir";
  19140. detail::FileStat stat_file(file_path);
  19141. EXPECT_TRUE(stat_file.is_file());
  19142. EXPECT_FALSE(stat_file.is_dir());
  19143. detail::FileStat stat_dir(dir_path);
  19144. EXPECT_FALSE(stat_dir.is_file());
  19145. EXPECT_TRUE(stat_dir.is_dir());
  19146. }
  19147. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  19148. // IPv4 with default HTTP port (80)
  19149. EXPECT_EQ("example.com",
  19150. detail::make_host_and_port_string("example.com", 80, false));
  19151. // IPv4 with default HTTPS port (443)
  19152. EXPECT_EQ("example.com",
  19153. detail::make_host_and_port_string("example.com", 443, true));
  19154. // IPv4 with non-default HTTP port
  19155. EXPECT_EQ("example.com:8080",
  19156. detail::make_host_and_port_string("example.com", 8080, false));
  19157. // IPv4 with non-default HTTPS port
  19158. EXPECT_EQ("example.com:8443",
  19159. detail::make_host_and_port_string("example.com", 8443, true));
  19160. // IPv6 with default HTTP port (80)
  19161. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  19162. // IPv6 with default HTTPS port (443)
  19163. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  19164. // IPv6 with non-default HTTP port
  19165. EXPECT_EQ("[::1]:8080",
  19166. detail::make_host_and_port_string("::1", 8080, false));
  19167. // IPv6 with non-default HTTPS port
  19168. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  19169. // IPv6 full address with default port
  19170. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  19171. detail::make_host_and_port_string(
  19172. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  19173. // IPv6 full address with non-default port
  19174. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  19175. detail::make_host_and_port_string(
  19176. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  19177. // IPv6 localhost with non-default port
  19178. EXPECT_EQ("[::1]:3000",
  19179. detail::make_host_and_port_string("::1", 3000, false));
  19180. // IPv6 with zone ID (link-local address) with default port
  19181. EXPECT_EQ("[fe80::1%eth0]",
  19182. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  19183. // IPv6 with zone ID (link-local address) with non-default port
  19184. EXPECT_EQ("[fe80::1%eth0]:8080",
  19185. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  19186. // Edge case: Port 443 with is_ssl=false (should add port)
  19187. EXPECT_EQ("example.com:443",
  19188. detail::make_host_and_port_string("example.com", 443, false));
  19189. // Edge case: Port 80 with is_ssl=true (should add port)
  19190. EXPECT_EQ("example.com:80",
  19191. detail::make_host_and_port_string("example.com", 80, true));
  19192. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  19193. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  19194. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  19195. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  19196. // Security fix: Already bracketed IPv6 should not get double brackets
  19197. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  19198. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  19199. EXPECT_EQ("[::1]:8080",
  19200. detail::make_host_and_port_string("[::1]", 8080, false));
  19201. EXPECT_EQ("[2001:db8::1]:8080",
  19202. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  19203. EXPECT_EQ("[fe80::1%eth0]",
  19204. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  19205. EXPECT_EQ("[fe80::1%eth0]:8080",
  19206. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  19207. // Edge case: Empty host (should return as-is)
  19208. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  19209. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  19210. // This is a known limitation but shouldn't crash
  19211. EXPECT_EQ("[host:name]",
  19212. detail::make_host_and_port_string("host:name", 80, false));
  19213. // Port number edge cases (no validation, but should not crash)
  19214. EXPECT_EQ("example.com:0",
  19215. detail::make_host_and_port_string("example.com", 0, false));
  19216. EXPECT_EQ("example.com:-1",
  19217. detail::make_host_and_port_string("example.com", -1, false));
  19218. EXPECT_EQ("example.com:65535",
  19219. detail::make_host_and_port_string("example.com", 65535, false));
  19220. EXPECT_EQ("example.com:65536",
  19221. detail::make_host_and_port_string("example.com", 65536, false));
  19222. }
  19223. namespace httplib {
  19224. namespace detail {
  19225. std::string
  19226. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  19227. const std::string &host, int port);
  19228. } // namespace detail
  19229. } // namespace httplib
  19230. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  19231. std::map<std::string, std::string> addr_map = {
  19232. {"ipv4.example", "192.0.2.10"},
  19233. {"ipv6.example", "2001:db8::1"},
  19234. {"name.example", "internal.example.lan"},
  19235. {"empty.example", ""}};
  19236. EXPECT_EQ("192.0.2.10:443",
  19237. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  19238. EXPECT_EQ("[2001:db8::1]:443",
  19239. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  19240. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  19241. addr_map, "name.example", 8443));
  19242. // An empty or absent mapping keeps the hostname as the target
  19243. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  19244. addr_map, "empty.example", 443));
  19245. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  19246. addr_map, "other.example", 443));
  19247. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  19248. }
  19249. #ifdef CPPHTTPLIB_SSL_ENABLED
  19250. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  19251. httplib::SSLClient cli("roblox.com", 443);
  19252. cli.set_follow_location(true);
  19253. auto res = cli.Get("/");
  19254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19255. EXPECT_EQ(StatusCode::OK_200, res->status);
  19256. }
  19257. #endif
  19258. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  19259. Server svr;
  19260. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19261. EXPECT_EQ(res.status, 400);
  19262. });
  19263. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19264. auto se = detail::scope_exit([&] {
  19265. svr.stop();
  19266. thread.join();
  19267. ASSERT_FALSE(svr.is_running());
  19268. });
  19269. svr.wait_until_ready();
  19270. Client cli(HOST, PORT);
  19271. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  19272. }
  19273. TEST(InvalidHeaderCharsTest, is_field_name) {
  19274. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  19275. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  19276. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  19277. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  19278. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  19279. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  19280. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  19281. EXPECT_FALSE(detail::fields::is_field_name(""));
  19282. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  19283. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  19284. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  19285. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  19286. }
  19287. TEST(InvalidHeaderCharsTest, is_field_value) {
  19288. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19289. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19290. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19291. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19292. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19293. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19294. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19295. EXPECT_TRUE(detail::fields::is_field_value(""));
  19296. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19297. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19298. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19299. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19300. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19301. }
  19302. TEST(InvalidHeaderCharsTest, OnServer) {
  19303. Server svr;
  19304. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19305. std::string header = "Not Set";
  19306. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19307. res.set_header(header, "value");
  19308. res.set_content("Page Content Page Content", "text/plain");
  19309. });
  19310. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19311. std::string header = "Not Set";
  19312. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19313. res.set_header("X-Test", header);
  19314. res.set_content("Page Content Page Content", "text/plain");
  19315. });
  19316. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19317. auto se = detail::scope_exit([&] {
  19318. svr.stop();
  19319. thread.join();
  19320. ASSERT_FALSE(svr.is_running());
  19321. });
  19322. svr.wait_until_ready();
  19323. Client cli(HOST, PORT);
  19324. {
  19325. auto res = cli.Get(
  19326. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19328. EXPECT_EQ("Page Content Page Content", res->body);
  19329. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19330. }
  19331. {
  19332. auto res = cli.Get(
  19333. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19335. EXPECT_EQ("Page Content Page Content", res->body);
  19336. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19337. }
  19338. }
  19339. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19340. auto handled = false;
  19341. Server svr;
  19342. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19343. thread t = thread([&] { svr.listen(HOST, PORT); });
  19344. auto se = detail::scope_exit([&] {
  19345. svr.stop();
  19346. t.join();
  19347. ASSERT_FALSE(svr.is_running());
  19348. ASSERT_FALSE(handled);
  19349. });
  19350. svr.wait_until_ready();
  19351. auto req = "POST /test HTTP/1.1\r\n"
  19352. "Content-Length: x\r\n"
  19353. "\r\n";
  19354. std::string response;
  19355. ASSERT_TRUE(send_request(1, req, &response));
  19356. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19357. response.substr(0, response.find("\r\n")));
  19358. }
  19359. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19360. // case-insensitive, and a server that receives a 100-continue expectation in
  19361. // an HTTP/1.0 request MUST ignore it.
  19362. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19363. std::string response;
  19364. ASSERT_TRUE(send_request(1, req, &response, port));
  19365. *got_100 = response.find("100 Continue") != std::string::npos;
  19366. }
  19367. class ExpectTokenTest : public ::testing::Test {
  19368. protected:
  19369. void SetUp() override {
  19370. svr_.Post("/p", [](const Request &, Response &res) {
  19371. res.set_content("ok", "text/plain");
  19372. });
  19373. port_ = svr_.bind_to_any_port(HOST);
  19374. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19375. svr_.wait_until_ready();
  19376. }
  19377. void TearDown() override {
  19378. svr_.stop();
  19379. if (thread_.joinable()) { thread_.join(); }
  19380. }
  19381. std::string request(const char *version, const char *expect_value) const {
  19382. return std::string("POST /p ") + version +
  19383. "\r\n"
  19384. "Host: localhost\r\n"
  19385. "Content-Length: 2\r\n"
  19386. "Connection: close\r\n"
  19387. "Expect: " +
  19388. expect_value +
  19389. "\r\n"
  19390. "\r\n"
  19391. "hi";
  19392. }
  19393. Server svr_;
  19394. int port_ = 0;
  19395. thread thread_;
  19396. };
  19397. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19398. bool got_100 = false;
  19399. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19400. EXPECT_TRUE(got_100);
  19401. }
  19402. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19403. bool got_100 = true;
  19404. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19405. EXPECT_FALSE(got_100);
  19406. }
  19407. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19408. bool got_100 = false;
  19409. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19410. EXPECT_TRUE(got_100);
  19411. }
  19412. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19413. bool got_100 = false;
  19414. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19415. EXPECT_TRUE(got_100);
  19416. }
  19417. // `100 Continue` is sent only when the server starts reading the body, so a
  19418. // request rejected before that never invites the client to send it. The
  19419. // requests below carry the expectation but withhold the body, as a client
  19420. // waiting for `100 Continue` would.
  19421. // A POST that expects `100 Continue` and withholds its two-byte body.
  19422. static std::string expect_headers_only(const std::string &path) {
  19423. return "POST " + path +
  19424. " HTTP/1.1\r\n"
  19425. "Host: localhost\r\n"
  19426. "Content-Length: 2\r\n"
  19427. "Expect: 100-continue\r\n"
  19428. "\r\n";
  19429. }
  19430. class ExpectLazyContinueTest : public ::testing::Test {
  19431. protected:
  19432. void SetUp() override {
  19433. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19434. if (req.path == "/pre-routing") {
  19435. res.status = StatusCode::Unauthorized_401;
  19436. return Server::HandlerResponse::Handled;
  19437. }
  19438. return Server::HandlerResponse::Unhandled;
  19439. });
  19440. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19441. if (req.matched_route == "/pre-request") {
  19442. res.status = StatusCode::Forbidden_403;
  19443. return Server::HandlerResponse::Handled;
  19444. }
  19445. return Server::HandlerResponse::Unhandled;
  19446. });
  19447. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19448. res.set_content("ok", "text/plain");
  19449. });
  19450. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19451. res.set_content("ok", "text/plain");
  19452. });
  19453. svr_.Post("/reader-used", [](const Request &, Response &res,
  19454. const ContentReader &content_reader) {
  19455. std::string body;
  19456. content_reader([&](const char *data, size_t len) {
  19457. body.append(data, len);
  19458. return true;
  19459. });
  19460. res.set_content(body, "text/plain");
  19461. });
  19462. svr_.Post("/reader-unused",
  19463. [](const Request &, Response &res, const ContentReader &) {
  19464. res.set_content("ignored", "text/plain");
  19465. });
  19466. port_ = svr_.bind_to_any_port(HOST);
  19467. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19468. svr_.wait_until_ready();
  19469. }
  19470. void TearDown() override {
  19471. svr_.stop();
  19472. if (thread_.joinable()) { thread_.join(); }
  19473. }
  19474. // Sends `req` and reads until the server closes the connection. Returns
  19475. // false if the read had to wait for the client-side timeout instead.
  19476. bool send_until_closed(const std::string &req, std::string *resp) const {
  19477. auto start = std::chrono::steady_clock::now();
  19478. if (!send_request(3, req, resp, port_)) { return false; }
  19479. auto elapsed = std::chrono::steady_clock::now() - start;
  19480. return elapsed < std::chrono::seconds(2);
  19481. }
  19482. // The final response comes without `100 Continue`, and the server closes
  19483. // the connection since the body may or may not follow.
  19484. void expect_final_without_interim(const std::string &path,
  19485. const char *status_line) const {
  19486. std::string resp;
  19487. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19488. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19489. EXPECT_EQ(0u, resp.find(status_line));
  19490. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19491. }
  19492. Server svr_;
  19493. int port_ = 0;
  19494. thread thread_;
  19495. };
  19496. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19497. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19498. }
  19499. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19500. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19501. }
  19502. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19503. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19504. }
  19505. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19506. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19507. }
  19508. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19509. // The body follows once `100 Continue` has had time to arrive.
  19510. auto req = expect_headers_only("/reader-used");
  19511. req.insert(req.size() - 2, "Connection: close\r\n");
  19512. std::string resp;
  19513. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19514. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19515. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19516. EXPECT_NE(std::string::npos, resp.find("hi"));
  19517. }
  19518. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19519. // Large enough for the client to add `Expect: 100-continue` itself.
  19520. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19521. std::atomic<bool> body_sent{false};
  19522. Client cli(HOST, port_);
  19523. auto res = cli.Post(
  19524. "/pre-request", length,
  19525. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19526. body_sent = true;
  19527. std::string chunk(len, 'x');
  19528. sink.write(chunk.data(), chunk.size());
  19529. return true;
  19530. },
  19531. "application/octet-stream");
  19532. ASSERT_TRUE(res);
  19533. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19534. EXPECT_FALSE(body_sent);
  19535. }
  19536. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19537. Server svr;
  19538. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19539. return StatusCode::ExpectationFailed_417;
  19540. });
  19541. svr.Post("/p", [](const Request &, Response &res) {
  19542. res.set_content("ok", "text/plain");
  19543. });
  19544. auto port = svr.bind_to_any_port(HOST);
  19545. thread t = thread([&] { svr.listen_after_bind(); });
  19546. auto se = detail::scope_exit([&] {
  19547. svr.stop();
  19548. t.join();
  19549. });
  19550. svr.wait_until_ready();
  19551. std::string resp;
  19552. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19553. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19554. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19555. // Exactly one response: the route handler must not run after the 417.
  19556. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19557. }
  19558. #ifndef _WIN32
  19559. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19560. static constexpr char reject[] = "Unauthorized";
  19561. static constexpr char accept[] = "Upload accepted";
  19562. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19563. Server svr;
  19564. svr.set_expect_100_continue_handler(
  19565. [](const Request & /*req*/, Response &res) {
  19566. res.status = StatusCode::Unauthorized_401;
  19567. res.set_content(reject, "text/plain");
  19568. return res.status;
  19569. });
  19570. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19571. res.set_content(accept, "text/plain");
  19572. });
  19573. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19574. auto se = detail::scope_exit([&] {
  19575. svr.stop();
  19576. thread.join();
  19577. ASSERT_FALSE(svr.is_running());
  19578. });
  19579. svr.wait_until_ready();
  19580. {
  19581. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19582. curl_easy_init(), &curl_easy_cleanup};
  19583. ASSERT_NE(curl, nullptr);
  19584. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19585. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19586. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19587. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19588. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19589. &curl_slist_free_all};
  19590. ASSERT_NE(list, nullptr);
  19591. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19592. struct read_data {
  19593. uint64_t read_size;
  19594. uint64_t total_size;
  19595. } data = {0, total_size};
  19596. using read_callback_t =
  19597. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19598. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19599. void *userdata) -> size_t {
  19600. read_data *d = (read_data *)userdata;
  19601. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19602. std::fill_n(ptr, size * nmemb, 'A');
  19603. d->read_size += size * nmemb;
  19604. return size * nmemb;
  19605. };
  19606. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19607. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19608. std::vector<char> buffer;
  19609. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19610. using write_callback_t =
  19611. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19612. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19613. void *userdata) -> size_t {
  19614. std::vector<char> *buf = (std::vector<char> *)userdata;
  19615. buf->reserve(buf->size() + size * nmemb + 1);
  19616. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19617. return size * nmemb;
  19618. };
  19619. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19620. {
  19621. const auto res = curl_easy_perform(curl.get());
  19622. ASSERT_EQ(res, CURLE_OK);
  19623. }
  19624. {
  19625. auto response_code = long{};
  19626. const auto res =
  19627. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19628. ASSERT_EQ(res, CURLE_OK);
  19629. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19630. }
  19631. {
  19632. auto dl = curl_off_t{};
  19633. const auto res =
  19634. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19635. ASSERT_EQ(res, CURLE_OK);
  19636. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19637. }
  19638. {
  19639. buffer.push_back('\0');
  19640. ASSERT_STRCASEEQ(buffer.data(), reject);
  19641. }
  19642. }
  19643. }
  19644. #endif
  19645. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19646. // Regression test for #2458.
  19647. //
  19648. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19649. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19650. // ticket can make the client socket spuriously readable during the
  19651. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19652. // the client withholds the body and then blocks reading a response that never
  19653. // comes, failing with `Failed to read connection`.
  19654. //
  19655. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19656. // within the timeout. This raw OpenSSL server deliberately never sends
  19657. // `100 Continue`; the client must still deliver the body and receive 200.
  19658. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19659. signal(SIGPIPE, SIG_IGN);
  19660. const auto port = PORT + 4;
  19661. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19662. ASSERT_NE(srv, INVALID_SOCKET);
  19663. int opt = 1;
  19664. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19665. sockaddr_in addr{};
  19666. addr.sin_family = AF_INET;
  19667. addr.sin_port = htons(static_cast<uint16_t>(port));
  19668. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19669. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19670. ASSERT_EQ(0, ::listen(srv, 1));
  19671. std::atomic<size_t> server_body_bytes{0};
  19672. auto server_thread = std::thread([&] {
  19673. sockaddr_in cli_addr{};
  19674. socklen_t cli_len = sizeof(cli_addr);
  19675. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19676. if (cli == INVALID_SOCKET) { return; }
  19677. // Bound the lifetime of the server side so a buggy client (which never
  19678. // sends the body) cannot make this thread block forever on join.
  19679. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19680. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19681. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19682. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19683. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19684. SSL *ssl = SSL_new(ctx);
  19685. SSL_set_fd(ssl, static_cast<int>(cli));
  19686. if (SSL_accept(ssl) > 0) {
  19687. // Read the request headers. Reading here also flushes the TLS 1.3
  19688. // session tickets to the client. Deliberately do NOT send
  19689. // `100 Continue`.
  19690. std::string buf;
  19691. char tmp[1024];
  19692. while (buf.find("\r\n\r\n") == std::string::npos) {
  19693. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19694. if (n <= 0) { break; }
  19695. buf.append(tmp, static_cast<size_t>(n));
  19696. }
  19697. // A correct client sends the body now; count what arrives.
  19698. auto pos = buf.find("\r\n\r\n");
  19699. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19700. while (body < 4096) {
  19701. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19702. if (n <= 0) { break; }
  19703. body += static_cast<size_t>(n);
  19704. }
  19705. server_body_bytes = body;
  19706. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19707. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19708. SSL_shutdown(ssl);
  19709. }
  19710. SSL_free(ssl);
  19711. detail::close_socket(cli);
  19712. SSL_CTX_free(ctx);
  19713. });
  19714. auto se = detail::scope_exit([&] {
  19715. server_thread.join();
  19716. detail::close_socket(srv);
  19717. });
  19718. SSLClient cli("127.0.0.1", port);
  19719. cli.enable_server_certificate_verification(false);
  19720. cli.set_connection_timeout(5, 0);
  19721. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19722. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19723. std::string body(4096, 'A');
  19724. auto res = cli.Put("/api/test", body, "application/json");
  19725. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19726. EXPECT_EQ(StatusCode::OK_200, res->status);
  19727. EXPECT_EQ(body.size(), server_body_bytes.load());
  19728. }
  19729. #endif
  19730. template <typename S, typename C>
  19731. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19732. svr.Get("/stream", [&](const Request &, Response &res) {
  19733. auto data = new std::string("01234567890123456789");
  19734. res.set_content_provider(
  19735. data->size(), "text/plain",
  19736. [&, data](size_t offset, size_t length, DataSink &sink) {
  19737. const size_t DATA_CHUNK_SIZE = 4;
  19738. const auto &d = *data;
  19739. std::this_thread::sleep_for(std::chrono::seconds(1));
  19740. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19741. return true;
  19742. },
  19743. [data](bool success) {
  19744. EXPECT_FALSE(success);
  19745. delete data;
  19746. });
  19747. });
  19748. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19749. auto i = new size_t(0);
  19750. res.set_content_provider(
  19751. "text/plain",
  19752. [i](size_t, DataSink &sink) {
  19753. if (*i < 5) {
  19754. std::this_thread::sleep_for(std::chrono::seconds(1));
  19755. sink.write("abcd", 4);
  19756. (*i)++;
  19757. } else {
  19758. sink.done();
  19759. }
  19760. return true;
  19761. },
  19762. [i](bool success) {
  19763. EXPECT_FALSE(success);
  19764. delete i;
  19765. });
  19766. });
  19767. svr.Get("/chunked", [&](const Request &, Response &res) {
  19768. auto i = new size_t(0);
  19769. res.set_chunked_content_provider(
  19770. "text/plain",
  19771. [i](size_t, DataSink &sink) {
  19772. if (*i < 5) {
  19773. std::this_thread::sleep_for(std::chrono::seconds(1));
  19774. sink.os << "abcd";
  19775. (*i)++;
  19776. } else {
  19777. sink.done();
  19778. }
  19779. return true;
  19780. },
  19781. [i](bool success) {
  19782. EXPECT_FALSE(success);
  19783. delete i;
  19784. });
  19785. });
  19786. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19787. auto se = detail::scope_exit([&] {
  19788. svr.stop();
  19789. listen_thread.join();
  19790. ASSERT_FALSE(svr.is_running());
  19791. });
  19792. svr.wait_until_ready();
  19793. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19794. {
  19795. auto start = std::chrono::steady_clock::now();
  19796. auto res = cli.Get("/stream");
  19797. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19798. std::chrono::steady_clock::now() - start)
  19799. .count();
  19800. ASSERT_FALSE(res);
  19801. EXPECT_EQ(Error::Read, res.error());
  19802. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19803. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19804. }
  19805. {
  19806. auto start = std::chrono::steady_clock::now();
  19807. auto res = cli.Get("/stream_without_length");
  19808. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19809. std::chrono::steady_clock::now() - start)
  19810. .count();
  19811. ASSERT_FALSE(res);
  19812. EXPECT_EQ(Error::Read, res.error());
  19813. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19814. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19815. }
  19816. {
  19817. auto start = std::chrono::steady_clock::now();
  19818. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19819. EXPECT_EQ("abcd", string(data, data_length));
  19820. return true;
  19821. });
  19822. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19823. std::chrono::steady_clock::now() - start)
  19824. .count();
  19825. ASSERT_FALSE(res);
  19826. EXPECT_EQ(Error::Read, res.error());
  19827. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19828. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19829. }
  19830. }
  19831. TEST(MaxTimeoutTest, ContentStream) {
  19832. time_t timeout = 2000;
  19833. time_t threshold = 200;
  19834. Server svr;
  19835. Client cli("localhost", PORT);
  19836. max_timeout_test(svr, cli, timeout, threshold);
  19837. }
  19838. #ifdef CPPHTTPLIB_SSL_ENABLED
  19839. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19840. time_t timeout = 2000;
  19841. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19842. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19843. SSLClient cli("localhost", PORT);
  19844. cli.enable_server_certificate_verification(false);
  19845. max_timeout_test(svr, cli, timeout, threshold);
  19846. }
  19847. #endif
  19848. class EventDispatcher {
  19849. public:
  19850. EventDispatcher() {}
  19851. bool wait_event(DataSink *sink) {
  19852. unique_lock<mutex> lk(m_);
  19853. int id = id_;
  19854. // Wait with timeout to prevent hanging if client disconnects
  19855. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19856. [&] { return cid_ == id; })) {
  19857. return false; // Timeout occurred
  19858. }
  19859. sink->write(message_.data(), message_.size());
  19860. return true;
  19861. }
  19862. void send_event(const string &message) {
  19863. lock_guard<mutex> lk(m_);
  19864. cid_ = id_++;
  19865. message_ = message;
  19866. cv_.notify_all();
  19867. }
  19868. private:
  19869. mutex m_;
  19870. condition_variable cv_;
  19871. atomic_int id_{0};
  19872. atomic_int cid_{-1};
  19873. string message_;
  19874. };
  19875. TEST(ClientInThreadTest, Issue2068) {
  19876. EventDispatcher ed;
  19877. Server svr;
  19878. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19879. res.set_chunked_content_provider("text/event-stream",
  19880. [&](size_t /*offset*/, DataSink &sink) {
  19881. return ed.wait_event(&sink);
  19882. });
  19883. });
  19884. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19885. svr.wait_until_ready();
  19886. thread event_thread([&] {
  19887. int id = 0;
  19888. while (svr.is_running()) {
  19889. this_thread::sleep_for(chrono::milliseconds(500));
  19890. std::stringstream ss;
  19891. ss << "data: " << id << "\n\n";
  19892. ed.send_event(ss.str());
  19893. id++;
  19894. }
  19895. });
  19896. auto se = detail::scope_exit([&] {
  19897. svr.stop();
  19898. listen_thread.join();
  19899. event_thread.join();
  19900. ASSERT_FALSE(svr.is_running());
  19901. });
  19902. {
  19903. auto client = detail::make_unique<Client>(HOST, PORT);
  19904. client->set_read_timeout(std::chrono::minutes(10));
  19905. std::atomic<bool> stop{false};
  19906. std::thread t([&] {
  19907. client->Get("/event1",
  19908. [&](const char *, size_t) -> bool { return !stop; });
  19909. });
  19910. std::this_thread::sleep_for(std::chrono::seconds(2));
  19911. stop = true;
  19912. client->stop();
  19913. t.join();
  19914. // Reset client after thread has finished
  19915. client.reset();
  19916. }
  19917. }
  19918. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19919. auto handled = false;
  19920. Server svr;
  19921. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19922. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19923. auto se = detail::scope_exit([&] {
  19924. svr.stop();
  19925. t.join();
  19926. ASSERT_FALSE(svr.is_running());
  19927. ASSERT_FALSE(handled);
  19928. });
  19929. svr.wait_until_ready();
  19930. // Two Content-Length headers with different values — must be rejected
  19931. auto req = "POST /test HTTP/1.1\r\n"
  19932. "Content-Length: 5\r\n"
  19933. "Content-Length: 10\r\n"
  19934. "\r\n"
  19935. "hello";
  19936. std::string response;
  19937. ASSERT_TRUE(send_request(1, req, &response));
  19938. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19939. response.substr(0, response.find("\r\n")));
  19940. }
  19941. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19942. auto handled = false;
  19943. Server svr;
  19944. svr.Post("/test", [&](const Request &, Response &res) {
  19945. handled = true;
  19946. res.set_content("ok", "text/plain");
  19947. });
  19948. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19949. auto se = detail::scope_exit([&] {
  19950. svr.stop();
  19951. t.join();
  19952. ASSERT_FALSE(svr.is_running());
  19953. ASSERT_TRUE(handled);
  19954. });
  19955. svr.wait_until_ready();
  19956. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19957. auto req = "POST /test HTTP/1.1\r\n"
  19958. "Host: localhost\r\n"
  19959. "Content-Length: 5\r\n"
  19960. "Content-Length: 5\r\n"
  19961. "\r\n"
  19962. "hello";
  19963. std::string response;
  19964. ASSERT_TRUE(send_request(1, req, &response));
  19965. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19966. }
  19967. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19968. Server svr;
  19969. svr.Get("/test", [](const Request &, Response &res) {
  19970. res.set_content("ok", "text/plain");
  19971. });
  19972. auto port = svr.bind_to_any_port(HOST);
  19973. thread t = thread([&] { svr.listen_after_bind(); });
  19974. auto se = detail::scope_exit([&] {
  19975. svr.stop();
  19976. t.join();
  19977. ASSERT_FALSE(svr.is_running());
  19978. });
  19979. svr.wait_until_ready();
  19980. auto status_line = [&](const std::string &host_lines) {
  19981. std::string res;
  19982. send_request(
  19983. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19984. &res, port);
  19985. return res.substr(0, res.find("\r\n"));
  19986. };
  19987. const char *accepted[] = {
  19988. "Host: localhost\r\n",
  19989. "Host: a.example:8080\r\n",
  19990. "Host: my_service\r\n",
  19991. "Host: [::1]:8080\r\n",
  19992. "Host: [fe80::1%25eth0]\r\n",
  19993. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19994. };
  19995. for (auto host_lines : accepted) {
  19996. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19997. }
  19998. const char *rejected[] = {
  19999. "Host: a.example\r\nHost: b.example\r\n",
  20000. "Host: a.example\r\nHost: a.example\r\n",
  20001. "Host: a@b.example\r\n",
  20002. "Host: a.example/b\r\n",
  20003. "Host: a.example\\b\r\n",
  20004. "Host: a.example?b\r\n",
  20005. "Host: a.example#b\r\n",
  20006. "Host: a.example b.example\r\n",
  20007. };
  20008. for (auto host_lines : rejected) {
  20009. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  20010. << host_lines;
  20011. }
  20012. }
  20013. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  20014. Server svr;
  20015. svr.Get("/", [](const Request &req, Response &res) {
  20016. EXPECT_EQ(2U, req.trailers.size());
  20017. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  20018. // Denied
  20019. EXPECT_FALSE(req.has_trailer("Content-Length"));
  20020. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  20021. // Accepted
  20022. EXPECT_TRUE(req.has_trailer("X-Hello"));
  20023. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  20024. EXPECT_TRUE(req.has_trailer("X-World"));
  20025. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  20026. res.set_content("ok", "text/plain");
  20027. });
  20028. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20029. auto se = detail::scope_exit([&] {
  20030. svr.stop();
  20031. t.join();
  20032. ASSERT_FALSE(svr.is_running());
  20033. });
  20034. svr.wait_until_ready();
  20035. const std::string req = "GET / HTTP/1.1\r\n"
  20036. "Transfer-Encoding: chunked\r\n"
  20037. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  20038. "\r\n"
  20039. "0\r\n"
  20040. "Content-Length: 10\r\n"
  20041. "Host: internal.local\r\n"
  20042. "Content-Type: malicious/content\r\n"
  20043. "Cookie: any\r\n"
  20044. "Set-Cookie: any\r\n"
  20045. "X-Forwarded-For: attacker.com\r\n"
  20046. "X-Real-Ip: 1.1.1.1\r\n"
  20047. "X-Hello: hello\r\n"
  20048. "X-World: world\r\n"
  20049. "\r\n";
  20050. std::string res;
  20051. ASSERT_TRUE(send_request(1, req, &res));
  20052. }
  20053. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  20054. // several field lines, and the combined value is what has to be parsed. A
  20055. // Trailer field split across lines therefore declares every name it lists;
  20056. // reading only the first line silently drops the trailers the later lines
  20057. // declare. The prohibited-trailer filter still applies to every line.
  20058. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  20059. Server svr;
  20060. size_t observed_trailer_count = 0;
  20061. std::string observed_hello;
  20062. std::string observed_world;
  20063. bool observed_content_length = true;
  20064. svr.Get("/", [&](const Request &req, Response &res) {
  20065. observed_trailer_count = req.trailers.size();
  20066. observed_hello = req.get_trailer_value("X-Hello");
  20067. observed_world = req.get_trailer_value("X-World");
  20068. observed_content_length = req.has_trailer("Content-Length");
  20069. res.set_content("ok", "text/plain");
  20070. });
  20071. auto port = svr.bind_to_any_port(HOST);
  20072. thread t = thread([&]() { svr.listen_after_bind(); });
  20073. auto se = detail::scope_exit([&] {
  20074. svr.stop();
  20075. t.join();
  20076. ASSERT_FALSE(svr.is_running());
  20077. });
  20078. svr.wait_until_ready();
  20079. const std::string req = "GET / HTTP/1.1\r\n"
  20080. "Host: localhost\r\n"
  20081. "Transfer-Encoding: chunked\r\n"
  20082. "Trailer: X-Hello\r\n"
  20083. "Trailer: X-World, Content-Length\r\n"
  20084. "\r\n"
  20085. "0\r\n"
  20086. "X-Hello: hello\r\n"
  20087. "X-World: world\r\n"
  20088. "Content-Length: 10\r\n"
  20089. "\r\n";
  20090. std::string res;
  20091. ASSERT_TRUE(send_request(1, req, &res, port));
  20092. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  20093. // Accepted: both field lines contribute to the declared set
  20094. EXPECT_EQ(2U, observed_trailer_count);
  20095. EXPECT_EQ(observed_hello, "hello");
  20096. EXPECT_EQ(observed_world, "world");
  20097. // Denied: a prohibited name stays prohibited on a later field line
  20098. EXPECT_FALSE(observed_content_length);
  20099. }
  20100. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  20101. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  20102. // unbounded run of fields that are never declared, because the counter would
  20103. // only advance for declared fields.
  20104. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  20105. Server svr;
  20106. bool handler_called = false;
  20107. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  20108. handler_called = true;
  20109. res.set_content("ok", "text/plain");
  20110. });
  20111. auto port = svr.bind_to_any_port(HOST);
  20112. thread t = thread([&]() { svr.listen_after_bind(); });
  20113. auto se = detail::scope_exit([&] {
  20114. svr.stop();
  20115. t.join();
  20116. ASSERT_FALSE(svr.is_running());
  20117. });
  20118. svr.wait_until_ready();
  20119. // Declare nothing, then send far more undeclared trailer fields than the
  20120. // header-count limit. Parsing must stop and reject the request rather than
  20121. // read every line.
  20122. std::string req = "GET / HTTP/1.1\r\n"
  20123. "Transfer-Encoding: chunked\r\n"
  20124. "\r\n"
  20125. "0\r\n";
  20126. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  20127. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  20128. }
  20129. req += "\r\n";
  20130. std::string res;
  20131. ASSERT_TRUE(send_request(1, req, &res, port));
  20132. // The request is rejected before the handler runs.
  20133. EXPECT_FALSE(handler_called);
  20134. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  20135. }
  20136. // The set of declared trailer names is capped so a peer cannot grow it without
  20137. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  20138. // declared past the cap is not honored, even if the field is actually sent.
  20139. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  20140. Server svr;
  20141. // One name inside the cap and one past it, so the test tracks the cap rather
  20142. // than a fixed count.
  20143. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  20144. const std::string within_cap_name = "X-T-0";
  20145. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  20146. bool observed_within_cap = false;
  20147. bool observed_past_cap = false;
  20148. svr.Get("/", [&](const Request &req, Response &res) {
  20149. observed_within_cap = req.has_trailer(within_cap_name);
  20150. observed_past_cap = req.has_trailer(past_cap_name);
  20151. res.set_content("ok", "text/plain");
  20152. });
  20153. auto port = svr.bind_to_any_port(HOST);
  20154. thread t = thread([&]() { svr.listen_after_bind(); });
  20155. auto se = detail::scope_exit([&] {
  20156. svr.stop();
  20157. t.join();
  20158. ASSERT_FALSE(svr.is_running());
  20159. });
  20160. svr.wait_until_ready();
  20161. // Declare more trailer names than the cap in a single Trailer field, then
  20162. // actually send the first (within the cap) and the last (past it).
  20163. std::string trailer_decl = "Trailer: ";
  20164. for (int i = 0; i < declared_count; i++) {
  20165. if (i != 0) { trailer_decl += ", "; }
  20166. trailer_decl += "X-T-" + std::to_string(i);
  20167. }
  20168. trailer_decl += "\r\n";
  20169. const std::string req = "GET / HTTP/1.1\r\n"
  20170. "Host: localhost\r\n"
  20171. "Transfer-Encoding: chunked\r\n" +
  20172. trailer_decl +
  20173. "\r\n"
  20174. "0\r\n" +
  20175. within_cap_name + ": a\r\n" + past_cap_name +
  20176. ": b\r\n"
  20177. "\r\n";
  20178. std::string res;
  20179. ASSERT_TRUE(send_request(1, req, &res, port));
  20180. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  20181. // A name within the cap is honored; one declared past the cap is dropped.
  20182. EXPECT_TRUE(observed_within_cap);
  20183. EXPECT_FALSE(observed_past_cap);
  20184. }
  20185. // A direct client that is not listed in trusted_proxies must not be able to
  20186. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  20187. // the peer address on the actual TCP connection determines whether the
  20188. // header is honored.
  20189. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  20190. Server svr;
  20191. // Deliberately does NOT include the loopback address the test client
  20192. // actually connects from, so the direct connection is not a trusted proxy.
  20193. svr.set_trusted_proxies({"203.0.113.66"});
  20194. std::string observed_remote_addr;
  20195. svr.Get("/ip", [&](const Request &req, Response &res) {
  20196. observed_remote_addr = req.remote_addr;
  20197. res.set_content("ok", "text/plain");
  20198. });
  20199. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20200. auto se = detail::scope_exit([&] {
  20201. svr.stop();
  20202. t.join();
  20203. ASSERT_FALSE(svr.is_running());
  20204. });
  20205. svr.wait_until_ready();
  20206. Client cli(HOST, PORT);
  20207. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  20208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20209. EXPECT_EQ(StatusCode::OK_200, res->status);
  20210. // The connecting peer is not a trusted proxy, so the spoofed header must be
  20211. // ignored entirely and the real connection-level address retained.
  20212. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20213. observed_remote_addr == "127.0.0.1");
  20214. }
  20215. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  20216. Server svr;
  20217. std::string observed_remote_addr;
  20218. std::string observed_xff;
  20219. svr.Get("/ip", [&](const Request &req, Response &res) {
  20220. observed_remote_addr = req.remote_addr;
  20221. observed_xff = req.get_header_value("X-Forwarded-For");
  20222. res.set_content("ok", "text/plain");
  20223. });
  20224. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20225. auto se = detail::scope_exit([&] {
  20226. svr.stop();
  20227. t.join();
  20228. ASSERT_FALSE(svr.is_running());
  20229. });
  20230. svr.wait_until_ready();
  20231. Client cli(HOST, PORT);
  20232. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  20233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20234. EXPECT_EQ(StatusCode::OK_200, res->status);
  20235. EXPECT_EQ(observed_xff, "203.0.113.66");
  20236. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20237. observed_remote_addr == "127.0.0.1");
  20238. }
  20239. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  20240. Server svr;
  20241. svr.set_trusted_proxies({"203.0.113.66"});
  20242. std::string observed_remote_addr;
  20243. std::string observed_xff;
  20244. svr.Get("/ip", [&](const Request &req, Response &res) {
  20245. observed_remote_addr = req.remote_addr;
  20246. observed_xff = req.get_header_value("X-Forwarded-For");
  20247. res.set_content("ok", "text/plain");
  20248. });
  20249. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20250. auto se = detail::scope_exit([&] {
  20251. svr.stop();
  20252. t.join();
  20253. ASSERT_FALSE(svr.is_running());
  20254. });
  20255. svr.wait_until_ready();
  20256. Client cli(HOST, PORT);
  20257. auto res = cli.Get("/ip");
  20258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20259. EXPECT_EQ(StatusCode::OK_200, res->status);
  20260. EXPECT_EQ(observed_xff, "");
  20261. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20262. observed_remote_addr == "127.0.0.1");
  20263. }
  20264. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  20265. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  20266. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  20267. Server svr;
  20268. svr.set_trusted_proxies({"127.0.0.1"});
  20269. svr.Get("/ip", [](const Request &req, Response &res) {
  20270. res.set_content(req.remote_addr, "text/plain");
  20271. });
  20272. auto port = svr.bind_to_any_port("::");
  20273. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  20274. thread t = thread([&] { svr.listen_after_bind(); });
  20275. auto se = detail::scope_exit([&] {
  20276. svr.stop();
  20277. t.join();
  20278. ASSERT_FALSE(svr.is_running());
  20279. });
  20280. svr.wait_until_ready();
  20281. Client cli("127.0.0.1", port);
  20282. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  20283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20284. EXPECT_EQ("198.51.100.23", res->body);
  20285. }
  20286. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  20287. Server svr;
  20288. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20289. svr.Get("/ip", [](const Request &req, Response &res) {
  20290. res.set_content(req.remote_addr, "text/plain");
  20291. });
  20292. auto port = svr.bind_to_any_port(HOST);
  20293. ASSERT_GT(port, 0);
  20294. thread t = thread([&] { svr.listen_after_bind(); });
  20295. auto se = detail::scope_exit([&] {
  20296. svr.stop();
  20297. t.join();
  20298. ASSERT_FALSE(svr.is_running());
  20299. });
  20300. svr.wait_until_ready();
  20301. Client cli(HOST, port);
  20302. auto res = cli.Get(
  20303. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20305. EXPECT_EQ("198.51.100.23", res->body);
  20306. }
  20307. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20308. Server svr;
  20309. // Include the loopback address the test client actually connects from, so
  20310. // the direct connection itself is recognized as the trusted proxy hop.
  20311. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20312. std::string observed_remote_addr;
  20313. std::string observed_xff;
  20314. svr.Get("/ip", [&](const Request &req, Response &res) {
  20315. observed_remote_addr = req.remote_addr;
  20316. observed_xff = req.get_header_value("X-Forwarded-For");
  20317. res.set_content("ok", "text/plain");
  20318. });
  20319. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20320. auto se = detail::scope_exit([&] {
  20321. svr.stop();
  20322. t.join();
  20323. ASSERT_FALSE(svr.is_running());
  20324. });
  20325. svr.wait_until_ready();
  20326. Client cli(HOST, PORT);
  20327. auto res = cli.Get(
  20328. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20330. EXPECT_EQ(StatusCode::OK_200, res->status);
  20331. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20332. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20333. }
  20334. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20335. Server svr;
  20336. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20337. std::string observed_remote_addr;
  20338. std::string observed_xff;
  20339. svr.Get("/ip", [&](const Request &req, Response &res) {
  20340. observed_remote_addr = req.remote_addr;
  20341. observed_xff = req.get_header_value("X-Forwarded-For");
  20342. res.set_content("ok", "text/plain");
  20343. });
  20344. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20345. auto se = detail::scope_exit([&] {
  20346. svr.stop();
  20347. t.join();
  20348. ASSERT_FALSE(svr.is_running());
  20349. });
  20350. svr.wait_until_ready();
  20351. Client cli(HOST, PORT);
  20352. auto res = cli.Get(
  20353. "/ip",
  20354. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20356. EXPECT_EQ(StatusCode::OK_200, res->status);
  20357. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20358. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20359. }
  20360. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20361. Server svr;
  20362. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20363. std::string observed_remote_addr;
  20364. std::string observed_xff;
  20365. svr.Get("/ip", [&](const Request &req, Response &res) {
  20366. observed_remote_addr = req.remote_addr;
  20367. observed_xff = req.get_header_value("X-Forwarded-For");
  20368. res.set_content("ok", "text/plain");
  20369. });
  20370. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20371. auto se = detail::scope_exit([&] {
  20372. svr.stop();
  20373. t.join();
  20374. ASSERT_FALSE(svr.is_running());
  20375. });
  20376. svr.wait_until_ready();
  20377. Client cli(HOST, PORT);
  20378. auto res = cli.Get(
  20379. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20381. EXPECT_EQ(StatusCode::OK_200, res->status);
  20382. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20383. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20384. // and must not be selected.
  20385. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20386. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20387. }
  20388. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20389. Server svr;
  20390. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20391. std::string observed_remote_addr;
  20392. svr.Get("/ip", [&](const Request &req, Response &res) {
  20393. observed_remote_addr = req.remote_addr;
  20394. res.set_content("ok", "text/plain");
  20395. });
  20396. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20397. auto se = detail::scope_exit([&] {
  20398. svr.stop();
  20399. t.join();
  20400. ASSERT_FALSE(svr.is_running());
  20401. });
  20402. svr.wait_until_ready();
  20403. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20404. // a forged address and the trusted proxy's own address; the forged value must
  20405. // not win over the address the trusted proxy actually recorded.
  20406. Client cli(HOST, PORT);
  20407. auto res = cli.Get(
  20408. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20410. EXPECT_EQ(StatusCode::OK_200, res->status);
  20411. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20412. }
  20413. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20414. Server svr;
  20415. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20416. std::string observed_remote_addr;
  20417. std::string observed_xff;
  20418. svr.Get("/ip", [&](const Request &req, Response &res) {
  20419. observed_remote_addr = req.remote_addr;
  20420. observed_xff = req.get_header_value("X-Forwarded-For");
  20421. res.set_content("ok", "text/plain");
  20422. });
  20423. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20424. auto se = detail::scope_exit([&] {
  20425. svr.stop();
  20426. t.join();
  20427. ASSERT_FALSE(svr.is_running());
  20428. });
  20429. svr.wait_until_ready();
  20430. Client cli(HOST, PORT);
  20431. auto res = cli.Get(
  20432. "/ip",
  20433. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20435. EXPECT_EQ(StatusCode::OK_200, res->status);
  20436. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20437. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20438. }
  20439. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20440. Server svr;
  20441. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20442. std::string observed_remote_addr;
  20443. std::string observed_xff;
  20444. svr.Get("/ip", [&](const Request &req, Response &res) {
  20445. observed_remote_addr = req.remote_addr;
  20446. observed_xff = req.get_header_value("X-Forwarded-For");
  20447. res.set_content("ok", "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 raw_req =
  20457. "GET /ip HTTP/1.1\r\n"
  20458. "Host: localhost\r\n"
  20459. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20460. "Connection: close\r\n"
  20461. "\r\n";
  20462. std::string out;
  20463. ASSERT_TRUE(send_request(5, raw_req, &out));
  20464. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20465. // Header parser trims surrounding whitespace of the header value
  20466. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20467. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20468. }
  20469. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20470. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20471. // their own X-Forwarded-For as a separate field line rather than extending the
  20472. // one the client sent, so every occurrence has to be taken into account.
  20473. // Reading only the first one hands back the address the client chose.
  20474. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20475. Server svr;
  20476. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20477. std::string observed_remote_addr;
  20478. size_t observed_xff_count = 0;
  20479. svr.Get("/ip", [&](const Request &req, Response &res) {
  20480. observed_remote_addr = req.remote_addr;
  20481. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20482. res.set_content("ok", "text/plain");
  20483. });
  20484. auto port = svr.bind_to_any_port(HOST);
  20485. thread t = thread([&]() { svr.listen_after_bind(); });
  20486. auto se = detail::scope_exit([&] {
  20487. svr.stop();
  20488. t.join();
  20489. ASSERT_FALSE(svr.is_running());
  20490. });
  20491. svr.wait_until_ready();
  20492. // The client supplies the first field line; the trusted proxy appends the
  20493. // address it observed as a second one.
  20494. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20495. "Host: localhost\r\n"
  20496. "X-Forwarded-For: 1.2.3.4\r\n"
  20497. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20498. "Connection: close\r\n"
  20499. "\r\n";
  20500. std::string out;
  20501. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20502. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20503. EXPECT_EQ(observed_xff_count, 2U);
  20504. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20505. // The same chain spread over one field line per hop derives the same client
  20506. // address, i.e. the split and the comma-joined representations agree.
  20507. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20508. "Host: localhost\r\n"
  20509. "X-Forwarded-For: 1.2.3.4\r\n"
  20510. "X-Forwarded-For: 198.51.100.23\r\n"
  20511. "X-Forwarded-For: 192.0.2.45\r\n"
  20512. "Connection: close\r\n"
  20513. "\r\n";
  20514. out.clear();
  20515. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20516. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20517. EXPECT_EQ(observed_xff_count, 3U);
  20518. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20519. }
  20520. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20521. // crash the server (it used to call front() on an empty vector inside
  20522. // get_client_ip). The connection-level remote address must be retained instead.
  20523. static void run_malformed_xff_test(const std::string &xff_value) {
  20524. Server svr;
  20525. svr.set_trusted_proxies({"192.0.2.45"});
  20526. std::string observed_remote_addr;
  20527. svr.Get("/ip", [&](const Request &req, Response &res) {
  20528. observed_remote_addr = req.remote_addr;
  20529. res.set_content("ok", "text/plain");
  20530. });
  20531. int port = 0;
  20532. thread t = thread([&]() {
  20533. port = svr.bind_to_any_port(HOST);
  20534. svr.listen_after_bind();
  20535. });
  20536. auto se = detail::scope_exit([&] {
  20537. svr.stop();
  20538. t.join();
  20539. ASSERT_FALSE(svr.is_running());
  20540. });
  20541. svr.wait_until_ready();
  20542. Client cli(HOST, port);
  20543. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20545. EXPECT_EQ(StatusCode::OK_200, res->status);
  20546. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20547. observed_remote_addr == "127.0.0.1");
  20548. }
  20549. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20550. run_malformed_xff_test("");
  20551. }
  20552. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20553. run_malformed_xff_test(",");
  20554. }
  20555. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20556. run_malformed_xff_test(", , ,");
  20557. }
  20558. // The same rule applies to Accept: a request whose acceptable types are spread
  20559. // over several field lines must be negotiated against all of them.
  20560. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20561. // case-insensitive connection options. Comparing the whole field value against
  20562. // one option misses a client that sends several of them, and misses every
  20563. // casing but the one written in the comparison.
  20564. //
  20565. // Sends req, reads the response, then reuses the same socket for a second
  20566. // request to find out whether the server kept the connection.
  20567. static void probe_connection_reuse(int port, const std::string &req,
  20568. bool *announced_close, bool *reusable) {
  20569. auto error = Error::Success;
  20570. auto sock = detail::create_client_socket(
  20571. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20572. /*connection_timeout_sec=*/5, 0,
  20573. /*read_timeout_sec=*/1, 0,
  20574. /*write_timeout_sec=*/5, 0, std::string(), error);
  20575. ASSERT_NE(sock, INVALID_SOCKET);
  20576. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20577. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20578. "Host: localhost\r\n"
  20579. "Connection: close\r\n"
  20580. "\r\n";
  20581. std::string first_response;
  20582. std::string second_response;
  20583. detail::process_client_socket(
  20584. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20585. [&](Stream &strm) {
  20586. if (strm.write(req.data(), req.size()) !=
  20587. static_cast<ssize_t>(req.size())) {
  20588. return false;
  20589. }
  20590. char buf[512];
  20591. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20592. // Headers plus the two-byte body of the handler below
  20593. while (reader.getline()) {
  20594. first_response += reader.ptr();
  20595. if (first_response.find("ok") != std::string::npos) { break; }
  20596. }
  20597. if (strm.write(second.data(), second.size()) !=
  20598. static_cast<ssize_t>(second.size())) {
  20599. return true;
  20600. }
  20601. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20602. while (reader2.getline()) {
  20603. second_response += reader2.ptr();
  20604. if (second_response.find("ok") != std::string::npos) { break; }
  20605. }
  20606. return true;
  20607. });
  20608. *announced_close =
  20609. first_response.find("Connection: close") != std::string::npos;
  20610. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20611. }
  20612. class ConnectionTokenTest : public ::testing::Test {
  20613. protected:
  20614. void SetUp() override {
  20615. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20616. res.set_content("ok", "text/plain");
  20617. });
  20618. port_ = svr_.bind_to_any_port(HOST);
  20619. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20620. svr_.wait_until_ready();
  20621. }
  20622. void TearDown() override {
  20623. svr_.stop();
  20624. if (thread_.joinable()) { thread_.join(); }
  20625. }
  20626. Server svr_;
  20627. int port_ = 0;
  20628. thread thread_;
  20629. };
  20630. // "close" alongside another option still closes the connection, and the
  20631. // response says so rather than leaving the peer to discover it.
  20632. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20633. bool announced_close = false;
  20634. bool reusable = true;
  20635. probe_connection_reuse(port_,
  20636. "GET /keepalive HTTP/1.1\r\n"
  20637. "Host: localhost\r\n"
  20638. "Connection: keep-alive, close\r\n"
  20639. "\r\n",
  20640. &announced_close, &reusable);
  20641. EXPECT_TRUE(announced_close);
  20642. EXPECT_FALSE(reusable);
  20643. }
  20644. // "close" split over two field lines is the same list, so it is honored too.
  20645. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20646. bool announced_close = false;
  20647. bool reusable = true;
  20648. probe_connection_reuse(port_,
  20649. "GET /keepalive HTTP/1.1\r\n"
  20650. "Host: localhost\r\n"
  20651. "Connection: keep-alive\r\n"
  20652. "Connection: close\r\n"
  20653. "\r\n",
  20654. &announced_close, &reusable);
  20655. EXPECT_TRUE(announced_close);
  20656. EXPECT_FALSE(reusable);
  20657. }
  20658. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20659. // keep-alive in the spelling everyone actually sends keeps its connection.
  20660. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20661. bool announced_close = false;
  20662. bool reusable = false;
  20663. probe_connection_reuse(port_,
  20664. "GET /keepalive HTTP/1.0\r\n"
  20665. "Host: localhost\r\n"
  20666. "Connection: keep-alive\r\n"
  20667. "\r\n",
  20668. &announced_close, &reusable);
  20669. EXPECT_FALSE(announced_close);
  20670. EXPECT_TRUE(reusable);
  20671. }
  20672. // A token the value merely contains is not the token itself.
  20673. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20674. bool announced_close = false;
  20675. bool reusable = false;
  20676. probe_connection_reuse(port_,
  20677. "GET /keepalive HTTP/1.1\r\n"
  20678. "Host: localhost\r\n"
  20679. "Connection: notclose\r\n"
  20680. "\r\n",
  20681. &announced_close, &reusable);
  20682. EXPECT_FALSE(announced_close);
  20683. EXPECT_TRUE(reusable);
  20684. }
  20685. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20686. Server svr;
  20687. std::vector<std::string> observed_types;
  20688. svr.Get("/", [&](const Request &req, Response &res) {
  20689. observed_types = req.accept_content_types;
  20690. res.set_content("ok", "text/plain");
  20691. });
  20692. auto port = svr.bind_to_any_port(HOST);
  20693. thread t = thread([&]() { svr.listen_after_bind(); });
  20694. auto se = detail::scope_exit([&] {
  20695. svr.stop();
  20696. t.join();
  20697. ASSERT_FALSE(svr.is_running());
  20698. });
  20699. svr.wait_until_ready();
  20700. Client cli(HOST, port);
  20701. Headers headers;
  20702. headers.emplace("Accept", "text/plain;q=0.5");
  20703. headers.emplace("Accept", "application/json");
  20704. auto res = cli.Get("/", headers);
  20705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20706. EXPECT_EQ(StatusCode::OK_200, res->status);
  20707. // Sorted by q-value, so the second field line's type comes first
  20708. ASSERT_EQ(2U, observed_types.size());
  20709. EXPECT_EQ("application/json", observed_types[0]);
  20710. EXPECT_EQ("text/plain", observed_types[1]);
  20711. }
  20712. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20713. // empty field line must not contribute a bare comma to the combined value.
  20714. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20715. Server svr;
  20716. std::vector<std::string> observed_types;
  20717. svr.Get("/", [&](const Request &req, Response &res) {
  20718. observed_types = req.accept_content_types;
  20719. res.set_content("ok", "text/plain");
  20720. });
  20721. auto port = svr.bind_to_any_port(HOST);
  20722. thread t = thread([&]() { svr.listen_after_bind(); });
  20723. auto se = detail::scope_exit([&] {
  20724. svr.stop();
  20725. t.join();
  20726. ASSERT_FALSE(svr.is_running());
  20727. });
  20728. svr.wait_until_ready();
  20729. // Empty first field line, then a real one
  20730. std::string raw_req = "GET / HTTP/1.1\r\n"
  20731. "Host: localhost\r\n"
  20732. "Accept:\r\n"
  20733. "Accept: application/json\r\n"
  20734. "Connection: close\r\n"
  20735. "\r\n";
  20736. std::string out;
  20737. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20738. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20739. ASSERT_EQ(1U, observed_types.size());
  20740. EXPECT_EQ("application/json", observed_types[0]);
  20741. }
  20742. // The skip in get_combined_header_value() is what keeps an empty field line
  20743. // from contributing a bare comma. Only a trailing empty field line exercises
  20744. // it: a leading one is already covered by the "combined is still empty" check,
  20745. // and parse_accept_header() now ignores the empty element either way, so the
  20746. // request-level test above can no longer tell the two apart.
  20747. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20748. Headers headers;
  20749. headers.emplace("Accept", "text/html");
  20750. headers.emplace("Accept", "");
  20751. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20752. headers.clear();
  20753. headers.emplace("Accept", "");
  20754. headers.emplace("Accept", "application/json");
  20755. EXPECT_EQ("application/json",
  20756. detail::get_combined_header_value(headers, "Accept"));
  20757. }
  20758. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20759. // An encoding offered on a later Accept-Encoding field line is still offered.
  20760. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20761. Server svr;
  20762. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20763. res.set_content(std::string(1024, 'x'), "text/plain");
  20764. });
  20765. auto port = svr.bind_to_any_port(HOST);
  20766. thread t = thread([&]() { svr.listen_after_bind(); });
  20767. auto se = detail::scope_exit([&] {
  20768. svr.stop();
  20769. t.join();
  20770. ASSERT_FALSE(svr.is_running());
  20771. });
  20772. svr.wait_until_ready();
  20773. Client cli(HOST, port);
  20774. cli.set_decompress(false);
  20775. Headers headers;
  20776. headers.emplace("Accept-Encoding", "identity");
  20777. headers.emplace("Accept-Encoding", "gzip");
  20778. auto res = cli.Get("/", headers);
  20779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20780. EXPECT_EQ(StatusCode::OK_200, res->status);
  20781. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20782. }
  20783. #endif
  20784. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20785. // Transfer-Encoding is not its body.
  20786. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20787. Server svr;
  20788. svr.set_payload_max_length(8);
  20789. svr.Post("/test", [](const Request &, Response &res) {
  20790. res.set_content("ok", "text/plain");
  20791. });
  20792. auto port = svr.bind_to_any_port(HOST);
  20793. ASSERT_GT(port, 0);
  20794. thread t = thread([&] { svr.listen_after_bind(); });
  20795. auto se = detail::scope_exit([&] {
  20796. svr.stop();
  20797. t.join();
  20798. ASSERT_FALSE(svr.is_running());
  20799. });
  20800. svr.wait_until_ready();
  20801. std::string resp;
  20802. ASSERT_TRUE(send_request(1,
  20803. "POST /test HTTP/1.1\r\n"
  20804. "Host: localhost\r\n"
  20805. "Connection: close\r\n"
  20806. "\r\n" +
  20807. std::string(16, 'X'),
  20808. &resp, port));
  20809. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20810. }
  20811. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20812. Server svr;
  20813. svr.Post("/post", [&](const Request &req, Response &res) {
  20814. res.set_content(req.body, "text/plain");
  20815. });
  20816. svr.Put("/put", [&](const Request &req, Response &res) {
  20817. res.set_content(req.body, "text/plain");
  20818. });
  20819. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20820. res.set_content(req.body, "text/plain");
  20821. });
  20822. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20823. res.set_content(req.body, "text/plain");
  20824. });
  20825. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20826. auto se = detail::scope_exit([&] {
  20827. svr.stop();
  20828. t.join();
  20829. ASSERT_FALSE(svr.is_running());
  20830. });
  20831. svr.wait_until_ready();
  20832. std::string resp;
  20833. // POST without Content-Length
  20834. ASSERT_TRUE(send_request(5,
  20835. "POST /post HTTP/1.1\r\n"
  20836. "Host: localhost\r\n"
  20837. "Connection: close\r\n"
  20838. "\r\n",
  20839. &resp));
  20840. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20841. // PUT without Content-Length
  20842. resp.clear();
  20843. ASSERT_TRUE(send_request(5,
  20844. "PUT /put HTTP/1.1\r\n"
  20845. "Host: localhost\r\n"
  20846. "Connection: close\r\n"
  20847. "\r\n",
  20848. &resp));
  20849. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20850. // PATCH without Content-Length
  20851. resp.clear();
  20852. ASSERT_TRUE(send_request(5,
  20853. "PATCH /patch HTTP/1.1\r\n"
  20854. "Host: localhost\r\n"
  20855. "Connection: close\r\n"
  20856. "\r\n",
  20857. &resp));
  20858. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20859. // DELETE without Content-Length
  20860. resp.clear();
  20861. ASSERT_TRUE(send_request(5,
  20862. "DELETE /delete HTTP/1.1\r\n"
  20863. "Host: localhost\r\n"
  20864. "Connection: close\r\n"
  20865. "\r\n",
  20866. &resp));
  20867. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20868. }
  20869. //==============================================================================
  20870. // open_stream() Tests
  20871. //==============================================================================
  20872. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20873. std::string result;
  20874. char buf[8192];
  20875. ssize_t n;
  20876. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20877. result.append(buf, static_cast<size_t>(n));
  20878. }
  20879. return result;
  20880. }
  20881. // Mock stream for unit tests
  20882. class MockStream : public Stream {
  20883. public:
  20884. std::string data;
  20885. size_t pos = 0;
  20886. ssize_t error_after = -1; // -1 = no error
  20887. explicit MockStream(const std::string &d, ssize_t err = -1)
  20888. : data(d), error_after(err) {}
  20889. bool is_readable() const override { return true; }
  20890. bool wait_readable() const override { return true; }
  20891. bool wait_writable() const override { return true; }
  20892. ssize_t read(char *ptr, size_t size) override {
  20893. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20894. if (pos >= data.size()) return 0;
  20895. size_t limit =
  20896. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20897. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20898. std::memcpy(ptr, data.data() + pos, to_read);
  20899. pos += to_read;
  20900. return static_cast<ssize_t>(to_read);
  20901. }
  20902. ssize_t write(const char *, size_t) override { return -1; }
  20903. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20904. ip = "127.0.0.1";
  20905. port = 0;
  20906. }
  20907. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20908. ip = "127.0.0.1";
  20909. port = 0;
  20910. }
  20911. socket_t socket() const override { return INVALID_SOCKET; }
  20912. time_t duration() const override { return 0; }
  20913. };
  20914. TEST(StreamHandleTest, Basic) {
  20915. ClientImpl::StreamHandle handle;
  20916. EXPECT_FALSE(handle.is_valid());
  20917. handle.response = detail::make_unique<Response>();
  20918. handle.error = Error::Connection;
  20919. EXPECT_FALSE(handle.is_valid());
  20920. handle.error = Error::Success;
  20921. EXPECT_TRUE(handle.is_valid());
  20922. }
  20923. TEST(BodyReaderTest, Basic) {
  20924. MockStream stream("Hello, World!");
  20925. detail::BodyReader reader;
  20926. reader.stream = &stream;
  20927. reader.content_length = 13;
  20928. char buf[32];
  20929. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20930. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20931. EXPECT_TRUE(reader.eof);
  20932. }
  20933. TEST(BodyReaderTest, NoStream) {
  20934. detail::BodyReader reader;
  20935. char buf[32];
  20936. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20937. EXPECT_EQ(Error::Connection, reader.last_error);
  20938. }
  20939. TEST(BodyReaderTest, Error) {
  20940. MockStream stream("Hello, World!", 5);
  20941. detail::BodyReader reader;
  20942. reader.stream = &stream;
  20943. reader.content_length = 13;
  20944. char buf[32];
  20945. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20946. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20947. EXPECT_EQ(Error::Read, reader.last_error);
  20948. }
  20949. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20950. // Mock-based StreamHandle tests relying on private internals are removed.
  20951. class OpenStreamTest : public ::testing::Test {
  20952. protected:
  20953. void SetUp() override {
  20954. svr_.Get("/hello", [](const Request &, Response &res) {
  20955. res.set_content("Hello World!", "text/plain");
  20956. });
  20957. svr_.Get("/large", [](const Request &, Response &res) {
  20958. res.set_content(std::string(10000, 'X'), "text/plain");
  20959. });
  20960. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20961. res.set_content("Hello World!", "image/jpeg");
  20962. res.set_header("Content-Encoding", "UTF-8");
  20963. });
  20964. svr_.Get("/chunked", [](const Request &, Response &res) {
  20965. res.set_chunked_content_provider("text/plain",
  20966. [](size_t offset, DataSink &sink) {
  20967. if (offset < 15) {
  20968. sink.write("chunk", 5);
  20969. return true;
  20970. }
  20971. sink.done();
  20972. return true;
  20973. });
  20974. });
  20975. svr_.Get("/compressible", [](const Request &, Response &res) {
  20976. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20977. DataSink &sink) {
  20978. if (offset < 100 * 1024) {
  20979. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20980. sink.write(chunk.data(), chunk.size());
  20981. return true;
  20982. }
  20983. sink.done();
  20984. return true;
  20985. });
  20986. });
  20987. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20988. [](const Request & /*req*/, Response &res) {
  20989. auto i = new int(0);
  20990. res.set_header("Trailer", "Content-Length, X-Allowed");
  20991. res.set_chunked_content_provider(
  20992. "text/plain",
  20993. [i](size_t /*offset*/, DataSink &sink) {
  20994. switch (*i) {
  20995. case 0: sink.os << "123"; break;
  20996. case 1: sink.os << "456"; break;
  20997. case 2: sink.os << "789"; break;
  20998. case 3: {
  20999. sink.done_with_trailer(
  21000. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  21001. } break;
  21002. }
  21003. (*i)++;
  21004. return true;
  21005. },
  21006. [i](bool success) {
  21007. EXPECT_TRUE(success);
  21008. delete i;
  21009. });
  21010. });
  21011. // Echo headers endpoint for header-related tests
  21012. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  21013. std::string body;
  21014. for (const auto &h : req.headers) {
  21015. body.append(h.first);
  21016. body.push_back(':');
  21017. body.append(h.second);
  21018. body.push_back('\n');
  21019. }
  21020. res.set_content(body, "text/plain");
  21021. });
  21022. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  21023. std::string body;
  21024. for (const auto &h : req.headers) {
  21025. body.append(h.first);
  21026. body.push_back(':');
  21027. body.append(h.second);
  21028. body.push_back('\n');
  21029. }
  21030. res.set_content(body, "text/plain");
  21031. });
  21032. port_ = svr_.bind_to_any_port("127.0.0.1");
  21033. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21034. svr_.wait_until_ready();
  21035. }
  21036. void TearDown() override {
  21037. svr_.stop();
  21038. if (thread_.joinable()) thread_.join();
  21039. }
  21040. Server svr_;
  21041. std::thread thread_;
  21042. int port_ = 0;
  21043. };
  21044. TEST_F(OpenStreamTest, Basic) {
  21045. Client cli("127.0.0.1", port_);
  21046. auto handle = cli.open_stream("GET", "/hello");
  21047. EXPECT_TRUE(handle.is_valid());
  21048. EXPECT_EQ("Hello World!", read_all(handle));
  21049. }
  21050. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  21051. Client cli("127.0.0.1", port_);
  21052. auto handle = cli.open_stream("GET", "/unknown-encoding");
  21053. ASSERT_TRUE(handle.is_valid());
  21054. EXPECT_EQ("Hello World!", read_all(handle));
  21055. }
  21056. TEST_F(OpenStreamTest, SmallBuffer) {
  21057. Client cli("127.0.0.1", port_);
  21058. auto handle = cli.open_stream("GET", "/hello");
  21059. std::string result;
  21060. char buf[4];
  21061. ssize_t n;
  21062. while ((n = handle.read(buf, sizeof(buf))) > 0)
  21063. result.append(buf, static_cast<size_t>(n));
  21064. EXPECT_EQ("Hello World!", result);
  21065. }
  21066. TEST_F(OpenStreamTest, DefaultHeaders) {
  21067. Client cli("127.0.0.1", port_);
  21068. // open_stream GET should include Host, User-Agent and Accept-Encoding
  21069. {
  21070. auto handle = cli.open_stream("GET", "/echo-headers");
  21071. ASSERT_TRUE(handle.is_valid());
  21072. auto body = read_all(handle);
  21073. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  21074. std::string::npos);
  21075. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  21076. std::string::npos);
  21077. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  21078. }
  21079. // open_stream POST with body and no explicit content_type should NOT add
  21080. // text/plain Content-Type (behavior differs from non-streaming path), but
  21081. // should include Content-Length
  21082. {
  21083. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  21084. ASSERT_TRUE(handle.is_valid());
  21085. auto body = read_all(handle);
  21086. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  21087. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  21088. }
  21089. // open_stream POST with explicit Content-Type should preserve it
  21090. {
  21091. auto handle = cli.open_stream("POST", "/echo-headers", {},
  21092. {{"Content-Type", "application/custom"}},
  21093. "{}", "application/custom");
  21094. ASSERT_TRUE(handle.is_valid());
  21095. auto body = read_all(handle);
  21096. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  21097. }
  21098. // User-specified User-Agent must not be overwritten for stream API
  21099. {
  21100. auto handle = cli.open_stream("GET", "/echo-headers", {},
  21101. {{"User-Agent", "MyAgent/1.2"}});
  21102. ASSERT_TRUE(handle.is_valid());
  21103. auto body = read_all(handle);
  21104. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  21105. }
  21106. }
  21107. TEST_F(OpenStreamTest, Large) {
  21108. Client cli("127.0.0.1", port_);
  21109. auto handle = cli.open_stream("GET", "/large");
  21110. EXPECT_EQ(10000u, read_all(handle).size());
  21111. }
  21112. TEST_F(OpenStreamTest, ConnectionError) {
  21113. Client cli("127.0.0.1", 9999);
  21114. auto handle = cli.open_stream("GET", "/hello");
  21115. EXPECT_FALSE(handle.is_valid());
  21116. }
  21117. TEST_F(OpenStreamTest, Chunked) {
  21118. Client cli("127.0.0.1", port_);
  21119. auto handle = cli.open_stream("GET", "/chunked");
  21120. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21121. "Transfer-Encoding") == "chunked");
  21122. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  21123. }
  21124. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  21125. Client cli("127.0.0.1", port_);
  21126. auto handle =
  21127. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  21128. ASSERT_TRUE(handle.is_valid());
  21129. // Consume body to allow trailers to be received/parsed
  21130. auto body = read_all(handle);
  21131. // Explicitly parse trailers (ensure trailers are available for assertion)
  21132. handle.parse_trailers_if_needed();
  21133. EXPECT_EQ(std::string("123456789"), body);
  21134. // The response should include a Trailer header declaring both names
  21135. ASSERT_TRUE(handle.response);
  21136. EXPECT_TRUE(handle.response->has_header("Trailer"));
  21137. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  21138. handle.response->get_header_value("Trailer"));
  21139. // Prohibited trailer must not be present
  21140. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  21141. // Allowed trailer should be present
  21142. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  21143. EXPECT_EQ(std::string("yes"),
  21144. handle.response->get_trailer_value("X-Allowed"));
  21145. // Verify trailers are NOT present as regular headers
  21146. EXPECT_EQ(std::string(""),
  21147. handle.response->get_header_value("Content-Length"));
  21148. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  21149. }
  21150. // Accepts one connection on an OS-assigned port, which it hands over through
  21151. // port_promise, reads the request head and sends back response. after_send,
  21152. // if given, runs on the connection before it is closed.
  21153. static std::thread
  21154. serve_single_response(std::promise<int> &port_promise,
  21155. const std::string &response,
  21156. std::function<void(socket_t)> after_send = nullptr) {
  21157. return std::thread([&port_promise, response, after_send] {
  21158. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21159. default_socket_options(srv);
  21160. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21161. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21162. sockaddr_in addr{};
  21163. addr.sin_family = AF_INET;
  21164. addr.sin_port = htons(0); // Let OS assign a free port
  21165. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21166. int opt = 1;
  21167. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  21168. #ifdef _WIN32
  21169. reinterpret_cast<const char *>(&opt),
  21170. #else
  21171. &opt,
  21172. #endif
  21173. sizeof(opt));
  21174. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21175. ::listen(srv, 1) != 0) {
  21176. port_promise.set_value(-1);
  21177. detail::close_socket(srv);
  21178. return;
  21179. }
  21180. socklen_t addr_len = sizeof(addr);
  21181. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21182. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21183. sockaddr_in cli_addr{};
  21184. socklen_t cli_len = sizeof(cli_addr);
  21185. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21186. if (cli != INVALID_SOCKET) {
  21187. // Read the complete HTTP request (until the blank line that terminates
  21188. // headers) before sending the response. If the server closes the socket
  21189. // while the client's request data is still unread in the kernel receive
  21190. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  21191. // connection on both sides: it discards the client's receive buffer
  21192. // (which already holds our response) and causes any in-progress write on
  21193. // the client to fail with ECONNRESET. Reading all request data first
  21194. // ensures close() emits a graceful FIN.
  21195. {
  21196. char rbuf[256];
  21197. std::string req;
  21198. while (req.find("\r\n\r\n") == std::string::npos) {
  21199. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  21200. if (n <= 0) { break; }
  21201. req.append(rbuf, static_cast<size_t>(n));
  21202. }
  21203. }
  21204. ::send(cli,
  21205. #ifdef _WIN32
  21206. static_cast<const char *>(response.c_str()),
  21207. static_cast<int>(response.size()),
  21208. #else
  21209. response.c_str(), response.size(),
  21210. #endif
  21211. 0);
  21212. if (after_send) { after_send(cli); }
  21213. detail::close_socket(cli);
  21214. }
  21215. detail::close_socket(srv);
  21216. });
  21217. }
  21218. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  21219. #ifndef _WIN32
  21220. signal(SIGPIPE, SIG_IGN);
  21221. #endif
  21222. std::promise<int> port_promise;
  21223. auto port_future = port_promise.get_future();
  21224. auto server_thread =
  21225. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  21226. "Content-Type: text/plain\r\n"
  21227. "Content-Length: not-a-number\r\n"
  21228. "Connection: close\r\n"
  21229. "\r\n"
  21230. "hello");
  21231. auto port = port_future.get();
  21232. ASSERT_GT(port, 0);
  21233. Client cli("127.0.0.1", port);
  21234. auto handle = cli.open_stream("GET", "/");
  21235. EXPECT_FALSE(handle.is_valid());
  21236. server_thread.join();
  21237. }
  21238. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  21239. #ifndef _WIN32
  21240. signal(SIGPIPE, SIG_IGN);
  21241. #endif
  21242. std::promise<int> port_promise;
  21243. auto port_future = port_promise.get_future();
  21244. auto server_thread = serve_single_response(
  21245. port_promise, "HTTP/1.1 200 OK\r\n"
  21246. "Content-Type: text/plain\r\n"
  21247. "Content-Length: 99999999999999999999999999\r\n"
  21248. "Connection: close\r\n"
  21249. "\r\n"
  21250. "hello");
  21251. auto port = port_future.get();
  21252. ASSERT_GT(port, 0);
  21253. // Historically std::stoull would throw std::out_of_range here and crash
  21254. // the process, then parsing silently clamped to a bogus framing length and
  21255. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  21256. // so the stream fails to open, matching the not-a-number case above. The
  21257. // process still must NOT terminate.
  21258. Client cli("127.0.0.1", port);
  21259. auto handle = cli.open_stream("GET", "/");
  21260. EXPECT_FALSE(handle.is_valid());
  21261. server_thread.join();
  21262. }
  21263. #ifndef _WIN32
  21264. // As above for the body of a streamed request: a send() cut short by the write
  21265. // timeout must not leave the rest of the body unsent.
  21266. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  21267. signal(SIGPIPE, SIG_IGN);
  21268. Server svr;
  21269. svr.set_socket_options([](socket_t sock) {
  21270. int size = 8192;
  21271. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  21272. reinterpret_cast<const char *>(&size), sizeof(size));
  21273. });
  21274. svr.Post("/size", [](const Request &, Response &res,
  21275. const ContentReader &content_reader) {
  21276. // Outlast the client's write timeout before reading the body.
  21277. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  21278. size_t received = 0;
  21279. content_reader([&](const char *, size_t len) {
  21280. received += len;
  21281. return true;
  21282. });
  21283. res.set_content(std::to_string(received), "text/plain");
  21284. });
  21285. auto port = svr.bind_to_any_port(HOST);
  21286. std::thread t([&]() { svr.listen_after_bind(); });
  21287. auto se = detail::scope_exit([&] {
  21288. svr.stop();
  21289. t.join();
  21290. });
  21291. svr.wait_until_ready();
  21292. Client cli(HOST, port);
  21293. cli.set_write_timeout(0, 500000);
  21294. cli.set_socket_options([](socket_t sock) {
  21295. int size = 8192;
  21296. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21297. reinterpret_cast<const char *>(&size), sizeof(size));
  21298. });
  21299. const std::string body(4 * 1024 * 1024, 'A');
  21300. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21301. "application/octet-stream");
  21302. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21303. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21304. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21305. }
  21306. #endif
  21307. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21308. std::promise<void> slow_started;
  21309. auto slow_started_future = slow_started.get_future();
  21310. Server svr;
  21311. svr.Get("/slow", [&](const Request &, Response &res) {
  21312. slow_started.set_value();
  21313. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21314. res.set_content("slow", "text/plain");
  21315. });
  21316. svr.Get("/fast", [](const Request &, Response &res) {
  21317. res.set_content("fast", "text/plain");
  21318. });
  21319. auto port = svr.bind_to_any_port(HOST);
  21320. std::thread t([&]() { svr.listen_after_bind(); });
  21321. auto se = detail::scope_exit([&] {
  21322. svr.stop();
  21323. t.join();
  21324. });
  21325. svr.wait_until_ready();
  21326. Client cli(HOST, port);
  21327. std::string slow_body;
  21328. std::thread slow_thread([&] {
  21329. auto res = cli.Get("/slow");
  21330. if (res) { slow_body = res->body; }
  21331. });
  21332. slow_started_future.wait();
  21333. auto result = stream::Get(cli, "/fast");
  21334. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21335. slow_thread.join();
  21336. EXPECT_EQ("slow", slow_body);
  21337. EXPECT_EQ("fast", fast_body);
  21338. }
  21339. // Serves `response` to the single request `fn` makes with a fresh client.
  21340. template <typename Fn>
  21341. static void with_single_response(const std::string &response, Fn fn) {
  21342. #ifndef _WIN32
  21343. signal(SIGPIPE, SIG_IGN);
  21344. #endif
  21345. std::promise<int> port_promise;
  21346. auto port_future = port_promise.get_future();
  21347. auto server_thread = serve_single_response(port_promise, response);
  21348. auto se = detail::scope_exit([&] { server_thread.join(); });
  21349. auto port = port_future.get();
  21350. ASSERT_GT(port, 0);
  21351. Client cli("127.0.0.1", port);
  21352. fn(cli);
  21353. }
  21354. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21355. // too, also in a build without the decoder for the advertised coding.
  21356. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21357. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21358. const auto response = "HTTP/1.1 200 OK\r\n"
  21359. "Content-Encoding: gzip\r\n"
  21360. "Content-Length: " +
  21361. std::to_string(gzipped.size()) +
  21362. "\r\n"
  21363. "Connection: close\r\n\r\n" +
  21364. gzipped;
  21365. with_single_response(response, [&](Client &cli) {
  21366. cli.set_decompress(false);
  21367. auto handle = cli.open_stream("GET", "/");
  21368. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21369. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21370. EXPECT_EQ(gzipped, read_all(handle));
  21371. EXPECT_FALSE(handle.has_read_error());
  21372. });
  21373. with_single_response(response, [&](Client &cli) {
  21374. cli.set_decompress(false);
  21375. auto res = stream::Get(cli, "/", 7);
  21376. ASSERT_TRUE(res) << to_string(res.error());
  21377. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21378. EXPECT_EQ(gzipped, res.read_all());
  21379. EXPECT_FALSE(res.has_read_error());
  21380. });
  21381. }
  21382. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21383. // Neither Content-Length nor chunked: the body ends at the close
  21384. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21385. "Connection: close\r\n"
  21386. "\r\n"
  21387. "hello";
  21388. with_single_response(close_delimited, [](Client &cli) {
  21389. auto handle = cli.open_stream("GET", "/");
  21390. ASSERT_TRUE(handle.is_valid());
  21391. EXPECT_EQ("hello", read_all(handle));
  21392. EXPECT_FALSE(handle.has_read_error());
  21393. });
  21394. // A close before the end of the Content-Length is still an error
  21395. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21396. "Content-Length: 10\r\n"
  21397. "\r\n"
  21398. "hello";
  21399. with_single_response(short_content_length, [](Client &cli) {
  21400. auto handle = cli.open_stream("GET", "/");
  21401. ASSERT_TRUE(handle.is_valid());
  21402. read_all(handle);
  21403. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21404. });
  21405. // So is a close before the last chunk
  21406. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21407. "Transfer-Encoding: chunked\r\n"
  21408. "\r\n"
  21409. "5\r\nhello\r\n";
  21410. with_single_response(short_chunked, [](Client &cli) {
  21411. auto handle = cli.open_stream("GET", "/");
  21412. ASSERT_TRUE(handle.is_valid());
  21413. read_all(handle);
  21414. EXPECT_TRUE(handle.has_read_error());
  21415. });
  21416. }
  21417. #ifdef CPPHTTPLIB_SSL_ENABLED
  21418. // Serves `response` to one request, then closes with or without a close_notify
  21419. template <typename Fn>
  21420. static void with_single_tls_response(const std::string &response,
  21421. bool close_notify, Fn fn) {
  21422. #ifndef _WIN32
  21423. signal(SIGPIPE, SIG_IGN);
  21424. #endif
  21425. std::promise<int> port_promise;
  21426. auto port_future = port_promise.get_future();
  21427. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21428. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21429. default_socket_options(srv);
  21430. sockaddr_in addr{};
  21431. addr.sin_family = AF_INET;
  21432. addr.sin_port = htons(0);
  21433. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21434. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21435. ::listen(srv, 1) != 0) {
  21436. port_promise.set_value(-1);
  21437. detail::close_socket(srv);
  21438. return;
  21439. }
  21440. socklen_t addr_len = sizeof(addr);
  21441. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21442. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21443. auto cli = ::accept(srv, nullptr, nullptr);
  21444. if (cli != INVALID_SOCKET) {
  21445. auto ctx = tls::create_server_context();
  21446. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21447. nullptr);
  21448. auto session = tls::create_session(ctx, cli);
  21449. tls::TlsError err;
  21450. if (tls::accept_nonblocking(session, cli, 5, 0, &err, nullptr)) {
  21451. // The request head first, so that closing the socket sends a FIN
  21452. // rather than an RST for the unread bytes.
  21453. std::string req;
  21454. char buf[256];
  21455. while (req.find("\r\n\r\n") == std::string::npos) {
  21456. auto n = tls::read(session, buf, sizeof(buf), err);
  21457. if (n <= 0) { break; }
  21458. req.append(buf, static_cast<size_t>(n));
  21459. }
  21460. size_t sent = 0;
  21461. while (sent < response.size()) {
  21462. auto n = tls::write(session, response.data() + sent,
  21463. response.size() - sent, err);
  21464. if (n <= 0) { break; }
  21465. sent += static_cast<size_t>(n);
  21466. }
  21467. if (close_notify) { tls::shutdown(session, true); }
  21468. }
  21469. tls::free_session(session);
  21470. detail::close_socket(cli);
  21471. tls::free_context(ctx);
  21472. }
  21473. detail::close_socket(srv);
  21474. });
  21475. auto se = detail::scope_exit([&] { server_thread.join(); });
  21476. auto port = port_future.get();
  21477. ASSERT_GT(port, 0);
  21478. SSLClient cli("127.0.0.1", port);
  21479. cli.enable_server_certificate_verification(false);
  21480. fn(cli);
  21481. }
  21482. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21483. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21484. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21485. "Connection: close\r\n"
  21486. "\r\n"
  21487. "hello";
  21488. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21489. auto res = cli.Get("/");
  21490. ASSERT_TRUE(res) << to_string(res.error());
  21491. EXPECT_EQ("hello", res->body);
  21492. });
  21493. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21494. auto res = cli.Get("/");
  21495. ASSERT_FALSE(res);
  21496. EXPECT_EQ(Error::Read, res.error());
  21497. });
  21498. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21499. auto handle = cli.open_stream("GET", "/");
  21500. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21501. read_all(handle);
  21502. EXPECT_TRUE(handle.has_read_error());
  21503. });
  21504. // A framed body ends where its framing says, with or without the alert
  21505. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21506. "Content-Length: 5\r\n"
  21507. "Connection: close\r\n"
  21508. "\r\n"
  21509. "hello";
  21510. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21511. auto res = cli.Get("/");
  21512. ASSERT_TRUE(res) << to_string(res.error());
  21513. EXPECT_EQ("hello", res->body);
  21514. });
  21515. }
  21516. #endif
  21517. TEST(ResponseHeaderLengthTest, ClientReadsLongerFieldsThanServer) {
  21518. const auto value = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH * 2, 'a');
  21519. const auto response = "HTTP/1.1 200 OK\r\n"
  21520. "X-Long: " +
  21521. value +
  21522. "\r\n"
  21523. "Content-Length: 2\r\n"
  21524. "Connection: close\r\n\r\nok";
  21525. with_single_response(response, [&](Client &cli) {
  21526. auto res = cli.Get("/");
  21527. ASSERT_TRUE(res) << to_string(res.error());
  21528. EXPECT_EQ(value, res->get_header_value("X-Long"));
  21529. });
  21530. with_single_response(response, [&](Client &cli) {
  21531. auto handle = cli.open_stream("GET", "/");
  21532. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21533. EXPECT_EQ(value, handle.response->get_header_value("X-Long"));
  21534. });
  21535. std::string out;
  21536. test_raw_request("GET /hi HTTP/1.1\r\n"
  21537. "Host: localhost\r\n"
  21538. "X-Long: " +
  21539. value + "\r\n\r\n",
  21540. &out);
  21541. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  21542. }
  21543. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21544. const char *responses[] = {
  21545. "HTTP/1.1 103 Early Hints\r\n"
  21546. "Link: </style.css>; rel=preload\r\n"
  21547. "\r\n"
  21548. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21549. "HTTP/1.1 100 Continue\r\n"
  21550. "X-Note: interim\r\n"
  21551. "\r\n"
  21552. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21553. };
  21554. for (auto response : responses) {
  21555. with_single_response(response, [](Client &cli) {
  21556. auto res = cli.Get("/");
  21557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21558. EXPECT_EQ(StatusCode::OK_200, res->status);
  21559. EXPECT_EQ("ok", res->body);
  21560. });
  21561. }
  21562. }
  21563. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21564. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21565. const std::string final_response =
  21566. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21567. std::string interims;
  21568. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21569. interims += interim;
  21570. }
  21571. with_single_response(interims + final_response, [](Client &cli) {
  21572. auto res = cli.Get("/");
  21573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21574. EXPECT_EQ("ok", res->body);
  21575. });
  21576. with_single_response(interims + interim + final_response, [](Client &cli) {
  21577. auto res = cli.Get("/");
  21578. ASSERT_FALSE(res);
  21579. EXPECT_EQ(Error::Read, res.error());
  21580. });
  21581. }
  21582. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21583. #ifndef _WIN32
  21584. signal(SIGPIPE, SIG_IGN);
  21585. #endif
  21586. // The server answers the head without asking for the body. Bytes it then
  21587. // reads on the connection would be taken for the body the request declared.
  21588. auto closed_by_client = false;
  21589. std::promise<int> port_promise;
  21590. auto server_thread = serve_single_response(
  21591. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21592. [&](socket_t sock) {
  21593. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21594. char buf[256];
  21595. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21596. });
  21597. Client cli("127.0.0.1", port_promise.get_future().get());
  21598. cli.set_keep_alive(true);
  21599. cli.set_read_timeout(1, 0);
  21600. // Long enough for the client to send Expect: 100-continue.
  21601. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21603. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21604. cli.Get("/second");
  21605. server_thread.join();
  21606. EXPECT_TRUE(closed_by_client);
  21607. }
  21608. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21609. // Long enough for the client to send Expect: 100-continue
  21610. with_single_response(
  21611. "HTTP/1.1 103 Early Hints\r\n"
  21612. "Link: </style.css>; rel=preload\r\n"
  21613. "\r\n"
  21614. "HTTP/1.1 401 Unauthorized\r\n"
  21615. "Content-Length: 0\r\n\r\n",
  21616. [](Client &cli) {
  21617. cli.set_read_timeout(2, 0);
  21618. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21620. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21621. });
  21622. }
  21623. #ifdef CPPHTTPLIB_SSL_ENABLED
  21624. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21625. #ifndef _WIN32
  21626. signal(SIGPIPE, SIG_IGN);
  21627. #endif
  21628. auto reused = false;
  21629. std::promise<int> port_promise;
  21630. auto server_thread = serve_single_response(
  21631. port_promise,
  21632. "HTTP/1.1 401 Unauthorized\r\n"
  21633. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21634. "Content-Length: 0\r\n\r\n",
  21635. [&](socket_t sock) {
  21636. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21637. char buf[256];
  21638. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21639. });
  21640. Client cli("127.0.0.1", port_promise.get_future().get());
  21641. cli.set_keep_alive(true);
  21642. cli.set_digest_auth("user", "pass");
  21643. cli.set_read_timeout(1, 0);
  21644. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21645. server_thread.join();
  21646. EXPECT_FALSE(reused);
  21647. }
  21648. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21649. // Any other answer to CONNECT would read as the origin's response.
  21650. struct {
  21651. const char *response;
  21652. bool passed_on;
  21653. } cases[] = {
  21654. {"HTTP/1.1 201 Created\r\n"
  21655. "Set-Cookie: session=from-proxy\r\n"
  21656. "Content-Length: 0\r\n\r\n",
  21657. false},
  21658. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21659. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21660. "Content-Length: 0\r\n\r\n",
  21661. true},
  21662. };
  21663. for (const auto &c : cases) {
  21664. std::promise<int> port_promise;
  21665. auto server_thread = serve_single_response(port_promise, c.response);
  21666. SSLClient cli("example.com", 443);
  21667. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21668. auto res = cli.Get("/");
  21669. server_thread.join();
  21670. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21671. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21672. if (res) {
  21673. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21674. }
  21675. }
  21676. }
  21677. #endif
  21678. // Records the client's error logger calls as "error METHOD path", or
  21679. // "error null" for a call without a request
  21680. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21681. return [&log](const Error &err, const Request *req) {
  21682. log.push_back(to_string(err) + " " +
  21683. (req ? req->method + " " + req->path : "null"));
  21684. };
  21685. }
  21686. // A failed request is reported once, with the request the caller made
  21687. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21688. Server svr;
  21689. svr.Get("/big", [](const Request &, Response &res) {
  21690. res.set_content(std::string(100000, 'b'), "text/plain");
  21691. });
  21692. auto port = svr.bind_to_any_port(HOST);
  21693. std::thread t([&]() { svr.listen_after_bind(); });
  21694. auto se = detail::scope_exit([&] {
  21695. svr.stop();
  21696. t.join();
  21697. });
  21698. svr.wait_until_ready();
  21699. Client cli(HOST, port);
  21700. std::vector<std::string> log;
  21701. cli.set_error_logger(record_errors(log));
  21702. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21703. cli.Get("/big", [](const char *, size_t) { return false; });
  21704. EXPECT_EQ(expected, log);
  21705. log.clear();
  21706. cli.Get("/big", [](size_t, size_t) { return false; });
  21707. EXPECT_EQ(expected, log);
  21708. }
  21709. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21710. // Fails while the body is read
  21711. auto broken = [](const Request &, Response &res) {
  21712. res.set_content_provider(10, "text/plain",
  21713. [](size_t, size_t, DataSink &) { return false; });
  21714. };
  21715. Server other;
  21716. other.Get("/broken", broken);
  21717. auto other_port = other.bind_to_any_port(HOST);
  21718. std::thread other_t([&]() { other.listen_after_bind(); });
  21719. auto other_se = detail::scope_exit([&] {
  21720. other.stop();
  21721. other_t.join();
  21722. });
  21723. other.wait_until_ready();
  21724. Server svr;
  21725. svr.Get("/broken", broken);
  21726. svr.Get("/same-origin",
  21727. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21728. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21729. res.set_redirect("http://" + std::string(HOST) + ":" +
  21730. std::to_string(other_port) + "/broken");
  21731. });
  21732. auto port = svr.bind_to_any_port(HOST);
  21733. std::thread t([&]() { svr.listen_after_bind(); });
  21734. auto se = detail::scope_exit([&] {
  21735. svr.stop();
  21736. t.join();
  21737. });
  21738. svr.wait_until_ready();
  21739. Client cli(HOST, port);
  21740. cli.set_follow_location(true);
  21741. std::vector<std::string> log;
  21742. cli.set_error_logger(record_errors(log));
  21743. for (auto path : {"/same-origin", "/cross-origin"}) {
  21744. log.clear();
  21745. auto res = cli.Get(path);
  21746. ASSERT_FALSE(res);
  21747. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21748. log);
  21749. }
  21750. }
  21751. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21752. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21753. std::vector<std::string> log;
  21754. cli.set_error_logger(record_errors(log));
  21755. auto handle = cli.open_stream("GET", "/x");
  21756. EXPECT_FALSE(handle.is_valid());
  21757. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21758. log);
  21759. });
  21760. }
  21761. #ifdef CPPHTTPLIB_SSL_ENABLED
  21762. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21763. // Not a TLS server, so the handshake fails. It waits for a request line in
  21764. // the handshake bytes, so a short read timeout lets it close quickly.
  21765. Server svr;
  21766. svr.set_read_timeout(0, 100000);
  21767. svr.Get("/x", [](const Request &, Response &res) {
  21768. res.set_content("x", "text/plain");
  21769. });
  21770. auto port = svr.bind_to_any_port(HOST);
  21771. std::thread t([&]() { svr.listen_after_bind(); });
  21772. auto se = detail::scope_exit([&] {
  21773. svr.stop();
  21774. t.join();
  21775. });
  21776. svr.wait_until_ready();
  21777. std::vector<std::string> log;
  21778. SSLClient cli(HOST, port);
  21779. cli.enable_server_certificate_verification(false);
  21780. cli.set_error_logger(record_errors(log));
  21781. auto res = cli.Get("/x");
  21782. ASSERT_FALSE(res);
  21783. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21784. log.clear();
  21785. auto handle = cli.open_stream("GET", "/x");
  21786. EXPECT_FALSE(handle.is_valid());
  21787. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21788. log.clear();
  21789. SSLClient no_ca(HOST, port);
  21790. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21791. no_ca.set_error_logger(record_errors(log));
  21792. res = no_ca.Get("/x");
  21793. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21794. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21795. }
  21796. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21797. #ifndef _WIN32
  21798. signal(SIGPIPE, SIG_IGN);
  21799. #endif
  21800. // Refused, answered with a challenge, or closed without an answer
  21801. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21802. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21803. "Content-Length: 0\r\n\r\n",
  21804. ""}) {
  21805. std::promise<int> port_promise;
  21806. auto server_thread = serve_single_response(port_promise, response);
  21807. SSLClient cli("example.com", 443);
  21808. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21809. std::vector<std::string> log;
  21810. cli.set_error_logger(record_errors(log));
  21811. auto res = cli.Get("/");
  21812. server_thread.join();
  21813. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21814. << response;
  21815. }
  21816. }
  21817. #endif
  21818. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21819. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21820. // the chunked coding and drop Content-Length, so a front-end that trusts
  21821. // Content-Length would disagree about where the body ends (response
  21822. // smuggling). The client must reject such a response.
  21823. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21824. for (const char *te : {"chunked", "gzip, chunked"}) {
  21825. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21826. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21827. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21828. "5\r\nhello\r\n0\r\n\r\n";
  21829. with_single_response(response, [&](Client &cli) {
  21830. auto res = cli.Get("/");
  21831. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21832. EXPECT_EQ(Error::Read, res.error()) << te;
  21833. });
  21834. with_single_response(response, [&](Client &cli) {
  21835. auto handle = cli.open_stream("GET", "/");
  21836. EXPECT_FALSE(handle.is_valid()) << te;
  21837. EXPECT_EQ(Error::Read, handle.error) << te;
  21838. });
  21839. }
  21840. }
  21841. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21842. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21843. // closing the connection (unlike a request, which must be rejected).
  21844. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21845. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21846. "Transfer-Encoding: chunked\r\n"
  21847. "Connection: close\r\n"
  21848. "\r\n"
  21849. "5\r\nhello\r\n0\r\n\r\n",
  21850. "HTTP/1.1 200 OK\r\n"
  21851. "Transfer-Encoding: gzip\r\n"
  21852. "Connection: close\r\n"
  21853. "\r\n"
  21854. "hello"}) {
  21855. with_single_response(response, [&](Client &cli) {
  21856. auto res = cli.Get("/");
  21857. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21858. EXPECT_EQ("hello", res->body);
  21859. });
  21860. with_single_response(response, [&](Client &cli) {
  21861. auto handle = cli.open_stream("GET", "/");
  21862. ASSERT_TRUE(handle.is_valid()) << response;
  21863. EXPECT_EQ("hello", read_all(handle));
  21864. });
  21865. }
  21866. }
  21867. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21868. // framing headers describe nothing to read and must not be rejected.
  21869. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21870. const std::string framing = "Content-Length: 5\r\n"
  21871. "Transfer-Encoding: chunked\r\n"
  21872. "Connection: close\r\n"
  21873. "\r\n";
  21874. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21875. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21876. });
  21877. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21878. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21879. });
  21880. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21881. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21882. with_single_response(response, [&](Client &cli) {
  21883. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21884. });
  21885. with_single_response(response, [&](Client &cli) {
  21886. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21887. });
  21888. }
  21889. }
  21890. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21891. // header section, so a stream opened on one has nothing to read, whatever
  21892. // framing or coding headers it carries.
  21893. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21894. struct Case {
  21895. const char *method;
  21896. const char *status;
  21897. };
  21898. // A reader of the declared body reports an early close when nothing
  21899. // follows, and hands back what does.
  21900. struct Framing {
  21901. const char *headers;
  21902. const char *after;
  21903. };
  21904. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21905. Case{"GET", "304 Not Modified"}}) {
  21906. for (const auto &f :
  21907. {Framing{"Content-Length: 5\r\n", ""},
  21908. Framing{"Content-Length: 5\r\n", "hello"},
  21909. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21910. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21911. // Not decoded, so a build without Brotli opens it too
  21912. Framing{"Content-Encoding: br\r\n", ""}}) {
  21913. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21914. "Connection: close\r\n"
  21915. "\r\n" +
  21916. f.after;
  21917. with_single_response(response, [&](Client &cli) {
  21918. auto handle = cli.open_stream(c.method, "/");
  21919. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21920. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21921. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21922. });
  21923. }
  21924. }
  21925. }
  21926. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21927. // response, is faulty framing, so the connection is not reused after it.
  21928. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21929. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21930. "Content-Length: 0\r\n"
  21931. "Transfer-Encoding: chunked\r\n"
  21932. "\r\n"
  21933. "5\r\nhello\r\n0\r\n\r\n",
  21934. "HTTP/1.0 200 Connection established\r\n"
  21935. "Connection: keep-alive\r\n"
  21936. "Transfer-Encoding: chunked\r\n"
  21937. "\r\n"
  21938. "5\r\nhello\r\n0\r\n\r\n"}) {
  21939. with_single_response(response, [&](Client &cli) {
  21940. cli.set_keep_alive(true);
  21941. auto res = cli.Get("/");
  21942. ASSERT_TRUE(res) << response;
  21943. EXPECT_EQ("hello", res->body);
  21944. EXPECT_FALSE(cli.is_socket_open()) << response;
  21945. });
  21946. }
  21947. }
  21948. // A payload max length of 0 means no limit, however the body is framed.
  21949. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21950. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21951. "Transfer-Encoding: chunked\r\n"
  21952. "\r\n"
  21953. "5\r\nhello\r\n0\r\n\r\n",
  21954. "HTTP/1.1 200 OK\r\n"
  21955. "Connection: close\r\n"
  21956. "\r\n"
  21957. "hello"}) {
  21958. with_single_response(response, [&](Client &cli) {
  21959. cli.set_payload_max_length(0);
  21960. auto res = cli.Get("/");
  21961. ASSERT_TRUE(res) << response;
  21962. EXPECT_EQ("hello", res->body) << response;
  21963. });
  21964. }
  21965. }
  21966. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21967. Server svr;
  21968. svr.set_payload_max_length(0);
  21969. svr.Post("/echo", [](const Request &req, Response &res) {
  21970. res.set_content(req.body, "text/plain");
  21971. });
  21972. auto port = svr.bind_to_any_port(HOST);
  21973. thread t = thread([&] { svr.listen_after_bind(); });
  21974. auto se = detail::scope_exit([&] {
  21975. svr.stop();
  21976. t.join();
  21977. ASSERT_FALSE(svr.is_running());
  21978. });
  21979. svr.wait_until_ready();
  21980. Client cli(HOST, port);
  21981. auto res = cli.Post(
  21982. "/echo",
  21983. [](size_t /*offset*/, DataSink &sink) {
  21984. sink.write("hello", 5);
  21985. sink.done();
  21986. return true;
  21987. },
  21988. "text/plain");
  21989. ASSERT_TRUE(res);
  21990. EXPECT_EQ(StatusCode::OK_200, res->status);
  21991. EXPECT_EQ("hello", res->body);
  21992. }
  21993. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21994. TEST_F(OpenStreamTest, Gzip) {
  21995. Client cli("127.0.0.1", port_);
  21996. auto handle = cli.open_stream("GET", "/compressible", {},
  21997. {{"Accept-Encoding", "gzip"}});
  21998. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21999. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  22000. }
  22001. TEST_F(OpenStreamTest, TrailersWithGzip) {
  22002. Client cli("127.0.0.1", port_);
  22003. auto handle =
  22004. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  22005. {{"Accept-Encoding", "gzip"}});
  22006. ASSERT_TRUE(handle.is_valid());
  22007. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  22008. EXPECT_EQ("123456789", read_all(handle));
  22009. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  22010. }
  22011. #endif
  22012. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22013. TEST_F(OpenStreamTest, Brotli) {
  22014. Client cli("127.0.0.1", port_);
  22015. auto handle =
  22016. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  22017. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  22018. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  22019. }
  22020. #endif
  22021. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22022. TEST_F(OpenStreamTest, Zstd) {
  22023. Client cli("127.0.0.1", port_);
  22024. auto handle = cli.open_stream("GET", "/compressible", {},
  22025. {{"Accept-Encoding", "zstd"}});
  22026. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  22027. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  22028. }
  22029. #endif
  22030. #ifdef CPPHTTPLIB_SSL_ENABLED
  22031. class SSLOpenStreamTest : public ::testing::Test {
  22032. protected:
  22033. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  22034. void SetUp() override {
  22035. svr_.Get("/hello", [](const Request &, Response &res) {
  22036. res.set_content("Hello SSL World!", "text/plain");
  22037. });
  22038. svr_.Get("/chunked", [](const Request &, Response &res) {
  22039. res.set_chunked_content_provider("text/plain",
  22040. [](size_t offset, DataSink &sink) {
  22041. if (offset < 15) {
  22042. sink.write("chunk", 5);
  22043. return true;
  22044. }
  22045. sink.done();
  22046. return true;
  22047. });
  22048. });
  22049. svr_.Post("/echo", [](const Request &req, Response &res) {
  22050. res.set_content(req.body, req.get_header_value("Content-Type"));
  22051. });
  22052. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  22053. std::string body = req.body;
  22054. res.set_chunked_content_provider(
  22055. "text/plain", [body](size_t offset, DataSink &sink) {
  22056. if (offset < body.size()) {
  22057. sink.write(body.data() + offset, body.size() - offset);
  22058. }
  22059. sink.done();
  22060. return true;
  22061. });
  22062. });
  22063. port_ = svr_.bind_to_any_port("127.0.0.1");
  22064. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22065. svr_.wait_until_ready();
  22066. }
  22067. void TearDown() override {
  22068. svr_.stop();
  22069. if (thread_.joinable()) thread_.join();
  22070. }
  22071. SSLServer svr_;
  22072. std::thread thread_;
  22073. int port_ = 0;
  22074. };
  22075. TEST_F(SSLOpenStreamTest, Basic) {
  22076. SSLClient cli("127.0.0.1", port_);
  22077. cli.enable_server_certificate_verification(false);
  22078. auto handle = cli.open_stream("GET", "/hello");
  22079. ASSERT_TRUE(handle.is_valid());
  22080. EXPECT_EQ("Hello SSL World!", read_all(handle));
  22081. }
  22082. TEST_F(SSLOpenStreamTest, Chunked) {
  22083. SSLClient cli("127.0.0.1", port_);
  22084. cli.enable_server_certificate_verification(false);
  22085. auto handle = cli.open_stream("GET", "/chunked");
  22086. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  22087. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  22088. "Transfer-Encoding") == "chunked");
  22089. auto body = read_all(handle);
  22090. EXPECT_EQ("chunkchunkchunk", body);
  22091. }
  22092. TEST_F(SSLOpenStreamTest, Post) {
  22093. SSLClient cli("127.0.0.1", port_);
  22094. cli.enable_server_certificate_verification(false);
  22095. auto handle =
  22096. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  22097. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  22098. EXPECT_EQ(200, handle.response->status);
  22099. auto body = read_all(handle);
  22100. EXPECT_EQ("Hello SSL POST", body);
  22101. }
  22102. TEST_F(SSLOpenStreamTest, PostChunked) {
  22103. SSLClient cli("127.0.0.1", port_);
  22104. cli.enable_server_certificate_verification(false);
  22105. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  22106. "Chunked SSL Data", "text/plain");
  22107. ASSERT_TRUE(handle.is_valid());
  22108. EXPECT_EQ(200, handle.response->status);
  22109. auto body = read_all(handle);
  22110. EXPECT_EQ("Chunked SSL Data", body);
  22111. }
  22112. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  22113. // Content-Length is terminated by the server closing the connection. When the
  22114. // SSL peer sends a close_notify after the body, the client must treat it as a
  22115. // clean EOF and return a successful response rather than an error.
  22116. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  22117. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22118. ASSERT_TRUE(svr.is_valid());
  22119. svr.set_keep_alive_max_count(1);
  22120. const std::string expected_body = "Hello from connection-close response!";
  22121. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  22122. res.set_content_provider("text/plain",
  22123. [&](size_t offset, DataSink &sink) -> bool {
  22124. if (offset < expected_body.size()) {
  22125. sink.write(expected_body.data() + offset,
  22126. expected_body.size() - offset);
  22127. }
  22128. sink.done();
  22129. return true;
  22130. });
  22131. });
  22132. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  22133. auto se = detail::scope_exit([&] {
  22134. svr.stop();
  22135. listen_thread.join();
  22136. ASSERT_FALSE(svr.is_running());
  22137. });
  22138. svr.wait_until_ready();
  22139. SSLClient cli(HOST, PORT);
  22140. cli.enable_server_certificate_verification(false);
  22141. auto res = cli.Get("/no-content-length");
  22142. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  22143. EXPECT_EQ(StatusCode::OK_200, res->status);
  22144. EXPECT_EQ(expected_body, res->body);
  22145. }
  22146. // Without Content-Length, the full buffer size reaches tls::read().
  22147. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  22148. if (sizeof(size_t) <= sizeof(int)) {
  22149. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  22150. }
  22151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22152. ASSERT_TRUE(svr.is_valid());
  22153. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  22154. res.set_content_provider("text/plain",
  22155. [&](size_t offset, DataSink &sink) -> bool {
  22156. if (offset == 0) { sink.write("Hello", 5); }
  22157. sink.done();
  22158. return true;
  22159. });
  22160. });
  22161. auto port = svr.bind_to_any_port(HOST);
  22162. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  22163. auto se = detail::scope_exit([&] {
  22164. svr.stop();
  22165. listen_thread.join();
  22166. });
  22167. svr.wait_until_ready();
  22168. SSLClient cli(HOST, port);
  22169. cli.enable_server_certificate_verification(false);
  22170. auto handle = cli.open_stream("GET", "/no-content-length");
  22171. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  22172. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  22173. std::unique_ptr<char[]> buf(new char[len]);
  22174. std::string body;
  22175. ssize_t n;
  22176. while ((n = handle.read(buf.get(), len)) > 0) {
  22177. body.append(buf.get(), static_cast<size_t>(n));
  22178. }
  22179. EXPECT_EQ(0, n);
  22180. EXPECT_EQ("Hello", body);
  22181. }
  22182. #endif // CPPHTTPLIB_SSL_ENABLED
  22183. //==============================================================================
  22184. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  22185. // results for various scenarios.
  22186. //==============================================================================
  22187. TEST(ParityTest, GetVsOpenStream) {
  22188. Server svr;
  22189. const std::string path = "/parity";
  22190. const std::string content = "Parity test content: hello world";
  22191. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22192. res.set_content(content, "text/plain");
  22193. });
  22194. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22195. auto se = detail::scope_exit([&] {
  22196. svr.stop();
  22197. t.join();
  22198. ASSERT_FALSE(svr.is_running());
  22199. });
  22200. svr.wait_until_ready();
  22201. Client cli(HOST, PORT);
  22202. // Non-stream path
  22203. auto r1 = cli.Get(path);
  22204. ASSERT_TRUE(r1);
  22205. EXPECT_EQ(StatusCode::OK_200, r1->status);
  22206. // Stream path
  22207. auto h = cli.open_stream("GET", path);
  22208. ASSERT_TRUE(h.is_valid());
  22209. EXPECT_EQ(r1->body, read_all(h));
  22210. }
  22211. // Helper to compress data with provided compressor type T
  22212. template <typename Compressor>
  22213. static std::string compress_payload_for_parity(const std::string &in) {
  22214. std::string out;
  22215. Compressor compressor;
  22216. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  22217. [&](const char *data, size_t n) {
  22218. out.append(data, n);
  22219. return true;
  22220. });
  22221. EXPECT_TRUE(ok);
  22222. return out;
  22223. }
  22224. // Helper function for compression parity tests
  22225. template <typename Compressor>
  22226. static void test_compression_parity(const std::string &original,
  22227. const std::string &path,
  22228. const std::string &encoding) {
  22229. const std::string compressed =
  22230. compress_payload_for_parity<Compressor>(original);
  22231. Server svr;
  22232. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22233. res.set_content(compressed, "application/octet-stream");
  22234. res.set_header("Content-Encoding", encoding);
  22235. });
  22236. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  22237. auto se = detail::scope_exit([&] {
  22238. svr.stop();
  22239. t.join();
  22240. ASSERT_FALSE(svr.is_running());
  22241. });
  22242. svr.wait_until_ready();
  22243. Client cli(HOST, PORT);
  22244. // Non-streaming
  22245. {
  22246. auto res = cli.Get(path);
  22247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22248. EXPECT_EQ(StatusCode::OK_200, res->status);
  22249. EXPECT_EQ(original, res->body);
  22250. }
  22251. // Streaming
  22252. {
  22253. auto h = cli.open_stream("GET", path);
  22254. ASSERT_TRUE(h.is_valid());
  22255. EXPECT_EQ(original, read_all(h));
  22256. }
  22257. }
  22258. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22259. TEST(ParityTest, Gzip) {
  22260. test_compression_parity<detail::gzip_compressor>(
  22261. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  22262. }
  22263. #endif
  22264. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22265. TEST(ParityTest, Brotli) {
  22266. test_compression_parity<detail::brotli_compressor>(
  22267. "Hello, brotli parity test payload", "/parity-br", "br");
  22268. }
  22269. #endif
  22270. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22271. TEST(ParityTest, Zstd) {
  22272. test_compression_parity<detail::zstd_compressor>(
  22273. "Zstandard parity test payload", "/parity-zstd", "zstd");
  22274. }
  22275. #endif
  22276. //==============================================================================
  22277. // New Stream API Tests
  22278. //==============================================================================
  22279. inline std::string read_body(httplib::stream::Result &result) {
  22280. std::string body;
  22281. while (result.next()) {
  22282. body.append(result.data(), result.size());
  22283. }
  22284. return body;
  22285. }
  22286. TEST(ClientConnectionTest, Basic) {
  22287. httplib::ClientConnection conn;
  22288. EXPECT_FALSE(conn.is_open());
  22289. conn.sock = 1;
  22290. EXPECT_TRUE(conn.is_open());
  22291. httplib::ClientConnection conn2(std::move(conn));
  22292. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  22293. conn2.sock = INVALID_SOCKET;
  22294. }
  22295. // Unified test server for all stream::* tests
  22296. class StreamApiTest : public ::testing::Test {
  22297. protected:
  22298. void SetUp() override {
  22299. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22300. res.set_content("Hello World!", "text/plain");
  22301. });
  22302. svr_.Get("/echo-params",
  22303. [](const httplib::Request &req, httplib::Response &res) {
  22304. std::string r;
  22305. for (const auto &p : req.params) {
  22306. if (!r.empty()) r += "&";
  22307. r += p.first + "=" + p.second;
  22308. }
  22309. res.set_content(r, "text/plain");
  22310. });
  22311. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22312. res.set_content(req.body, req.get_header_value("Content-Type"));
  22313. });
  22314. svr_.Post("/echo-headers",
  22315. [](const httplib::Request &req, httplib::Response &res) {
  22316. std::string r;
  22317. for (const auto &h : req.headers)
  22318. r += h.first + ": " + h.second + "\n";
  22319. res.set_content(r, "text/plain");
  22320. });
  22321. svr_.Post("/echo-params",
  22322. [](const httplib::Request &req, httplib::Response &res) {
  22323. std::string r = "params:";
  22324. for (const auto &p : req.params)
  22325. r += p.first + "=" + p.second + ";";
  22326. res.set_content(r + " body:" + req.body, "text/plain");
  22327. });
  22328. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22329. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22330. });
  22331. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22332. res.set_content("PUT:" + req.body, "text/plain");
  22333. });
  22334. svr_.Patch("/echo",
  22335. [](const httplib::Request &req, httplib::Response &res) {
  22336. res.set_content("PATCH:" + req.body, "text/plain");
  22337. });
  22338. svr_.Delete(
  22339. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22340. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22341. "text/plain");
  22342. });
  22343. svr_.Get("/head-test",
  22344. [](const httplib::Request &, httplib::Response &res) {
  22345. res.set_content("body for HEAD", "text/plain");
  22346. });
  22347. svr_.Options("/options",
  22348. [](const httplib::Request &, httplib::Response &res) {
  22349. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22350. });
  22351. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22352. svr_.wait_until_ready();
  22353. }
  22354. void TearDown() override {
  22355. svr_.stop();
  22356. if (thread_.joinable()) thread_.join();
  22357. }
  22358. httplib::Server svr_;
  22359. std::thread thread_;
  22360. };
  22361. // stream::Get tests
  22362. TEST_F(StreamApiTest, GetBasic) {
  22363. httplib::Client cli(HOST, PORT);
  22364. auto result = httplib::stream::Get(cli, "/hello");
  22365. ASSERT_TRUE(result.is_valid());
  22366. EXPECT_EQ(200, result.status());
  22367. EXPECT_EQ("Hello World!", read_body(result));
  22368. }
  22369. TEST_F(StreamApiTest, GetWithParams) {
  22370. httplib::Client cli(HOST, PORT);
  22371. httplib::Params params{{"foo", "bar"}};
  22372. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22373. ASSERT_TRUE(result.is_valid());
  22374. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22375. }
  22376. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22377. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22378. httplib::Client cli(HOST, PORT);
  22379. cli.set_payload_max_length(0);
  22380. auto result = httplib::stream::Get(cli, "/hello");
  22381. ASSERT_TRUE(result.is_valid());
  22382. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22383. EXPECT_EQ("Hello World!", read_body(result));
  22384. }
  22385. #endif
  22386. TEST_F(StreamApiTest, GetConnectionError) {
  22387. httplib::Client cli(HOST, 9999);
  22388. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22389. }
  22390. TEST_F(StreamApiTest, Get404) {
  22391. httplib::Client cli(HOST, PORT);
  22392. auto result = httplib::stream::Get(cli, "/nonexistent");
  22393. EXPECT_TRUE(result.is_valid());
  22394. EXPECT_EQ(404, result.status());
  22395. }
  22396. // stream::Post tests
  22397. TEST_F(StreamApiTest, PostBasic) {
  22398. httplib::Client cli(HOST, PORT);
  22399. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22400. "application/json");
  22401. ASSERT_TRUE(result.is_valid());
  22402. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22403. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22404. }
  22405. TEST_F(StreamApiTest, PostWithHeaders) {
  22406. httplib::Client cli(HOST, PORT);
  22407. httplib::Headers headers{{"X-Custom", "value"}};
  22408. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22409. "text/plain");
  22410. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22411. }
  22412. TEST_F(StreamApiTest, PostWithParams) {
  22413. httplib::Client cli(HOST, PORT);
  22414. httplib::Params params{{"k", "v"}};
  22415. auto result =
  22416. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22417. auto body = read_body(result);
  22418. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22419. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22420. }
  22421. TEST_F(StreamApiTest, PostLarge) {
  22422. httplib::Client cli(HOST, PORT);
  22423. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22424. size_t total = 0;
  22425. while (result.next()) {
  22426. total += result.size();
  22427. }
  22428. EXPECT_EQ(100u * 1024u, total);
  22429. }
  22430. // stream::Put/Patch tests
  22431. TEST_F(StreamApiTest, PutAndPatch) {
  22432. httplib::Client cli(HOST, PORT);
  22433. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22434. EXPECT_EQ("PUT:test", read_body(put));
  22435. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22436. EXPECT_EQ("PATCH:test", read_body(patch));
  22437. }
  22438. // stream::Delete tests
  22439. TEST_F(StreamApiTest, Delete) {
  22440. httplib::Client cli(HOST, PORT);
  22441. auto del1 = httplib::stream::Delete(cli, "/resource");
  22442. EXPECT_EQ("Deleted", read_body(del1));
  22443. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22444. EXPECT_EQ("Deleted:data", read_body(del2));
  22445. }
  22446. // stream::Head/Options tests
  22447. TEST_F(StreamApiTest, HeadAndOptions) {
  22448. httplib::Client cli(HOST, PORT);
  22449. auto head = httplib::stream::Head(cli, "/head-test");
  22450. EXPECT_TRUE(head.is_valid());
  22451. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22452. auto opts = httplib::stream::Options(cli, "/options");
  22453. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22454. }
  22455. // SSL stream::* tests
  22456. #ifdef CPPHTTPLIB_SSL_ENABLED
  22457. class SSLStreamApiTest : public ::testing::Test {
  22458. protected:
  22459. void SetUp() override {
  22460. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22461. res.set_content("Hello SSL!", "text/plain");
  22462. });
  22463. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22464. res.set_content(req.body, "text/plain");
  22465. });
  22466. port_ = svr_.bind_to_any_port("127.0.0.1");
  22467. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22468. svr_.wait_until_ready();
  22469. }
  22470. void TearDown() override {
  22471. svr_.stop();
  22472. if (thread_.joinable()) thread_.join();
  22473. }
  22474. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22475. std::thread thread_;
  22476. int port_ = 0;
  22477. };
  22478. TEST_F(SSLStreamApiTest, GetAndPost) {
  22479. httplib::SSLClient cli("127.0.0.1", port_);
  22480. cli.enable_server_certificate_verification(false);
  22481. auto get = httplib::stream::Get(cli, "/hello");
  22482. EXPECT_EQ("Hello SSL!", read_body(get));
  22483. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22484. EXPECT_EQ("test", read_body(post));
  22485. }
  22486. #endif
  22487. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22488. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22489. // BodyReader
  22490. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22491. // Test that read timeout during streaming is detected
  22492. // Use a large content-length response where server delays mid-stream
  22493. Server svr;
  22494. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22495. // Send a large response with delay in the middle
  22496. res.set_content_provider(
  22497. 1000, // content_length
  22498. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22499. if (offset < 100) {
  22500. // Send first 100 bytes immediately
  22501. std::string data(100, 'A');
  22502. sink.write(data.c_str(), data.size());
  22503. return true;
  22504. }
  22505. // Then delay longer than client timeout
  22506. std::this_thread::sleep_for(std::chrono::seconds(3));
  22507. std::string data(900, 'B');
  22508. sink.write(data.c_str(), data.size());
  22509. return true;
  22510. });
  22511. });
  22512. auto port = 8091;
  22513. std::thread t([&]() { svr.listen("localhost", port); });
  22514. svr.wait_until_ready();
  22515. Client cli("localhost", port);
  22516. cli.set_read_timeout(1, 0); // 1 second timeout
  22517. auto handle = cli.open_stream("GET", "/slow-stream");
  22518. ASSERT_TRUE(handle.is_valid());
  22519. char buf[256];
  22520. ssize_t total = 0;
  22521. ssize_t n;
  22522. bool got_error = false;
  22523. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22524. total += n;
  22525. }
  22526. if (n < 0) {
  22527. got_error = true;
  22528. // Should be timeout or read error
  22529. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22530. handle.get_read_error() == Error::Read)
  22531. << "Actual error: " << to_string(handle.get_read_error());
  22532. }
  22533. // Either we got an error, or we got less data than expected
  22534. EXPECT_TRUE(got_error || total < 1000)
  22535. << "Expected timeout but got all " << total << " bytes";
  22536. svr.stop();
  22537. t.join();
  22538. }
  22539. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22540. // Test connection closed detection via BodyReader
  22541. Server svr;
  22542. std::atomic<bool> close_now{false};
  22543. svr.Get("/will-close", [&](const Request &, Response &res) {
  22544. res.set_content_provider(
  22545. 10000, // Large content_length that we won't fully send
  22546. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22547. if (offset < 100) {
  22548. std::string data(100, 'X');
  22549. sink.write(data.c_str(), data.size());
  22550. return true;
  22551. }
  22552. // Wait for signal then abort
  22553. while (!close_now) {
  22554. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22555. }
  22556. return false; // Abort - server will close connection
  22557. });
  22558. });
  22559. auto port = 8092;
  22560. std::thread t([&]() { svr.listen("localhost", port); });
  22561. svr.wait_until_ready();
  22562. Client cli("localhost", port);
  22563. auto handle = cli.open_stream("GET", "/will-close");
  22564. ASSERT_TRUE(handle.is_valid());
  22565. char buf[256];
  22566. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22567. EXPECT_GT(n, 0) << "First read should succeed";
  22568. // Signal server to close
  22569. close_now = true;
  22570. // Keep reading until error or EOF
  22571. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22572. // Keep reading
  22573. }
  22574. // Should get an error since content_length wasn't satisfied
  22575. if (n < 0) {
  22576. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22577. handle.get_read_error() == Error::Read)
  22578. << "Actual error: " << to_string(handle.get_read_error());
  22579. }
  22580. svr.stop();
  22581. t.join();
  22582. }
  22583. #ifdef CPPHTTPLIB_SSL_ENABLED
  22584. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22585. // Test that read timeout during SSL streaming is detected
  22586. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22587. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22588. res.set_content_provider(
  22589. 1000, "text/plain",
  22590. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22591. if (offset < 100) {
  22592. std::string data(100, 'A');
  22593. sink.write(data.c_str(), data.size());
  22594. return true;
  22595. }
  22596. std::this_thread::sleep_for(std::chrono::seconds(3));
  22597. std::string data(900, 'B');
  22598. sink.write(data.c_str(), data.size());
  22599. return true;
  22600. });
  22601. });
  22602. auto port = 8093;
  22603. std::thread t([&]() { svr.listen("localhost", port); });
  22604. svr.wait_until_ready();
  22605. SSLClient cli("localhost", port);
  22606. cli.enable_server_certificate_verification(false);
  22607. cli.set_read_timeout(1, 0); // 1 second timeout
  22608. auto handle = cli.open_stream("GET", "/slow-stream");
  22609. ASSERT_TRUE(handle.is_valid());
  22610. char buf[256];
  22611. ssize_t total = 0;
  22612. ssize_t n;
  22613. bool got_error = false;
  22614. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22615. total += n;
  22616. }
  22617. if (n < 0) {
  22618. got_error = true;
  22619. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22620. handle.get_read_error() == Error::Read)
  22621. << "Actual error: " << to_string(handle.get_read_error());
  22622. }
  22623. EXPECT_TRUE(got_error || total < 1000)
  22624. << "Expected timeout but got all " << total << " bytes";
  22625. svr.stop();
  22626. t.join();
  22627. }
  22628. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22629. // Test SSL connection closed detection
  22630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22631. std::atomic<bool> close_now{false};
  22632. svr.Get("/will-close", [&](const Request &, Response &res) {
  22633. res.set_content_provider(
  22634. 10000, "text/plain",
  22635. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22636. if (offset < 100) {
  22637. std::string data(100, 'X');
  22638. sink.write(data.c_str(), data.size());
  22639. return true;
  22640. }
  22641. while (!close_now) {
  22642. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22643. }
  22644. return false;
  22645. });
  22646. });
  22647. auto port = 8094;
  22648. std::thread t([&]() { svr.listen("localhost", port); });
  22649. svr.wait_until_ready();
  22650. SSLClient cli("localhost", port);
  22651. cli.enable_server_certificate_verification(false);
  22652. auto handle = cli.open_stream("GET", "/will-close");
  22653. ASSERT_TRUE(handle.is_valid());
  22654. char buf[256];
  22655. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22656. EXPECT_GT(n, 0);
  22657. // Signal server to close
  22658. close_now = true;
  22659. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22660. // Keep reading
  22661. }
  22662. if (n < 0) {
  22663. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22664. handle.get_read_error() == Error::Read)
  22665. << "Actual error: " << to_string(handle.get_read_error());
  22666. }
  22667. svr.stop();
  22668. t.join();
  22669. }
  22670. #endif
  22671. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22672. using namespace httplib;
  22673. // Create a test file
  22674. const char *fname = "etag_testfile.txt";
  22675. const char *content = "etag-content";
  22676. {
  22677. std::ofstream ofs(fname);
  22678. ofs << content;
  22679. ASSERT_TRUE(ofs.good());
  22680. }
  22681. Server svr;
  22682. svr.set_mount_point("/static", ".");
  22683. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22684. svr.wait_until_ready();
  22685. Client cli(HOST, PORT);
  22686. // First request: should get 200 with ETag header
  22687. auto res1 = cli.Get("/static/etag_testfile.txt");
  22688. ASSERT_TRUE(res1);
  22689. ASSERT_EQ(200, res1->status);
  22690. ASSERT_TRUE(res1->has_header("ETag"));
  22691. std::string etag = res1->get_header_value("ETag");
  22692. EXPECT_FALSE(etag.empty());
  22693. // Verify ETag format: W/"hex-hex"
  22694. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22695. EXPECT_EQ('W', etag[0]);
  22696. EXPECT_EQ('/', etag[1]);
  22697. EXPECT_EQ('"', etag[2]);
  22698. EXPECT_EQ('"', etag.back());
  22699. // Exact match: expect 304 Not Modified
  22700. Headers h2 = {{"If-None-Match", etag}};
  22701. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22702. ASSERT_TRUE(res2);
  22703. EXPECT_EQ(304, res2->status);
  22704. // Wildcard match: expect 304 Not Modified
  22705. Headers h3 = {{"If-None-Match", "*"}};
  22706. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22707. ASSERT_TRUE(res3);
  22708. EXPECT_EQ(304, res3->status);
  22709. // Non-matching ETag: expect 200
  22710. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22711. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22712. ASSERT_TRUE(res4);
  22713. EXPECT_EQ(200, res4->status);
  22714. // Multiple ETags with one matching: expect 304
  22715. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22716. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22717. ASSERT_TRUE(res5);
  22718. EXPECT_EQ(304, res5->status);
  22719. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22720. // that equivalent to the single comma-separated list above, so the match on
  22721. // the second line must still be found.
  22722. Headers h6;
  22723. h6.emplace("If-None-Match", "W/\"other\"");
  22724. h6.emplace("If-None-Match", etag);
  22725. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22726. ASSERT_TRUE(res6);
  22727. EXPECT_EQ(304, res6->status);
  22728. svr.stop();
  22729. t.join();
  22730. std::remove(fname);
  22731. }
  22732. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22733. using namespace httplib;
  22734. Server svr;
  22735. svr.set_mount_point("/static", ".");
  22736. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22737. svr.wait_until_ready();
  22738. Client cli(HOST, PORT);
  22739. // Send If-None-Match: * to a non-existent file
  22740. Headers h = {{"If-None-Match", "*"}};
  22741. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22743. EXPECT_EQ(404, res->status);
  22744. svr.stop();
  22745. t.join();
  22746. }
  22747. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22748. using namespace httplib;
  22749. // Create a test file
  22750. const char *fname = "etag_boundary_testfile.txt";
  22751. const char *content = "boundary-test";
  22752. {
  22753. std::ofstream ofs(fname);
  22754. ofs << content;
  22755. ASSERT_TRUE(ofs.good());
  22756. }
  22757. Server svr;
  22758. svr.set_mount_point("/static", ".");
  22759. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22760. svr.wait_until_ready();
  22761. Client cli(HOST, PORT);
  22762. // Get the actual ETag
  22763. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22764. ASSERT_TRUE(res1);
  22765. ASSERT_EQ(200, res1->status);
  22766. ASSERT_TRUE(res1->has_header("ETag"));
  22767. std::string etag = res1->get_header_value("ETag");
  22768. // Test 1: Very long ETag value (longer than actual ETag)
  22769. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22770. Headers h1 = {{"If-None-Match", "W/"
  22771. "\"very-long-etag-value-that-is-much-longer-"
  22772. "than-the-actual-etag-value\""}};
  22773. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22774. ASSERT_TRUE(res2);
  22775. EXPECT_EQ(200, res2->status); // Should not match
  22776. // Test 2: Long string followed by wildcard
  22777. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22778. // string)
  22779. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22780. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22781. ASSERT_TRUE(res3);
  22782. EXPECT_EQ(304, res3->status); // Should match on "*"
  22783. // Test 3: Wildcard followed by long string
  22784. // Should match on "*" immediately and return 304
  22785. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22786. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22787. ASSERT_TRUE(res4);
  22788. EXPECT_EQ(304, res4->status); // Should match on "*"
  22789. // Test 4: Multiple long non-matching values
  22790. // Should NOT match and return 200 (test that all comparisons are safe)
  22791. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22792. "W/\"second-long-non-matching-value\", "
  22793. "W/\"third-long-non-matching-value\""}};
  22794. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22795. ASSERT_TRUE(res5);
  22796. EXPECT_EQ(200, res5->status); // Should not match
  22797. // Test 5: Single character that is not "*" (edge case)
  22798. Headers h5 = {{"If-None-Match", "X"}};
  22799. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22800. ASSERT_TRUE(res6);
  22801. EXPECT_EQ(200, res6->status); // Should not match
  22802. svr.stop();
  22803. t.join();
  22804. std::remove(fname);
  22805. }
  22806. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22807. using namespace httplib;
  22808. // Create a test file
  22809. const char *fname = "ims_testfile.txt";
  22810. const char *content = "if-modified-since-test";
  22811. {
  22812. std::ofstream ofs(fname);
  22813. ofs << content;
  22814. ASSERT_TRUE(ofs.good());
  22815. }
  22816. Server svr;
  22817. svr.set_mount_point("/static", ".");
  22818. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22819. svr.wait_until_ready();
  22820. Client cli(HOST, PORT);
  22821. // First request: should get 200 with Last-Modified header
  22822. auto res1 = cli.Get("/static/ims_testfile.txt");
  22823. ASSERT_TRUE(res1);
  22824. ASSERT_EQ(200, res1->status);
  22825. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22826. std::string last_modified = res1->get_header_value("Last-Modified");
  22827. EXPECT_FALSE(last_modified.empty());
  22828. // If-Modified-Since with same time: expect 304
  22829. Headers h2 = {{"If-Modified-Since", last_modified}};
  22830. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22831. ASSERT_TRUE(res2);
  22832. EXPECT_EQ(304, res2->status);
  22833. // If-Modified-Since with future time: expect 304
  22834. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22835. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22836. ASSERT_TRUE(res3);
  22837. EXPECT_EQ(304, res3->status);
  22838. // If-Modified-Since with past time: expect 200
  22839. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22840. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22841. ASSERT_TRUE(res4);
  22842. EXPECT_EQ(200, res4->status);
  22843. // If-None-Match takes precedence over If-Modified-Since
  22844. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22845. ASSERT_TRUE(res1->has_header("ETag"));
  22846. std::string etag = res1->get_header_value("ETag");
  22847. Headers h5 = {{"If-None-Match", etag},
  22848. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22849. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22850. ASSERT_TRUE(res5);
  22851. EXPECT_EQ(304, res5->status);
  22852. svr.stop();
  22853. t.join();
  22854. std::remove(fname);
  22855. }
  22856. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22857. using namespace httplib;
  22858. Server svr;
  22859. // Endpoint that returns compressible content
  22860. svr.Get("/compressible", [](const Request &, Response &res) {
  22861. // Return a large enough body to trigger compression
  22862. std::string body(1000, 'a');
  22863. res.set_content(body, "text/plain");
  22864. });
  22865. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22866. svr.wait_until_ready();
  22867. Client cli(HOST, PORT);
  22868. // Request with gzip support: should get Vary header when compressed
  22869. cli.set_compress(true);
  22870. auto res1 = cli.Get("/compressible");
  22871. ASSERT_TRUE(res1);
  22872. EXPECT_EQ(200, res1->status);
  22873. // If Content-Encoding is set, Vary should also be set
  22874. if (res1->has_header("Content-Encoding")) {
  22875. EXPECT_TRUE(res1->has_header("Vary"));
  22876. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22877. }
  22878. // Request without Accept-Encoding header: should not have compression
  22879. Headers h_no_compress;
  22880. auto res2 = cli.Get("/compressible", h_no_compress);
  22881. ASSERT_TRUE(res2);
  22882. EXPECT_EQ(200, res2->status);
  22883. // Verify Vary header is present when compression is applied
  22884. // (the exact behavior depends on server configuration)
  22885. svr.stop();
  22886. t.join();
  22887. }
  22888. TEST(ETagTest, IfRangeWithETag) {
  22889. using namespace httplib;
  22890. // Create a test file with known content
  22891. const char *fname = "if_range_testfile.txt";
  22892. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22893. {
  22894. std::ofstream ofs(fname);
  22895. ofs << content;
  22896. ASSERT_TRUE(ofs.good());
  22897. }
  22898. Server svr;
  22899. svr.set_mount_point("/static", ".");
  22900. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22901. svr.wait_until_ready();
  22902. Client cli(HOST, PORT);
  22903. // First request: get ETag
  22904. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22905. ASSERT_TRUE(res1);
  22906. ASSERT_EQ(200, res1->status);
  22907. ASSERT_TRUE(res1->has_header("ETag"));
  22908. std::string etag = res1->get_header_value("ETag");
  22909. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22910. // Since our server generates weak ETags (W/"..."), If-Range with our
  22911. // ETag should NOT result in partial content - it should return full content.
  22912. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22913. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22914. ASSERT_TRUE(res2);
  22915. // Weak ETag in If-Range -> full content (200), not partial (206)
  22916. EXPECT_EQ(200, res2->status);
  22917. EXPECT_EQ(content, res2->body);
  22918. EXPECT_FALSE(res2->has_header("Content-Range"));
  22919. // Range request with non-matching If-Range (ETag): should get 200 (full
  22920. // content)
  22921. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22922. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22923. ASSERT_TRUE(res3);
  22924. EXPECT_EQ(200, res3->status);
  22925. EXPECT_EQ(content, res3->body);
  22926. EXPECT_FALSE(res3->has_header("Content-Range"));
  22927. // Range request with strong ETag (hypothetical - our server doesn't generate
  22928. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22929. // should return full content)
  22930. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22931. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22932. ASSERT_TRUE(res4);
  22933. EXPECT_EQ(200, res4->status);
  22934. EXPECT_EQ(content, res4->body);
  22935. EXPECT_FALSE(res4->has_header("Content-Range"));
  22936. svr.stop();
  22937. t.join();
  22938. std::remove(fname);
  22939. }
  22940. TEST(ETagTest, IfRangeWithDate) {
  22941. using namespace httplib;
  22942. // Create a test file
  22943. const char *fname = "if_range_date_testfile.txt";
  22944. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22945. {
  22946. std::ofstream ofs(fname);
  22947. ofs << content;
  22948. ASSERT_TRUE(ofs.good());
  22949. }
  22950. Server svr;
  22951. svr.set_mount_point("/static", ".");
  22952. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22953. svr.wait_until_ready();
  22954. Client cli(HOST, PORT);
  22955. // First request: get Last-Modified
  22956. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22957. ASSERT_TRUE(res1);
  22958. ASSERT_EQ(200, res1->status);
  22959. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22960. std::string last_modified = res1->get_header_value("Last-Modified");
  22961. // Range request with matching If-Range (date): should get 206
  22962. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22963. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22964. ASSERT_TRUE(res2);
  22965. EXPECT_EQ(206, res2->status);
  22966. EXPECT_EQ("FGHIJ", res2->body);
  22967. // Range request with old If-Range date: should get 200 (full content)
  22968. Headers h3 = {{"Range", "bytes=5-9"},
  22969. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22970. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22971. ASSERT_TRUE(res3);
  22972. EXPECT_EQ(200, res3->status);
  22973. EXPECT_EQ(content, res3->body);
  22974. // Range request with future If-Range date: should get 200 (full content)
  22975. Headers h4 = {{"Range", "bytes=0-4"},
  22976. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22977. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22978. ASSERT_TRUE(res4);
  22979. EXPECT_EQ(200, res4->status);
  22980. EXPECT_EQ(content, res4->body);
  22981. #if defined(__APPLE__) || defined(__linux__)
  22982. // File replaced by one with an older mtime: should get 200 (full content)
  22983. const std::string replaced = "abcdefghij9876543210";
  22984. {
  22985. std::ofstream ofs(fname);
  22986. ofs << replaced;
  22987. ASSERT_TRUE(ofs.good());
  22988. }
  22989. struct timeval times[2];
  22990. times[0].tv_sec = time(nullptr);
  22991. times[0].tv_usec = 0;
  22992. times[1].tv_sec = time(nullptr) - 3600;
  22993. times[1].tv_usec = 0;
  22994. ASSERT_EQ(0, utimes(fname, times));
  22995. Headers h5 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22996. auto res5 = cli.Get("/static/if_range_date_testfile.txt", h5);
  22997. ASSERT_TRUE(res5);
  22998. EXPECT_EQ(200, res5->status);
  22999. EXPECT_EQ(replaced, res5->body);
  23000. #endif
  23001. svr.stop();
  23002. t.join();
  23003. std::remove(fname);
  23004. }
  23005. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  23006. using namespace httplib;
  23007. const char *fname = "etag_malformed.txt";
  23008. const char *content = "malformed-etag";
  23009. {
  23010. std::ofstream ofs(fname);
  23011. ofs << content;
  23012. ASSERT_TRUE(ofs.good());
  23013. }
  23014. Server svr;
  23015. svr.set_mount_point("/static", ".");
  23016. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23017. svr.wait_until_ready();
  23018. Client cli(HOST, PORT);
  23019. // baseline: should get 200 and an ETag
  23020. auto res1 = cli.Get("/static/etag_malformed.txt");
  23021. ASSERT_TRUE(res1);
  23022. ASSERT_EQ(200, res1->status);
  23023. ASSERT_TRUE(res1->has_header("ETag"));
  23024. // Malformed ETag value (missing quotes) should be treated as non-matching
  23025. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  23026. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  23027. ASSERT_TRUE(res_bad);
  23028. EXPECT_EQ(200, res_bad->status);
  23029. // Whitespace-only header value should be considered invalid / non-matching
  23030. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  23031. "Host: localhost\r\n"
  23032. "If-None-Match: \r\n"
  23033. "Connection: close\r\n"
  23034. "\r\n";
  23035. std::string out;
  23036. ASSERT_TRUE(send_request(5, raw_req, &out));
  23037. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  23038. svr.stop();
  23039. t.join();
  23040. std::remove(fname);
  23041. }
  23042. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  23043. using namespace httplib;
  23044. const char *fname = "ims_invalid_format.txt";
  23045. const char *content = "ims-bad-format";
  23046. {
  23047. std::ofstream ofs(fname);
  23048. ofs << content;
  23049. ASSERT_TRUE(ofs.good());
  23050. }
  23051. Server svr;
  23052. svr.set_mount_point("/static", ".");
  23053. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23054. svr.wait_until_ready();
  23055. Client cli(HOST, PORT);
  23056. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  23057. ASSERT_TRUE(res1);
  23058. ASSERT_EQ(200, res1->status);
  23059. ASSERT_TRUE(res1->has_header("Last-Modified"));
  23060. // If-Modified-Since with invalid format should not result in 304
  23061. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  23062. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  23063. ASSERT_TRUE(res_bad);
  23064. EXPECT_EQ(200, res_bad->status);
  23065. // If-Range with invalid date format should be treated as mismatch -> full
  23066. // content (200)
  23067. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  23068. {"If-Range", "invalid-date"}};
  23069. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  23070. ASSERT_TRUE(res_ifrange);
  23071. EXPECT_EQ(200, res_ifrange->status);
  23072. svr.stop();
  23073. t.join();
  23074. std::remove(fname);
  23075. }
  23076. TEST(ETagTest, IfRangeWithMalformedETag) {
  23077. using namespace httplib;
  23078. const char *fname = "ifrange_malformed.txt";
  23079. const std::string content = "0123456789";
  23080. {
  23081. std::ofstream ofs(fname);
  23082. ofs << content;
  23083. ASSERT_TRUE(ofs.good());
  23084. }
  23085. Server svr;
  23086. svr.set_mount_point("/static", ".");
  23087. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23088. svr.wait_until_ready();
  23089. Client cli(HOST, PORT);
  23090. // First request: get ETag
  23091. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  23092. ASSERT_TRUE(res1);
  23093. ASSERT_EQ(200, res1->status);
  23094. ASSERT_TRUE(res1->has_header("ETag"));
  23095. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  23096. // full content (200)
  23097. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  23098. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  23099. ASSERT_TRUE(res2);
  23100. EXPECT_EQ(200, res2->status);
  23101. EXPECT_EQ(content, res2->body);
  23102. svr.stop();
  23103. t.join();
  23104. std::remove(fname);
  23105. }
  23106. TEST(ETagTest, ExtremeLargeDateValues) {
  23107. using namespace httplib;
  23108. const char *fname = "ims_extreme_date.txt";
  23109. const char *content = "ims-extreme-date";
  23110. {
  23111. std::ofstream ofs(fname);
  23112. ofs << content;
  23113. ASSERT_TRUE(ofs.good());
  23114. }
  23115. Server svr;
  23116. svr.set_mount_point("/static", ".");
  23117. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23118. svr.wait_until_ready();
  23119. Client cli(HOST, PORT);
  23120. auto res1 = cli.Get(std::string("/static/") + fname);
  23121. ASSERT_TRUE(res1);
  23122. ASSERT_EQ(200, res1->status);
  23123. ASSERT_TRUE(res1->has_header("Last-Modified"));
  23124. // Extremely large year that may overflow date parsing routines.
  23125. Headers h_large_date = {
  23126. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  23127. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  23128. ASSERT_TRUE(res_bad);
  23129. // Expect server to treat this as invalid/mismatch and return full content
  23130. EXPECT_EQ(200, res_bad->status);
  23131. // If-Range with extremely large date should be treated as mismatch -> full
  23132. // content (200)
  23133. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  23134. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  23135. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  23136. ASSERT_TRUE(res_ifrange);
  23137. EXPECT_EQ(200, res_ifrange->status);
  23138. svr.stop();
  23139. t.join();
  23140. std::remove(fname);
  23141. }
  23142. TEST(ETagTest, NegativeFileModificationTime) {
  23143. using namespace httplib;
  23144. const char *fname = "ims_negative_mtime.txt";
  23145. const std::string content = "negative-mtime";
  23146. {
  23147. std::ofstream ofs(fname);
  23148. ofs << content;
  23149. ASSERT_TRUE(ofs.good());
  23150. }
  23151. // Try to set file mtime to a negative value. This may fail on some
  23152. // platforms/filesystems; if it fails, the test will still verify server
  23153. // behaves safely by performing a regular conditional request.
  23154. #if defined(__APPLE__) || defined(__linux__)
  23155. bool set_negative = false;
  23156. do {
  23157. struct timeval times[2];
  23158. // access time: now
  23159. times[0].tv_sec = time(nullptr);
  23160. times[0].tv_usec = 0;
  23161. // modification time: negative (e.g., -1)
  23162. times[1].tv_sec = -1;
  23163. times[1].tv_usec = 0;
  23164. if (utimes(fname, times) == 0) { set_negative = true; }
  23165. } while (0);
  23166. #else
  23167. bool set_negative = false;
  23168. #endif
  23169. Server svr;
  23170. svr.set_mount_point("/static", ".");
  23171. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  23172. svr.wait_until_ready();
  23173. Client cli(HOST, PORT);
  23174. auto res1 = cli.Get(std::string("/static/") + fname);
  23175. ASSERT_TRUE(res1);
  23176. ASSERT_EQ(200, res1->status);
  23177. bool has_last_modified = res1->has_header("Last-Modified");
  23178. std::string last_modified;
  23179. if (has_last_modified) {
  23180. last_modified = res1->get_header_value("Last-Modified");
  23181. }
  23182. if (set_negative) {
  23183. // If we successfully set a negative mtime, ensure server returns a
  23184. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  23185. // with an old date and ensure server handles it without crash.
  23186. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  23187. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  23188. ASSERT_TRUE(res2);
  23189. // Behavior may vary; at minimum ensure server responds (200 or 304).
  23190. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  23191. } else {
  23192. // Could not set negative mtime on this platform; fall back to verifying
  23193. // that normal invalid/malformed dates are treated safely (non-304).
  23194. Headers h_bad_date = {
  23195. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  23196. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  23197. ASSERT_TRUE(res_bad);
  23198. EXPECT_EQ(200, res_bad->status);
  23199. }
  23200. svr.stop();
  23201. t.join();
  23202. std::remove(fname);
  23203. }
  23204. //==============================================================================
  23205. // Integration Tests with Server
  23206. //==============================================================================
  23207. class SSEIntegrationTest : public ::testing::Test {
  23208. protected:
  23209. void SetUp() override {
  23210. stop_server_.store(false);
  23211. events_.clear();
  23212. server_ = httplib::detail::make_unique<Server>();
  23213. setup_server();
  23214. start_server();
  23215. }
  23216. void TearDown() override {
  23217. stop_server_.store(true);
  23218. event_cv_.notify_all();
  23219. server_->stop();
  23220. if (server_thread_.joinable()) { server_thread_.join(); }
  23221. }
  23222. void setup_server() {
  23223. // Simple SSE endpoint
  23224. server_->Get("/events", [this](const Request &req, Response &res) {
  23225. auto last_id = req.get_header_value("Last-Event-ID");
  23226. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  23227. res.set_chunked_content_provider(
  23228. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  23229. std::unique_lock<std::mutex> lock(event_mutex_);
  23230. if (event_cv_.wait_for(
  23231. lock, std::chrono::milliseconds(200), [this] {
  23232. return !events_.empty() || stop_server_.load();
  23233. })) {
  23234. if (stop_server_.load()) { return false; }
  23235. if (!events_.empty()) {
  23236. std::string event = events_.front();
  23237. events_.erase(events_.begin());
  23238. sink.write(event.data(), event.size());
  23239. return true;
  23240. }
  23241. }
  23242. return !stop_server_.load();
  23243. });
  23244. });
  23245. // Endpoint that returns error
  23246. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  23247. res.status = 500;
  23248. res.set_content("Internal Server Error", "text/plain");
  23249. });
  23250. // Endpoint for custom event types
  23251. server_->Get("/custom-events", [](const Request &, Response &res) {
  23252. res.set_chunked_content_provider(
  23253. "text/event-stream", [](size_t offset, DataSink &sink) {
  23254. if (offset == 0) {
  23255. std::string event = "event: update\ndata: updated\n\n"
  23256. "event: delete\ndata: deleted\n\n";
  23257. sink.write(event.data(), event.size());
  23258. }
  23259. return false; // End stream after sending
  23260. });
  23261. });
  23262. }
  23263. void start_server() {
  23264. port_ = server_->bind_to_any_port(HOST);
  23265. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23266. // Wait for server to start
  23267. while (!server_->is_running()) {
  23268. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23269. }
  23270. }
  23271. int get_port() const { return port_; }
  23272. void send_event(const std::string &event) {
  23273. std::lock_guard<std::mutex> lock(event_mutex_);
  23274. events_.push_back(event);
  23275. event_cv_.notify_all();
  23276. }
  23277. std::unique_ptr<Server> server_;
  23278. std::thread server_thread_;
  23279. std::mutex event_mutex_;
  23280. std::condition_variable event_cv_;
  23281. std::vector<std::string> events_;
  23282. std::atomic<bool> stop_server_{false};
  23283. std::string last_received_event_id_;
  23284. int port_ = 0;
  23285. };
  23286. //==============================================================================
  23287. // SSE Parser Tests
  23288. //==============================================================================
  23289. struct SSEParseResult {
  23290. std::vector<sse::SSEMessage> events;
  23291. std::vector<std::string> ids;
  23292. std::vector<int> retries;
  23293. bool ok = true;
  23294. std::string trace; // Every handler call in order
  23295. };
  23296. static SSEParseResult
  23297. sse_parse(const std::vector<std::string> &chunks,
  23298. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  23299. SSEParseResult r;
  23300. detail::SSEParser parser(
  23301. [&](const sse::SSEMessage &msg) {
  23302. r.events.push_back(msg);
  23303. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  23304. },
  23305. [&](const std::string &id) {
  23306. r.ids.push_back(id);
  23307. r.trace += "id[" + id + "]";
  23308. },
  23309. [&](int retry_ms) {
  23310. r.retries.push_back(retry_ms);
  23311. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  23312. },
  23313. max_event_length);
  23314. for (const auto &chunk : chunks) {
  23315. if (!parser.parse(chunk.data(), chunk.size())) {
  23316. r.ok = false;
  23317. break;
  23318. }
  23319. }
  23320. return r;
  23321. }
  23322. static SSEParseResult sse_parse(const std::string &stream) {
  23323. return sse_parse(std::vector<std::string>{stream});
  23324. }
  23325. TEST(SSEParserTest, SingleLineData) {
  23326. auto r = sse_parse("data: hello\n\n");
  23327. ASSERT_EQ(r.events.size(), 1u);
  23328. EXPECT_EQ(r.events[0].data, "hello");
  23329. EXPECT_EQ(r.events[0].event, "message");
  23330. }
  23331. TEST(SSEParserTest, MultiLineData) {
  23332. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  23333. ASSERT_EQ(r.events.size(), 1u);
  23334. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23335. }
  23336. TEST(SSEParserTest, CustomEventType) {
  23337. auto r = sse_parse("event: update\ndata: payload\n\n");
  23338. ASSERT_EQ(r.events.size(), 1u);
  23339. EXPECT_EQ(r.events[0].event, "update");
  23340. EXPECT_EQ(r.events[0].data, "payload");
  23341. }
  23342. TEST(SSEParserTest, EventIdHandling) {
  23343. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23344. ASSERT_EQ(r.events.size(), 1u);
  23345. EXPECT_EQ(r.events[0].id, "12345");
  23346. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23347. }
  23348. TEST(SSEParserTest, EmptyEventId) {
  23349. auto r = sse_parse("id:\ndata: test\n\n");
  23350. ASSERT_EQ(r.events.size(), 1u);
  23351. EXPECT_EQ(r.events[0].id, "");
  23352. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23353. }
  23354. TEST(SSEParserTest, CommentsIgnored) {
  23355. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23356. ASSERT_EQ(r.events.size(), 1u);
  23357. EXPECT_EQ(r.events[0].data, "hello");
  23358. EXPECT_EQ(r.events[0].event, "message");
  23359. }
  23360. TEST(SSEParserTest, ColonInValue) {
  23361. auto r = sse_parse("data: hello:world:test\n\n");
  23362. ASSERT_EQ(r.events.size(), 1u);
  23363. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23364. }
  23365. TEST(SSEParserTest, FieldNameOnly) {
  23366. // A line without a colon is a field name with an empty value
  23367. auto r = sse_parse("data\n\n");
  23368. ASSERT_EQ(r.events.size(), 1u);
  23369. EXPECT_EQ(r.events[0].data, "");
  23370. }
  23371. TEST(SSEParserTest, TrailingCarriageReturn) {
  23372. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23373. ASSERT_EQ(r.events.size(), 1u);
  23374. EXPECT_EQ(r.events[0].event, "update");
  23375. EXPECT_EQ(r.events[0].data, "hello");
  23376. }
  23377. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23378. auto r = sse_parse("data\r\n\r\n");
  23379. ASSERT_EQ(r.events.size(), 1u);
  23380. EXPECT_EQ(r.events[0].data, "");
  23381. }
  23382. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23383. auto r = sse_parse("event: update\rdata: hello\r\r");
  23384. ASSERT_EQ(r.events.size(), 1u);
  23385. EXPECT_EQ(r.events[0].event, "update");
  23386. EXPECT_EQ(r.events[0].data, "hello");
  23387. }
  23388. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23389. // Chunk boundaries fall inside every \r\n and right before the first one
  23390. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23391. "\ndata: hello\r", "\n\r", "\n"});
  23392. ASSERT_EQ(r.events.size(), 1u);
  23393. EXPECT_EQ(r.events[0].event, "update");
  23394. EXPECT_EQ(r.events[0].data, "hello");
  23395. }
  23396. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23397. // Only a BOM at the start of the stream is ignored
  23398. auto r = sse_parse("\xEF\xBB\xBF"
  23399. "data: first\n\n"
  23400. "\xEF\xBB\xBF"
  23401. "data: second\n\n");
  23402. ASSERT_EQ(r.events.size(), 1u);
  23403. EXPECT_EQ(r.events[0].data, "first");
  23404. }
  23405. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23406. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23407. ASSERT_EQ(r.events.size(), 1u);
  23408. EXPECT_EQ(r.events[0].data, "hello");
  23409. EXPECT_EQ(r.events[0].event, "message");
  23410. }
  23411. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23412. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23413. ASSERT_EQ(r.events.size(), 2u);
  23414. EXPECT_EQ(r.events[0].data, "hello");
  23415. EXPECT_EQ(r.events[1].data, "hello");
  23416. }
  23417. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23418. // An event without data is not dispatched, and its type must not leak
  23419. // into the next event
  23420. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23421. ASSERT_EQ(r.events.size(), 1u);
  23422. EXPECT_EQ(r.events[0].event, "message");
  23423. EXPECT_EQ(r.events[0].data, "hello");
  23424. }
  23425. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23426. // Also when the empty field replaces an earlier type
  23427. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23428. ASSERT_EQ(r.events.size(), 2u);
  23429. EXPECT_EQ(r.events[0].event, "message");
  23430. EXPECT_EQ(r.events[1].event, "message");
  23431. }
  23432. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23433. auto r = sse_parse("id: 42\n\n");
  23434. EXPECT_TRUE(r.events.empty());
  23435. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23436. }
  23437. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23438. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23439. ASSERT_EQ(r.events.size(), 2u);
  23440. EXPECT_EQ(r.events[0].id, "1");
  23441. EXPECT_EQ(r.events[1].id, "");
  23442. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23443. }
  23444. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23445. // Ids that cannot be carried in a Last-Event-ID header
  23446. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23447. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23448. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23449. }
  23450. TEST(SSEParserTest, RetryDigitsOnly) {
  23451. auto r = sse_parse("retry: 1000\n");
  23452. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23453. // A value that is not all ASCII digits, or does not fit, is ignored
  23454. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23455. EXPECT_TRUE(r.retries.empty());
  23456. }
  23457. TEST(SSEParserTest, CompleteEventParsing) {
  23458. auto r = sse_parse("event: notification\nid: evt-42\n"
  23459. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23460. ASSERT_EQ(r.events.size(), 1u);
  23461. EXPECT_EQ(r.events[0].event, "notification");
  23462. EXPECT_EQ(r.events[0].id, "evt-42");
  23463. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23464. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23465. }
  23466. TEST(SSEParserTest, IncompleteEventNotReported) {
  23467. // An event still waiting for its blank line when the stream ends is
  23468. // discarded per the SSE spec
  23469. auto r = sse_parse("id: 1\ndata: x\n");
  23470. EXPECT_TRUE(r.events.empty());
  23471. EXPECT_TRUE(r.ids.empty());
  23472. }
  23473. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23474. const std::vector<std::string> streams = {
  23475. "\xEF\xBB\xBF"
  23476. "data: bom\r\n\r\n",
  23477. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23478. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23479. };
  23480. for (const auto &stream : streams) {
  23481. auto expected = sse_parse(stream).trace;
  23482. ASSERT_FALSE(expected.empty());
  23483. for (size_t i = 0; i <= stream.size(); i++) {
  23484. auto r = sse_parse(
  23485. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23486. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23487. }
  23488. std::vector<std::string> bytes;
  23489. for (auto c : stream) {
  23490. bytes.emplace_back(1, c);
  23491. }
  23492. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23493. }
  23494. }
  23495. TEST(SSEParserTest, MaxEventLength) {
  23496. // A line still waiting for its end
  23497. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23498. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23499. // Data accumulated over the lines of one event
  23500. EXPECT_TRUE(
  23501. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23502. EXPECT_FALSE(
  23503. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23504. // 0 means no limit
  23505. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23506. // Events completed in the same chunk are still reported
  23507. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23508. EXPECT_FALSE(r.ok);
  23509. ASSERT_EQ(r.events.size(), 1u);
  23510. EXPECT_EQ(r.events[0].data, "a");
  23511. }
  23512. TEST(SSEMessageTest, Clear) {
  23513. sse::SSEMessage msg;
  23514. msg.event = "custom";
  23515. msg.data = "some data";
  23516. msg.id = "123";
  23517. msg.clear();
  23518. EXPECT_EQ(msg.event, "message");
  23519. EXPECT_EQ(msg.data, "");
  23520. EXPECT_EQ(msg.id, "");
  23521. }
  23522. //==============================================================================
  23523. // SSE Integration Tests
  23524. //==============================================================================
  23525. // Test: Successful connection and on_open callback
  23526. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23527. // Add a simple endpoint that sends one event and closes
  23528. server_->Get("/simple-event", [](const Request &, Response &res) {
  23529. res.set_chunked_content_provider(
  23530. "text/event-stream", [](size_t offset, DataSink &sink) {
  23531. if (offset == 0) {
  23532. std::string event = "data: hello\n\n";
  23533. sink.write(event.data(), event.size());
  23534. }
  23535. return false; // Close stream after sending
  23536. });
  23537. });
  23538. Client client("localhost", get_port());
  23539. sse::SSEClient sse(client, "/simple-event");
  23540. std::atomic<bool> open_called{false};
  23541. std::atomic<bool> message_received{false};
  23542. sse.on_open([&open_called]() { open_called.store(true); });
  23543. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23544. if (msg.data == "hello") { message_received.store(true); }
  23545. });
  23546. sse.set_reconnect_interval(100);
  23547. sse.set_max_reconnect_attempts(1);
  23548. // Start async
  23549. sse.start_async();
  23550. // Wait for message to be processed
  23551. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23552. sse.stop();
  23553. EXPECT_TRUE(open_called.load());
  23554. EXPECT_TRUE(message_received.load());
  23555. }
  23556. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23557. // A data line that never ends.
  23558. server_->Get("/endless-line", [](const Request &, Response &res) {
  23559. res.set_chunked_content_provider(
  23560. "text/event-stream", [](size_t offset, DataSink &sink) {
  23561. if (offset == 0) { sink.write("data: ", 6); }
  23562. std::string chunk(64 * 1024, 'A');
  23563. return sink.write(chunk.data(), chunk.size());
  23564. });
  23565. });
  23566. Client client("localhost", get_port());
  23567. sse::SSEClient sse(client, "/endless-line");
  23568. std::atomic<bool> too_long{false};
  23569. sse.on_error([&](Error err) {
  23570. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23571. });
  23572. sse.set_max_reconnect_attempts(1);
  23573. sse.start_async();
  23574. for (int i = 0; i < 500 && !too_long; i++) {
  23575. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23576. }
  23577. sse.stop();
  23578. EXPECT_TRUE(too_long);
  23579. }
  23580. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23581. // Far more in all than the client's payload limit below.
  23582. server_->Get("/many-events", [](const Request &, Response &res) {
  23583. res.set_chunked_content_provider(
  23584. "text/event-stream", [](size_t offset, DataSink &sink) {
  23585. if (offset == 0) {
  23586. std::string events;
  23587. for (int i = 0; i < 1000; i++) {
  23588. events += "data: message\n\n";
  23589. }
  23590. sink.write(events.data(), events.size());
  23591. }
  23592. return false;
  23593. });
  23594. });
  23595. Client client("localhost", get_port());
  23596. client.set_payload_max_length(1024);
  23597. sse::SSEClient sse(client, "/many-events");
  23598. std::atomic<int> messages{0};
  23599. std::atomic<bool> too_large{false};
  23600. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23601. sse.on_error([&](Error err) {
  23602. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23603. });
  23604. sse.set_max_reconnect_attempts(1);
  23605. sse.start_async();
  23606. for (int i = 0; i < 500 && messages < 1000; i++) {
  23607. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23608. }
  23609. sse.stop();
  23610. EXPECT_GE(messages.load(), 1000);
  23611. EXPECT_FALSE(too_large);
  23612. }
  23613. // Test: on_message callback
  23614. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23615. // Endpoint that sends multiple events then closes
  23616. server_->Get("/multi-event", [](const Request &, Response &res) {
  23617. res.set_chunked_content_provider(
  23618. "text/event-stream", [](size_t offset, DataSink &sink) {
  23619. if (offset == 0) {
  23620. std::string events = "data: message1\n\ndata: message2\n\n";
  23621. sink.write(events.data(), events.size());
  23622. }
  23623. return false;
  23624. });
  23625. });
  23626. Client client("localhost", get_port());
  23627. sse::SSEClient sse(client, "/multi-event");
  23628. std::vector<std::string> received_messages;
  23629. std::mutex messages_mutex;
  23630. sse.on_message([&](const sse::SSEMessage &msg) {
  23631. std::lock_guard<std::mutex> lock(messages_mutex);
  23632. received_messages.push_back(msg.data);
  23633. });
  23634. sse.set_reconnect_interval(100);
  23635. sse.set_max_reconnect_attempts(1);
  23636. sse.start_async();
  23637. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23638. sse.stop();
  23639. std::lock_guard<std::mutex> lock(messages_mutex);
  23640. EXPECT_GE(received_messages.size(), 2u);
  23641. if (received_messages.size() >= 2) {
  23642. EXPECT_EQ(received_messages[0], "message1");
  23643. EXPECT_EQ(received_messages[1], "message2");
  23644. }
  23645. }
  23646. // Test: on_event for specific types
  23647. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23648. Client client("localhost", get_port());
  23649. sse::SSEClient sse(client, "/custom-events");
  23650. std::atomic<bool> update_received{false};
  23651. std::atomic<bool> delete_received{false};
  23652. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23653. if (msg.data == "updated") { update_received.store(true); }
  23654. });
  23655. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23656. if (msg.data == "deleted") { delete_received.store(true); }
  23657. });
  23658. sse.set_max_reconnect_attempts(1);
  23659. sse.start_async();
  23660. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23661. sse.stop();
  23662. EXPECT_TRUE(update_received.load());
  23663. EXPECT_TRUE(delete_received.load());
  23664. }
  23665. // Test: on_error callback on connection failure
  23666. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23667. // Connect to a non-existent port
  23668. Client client("localhost", 59999);
  23669. sse::SSEClient sse(client, "/events");
  23670. std::atomic<bool> error_called{false};
  23671. Error received_error = Error::Success;
  23672. sse.on_error([&](Error err) {
  23673. error_called.store(true);
  23674. received_error = err;
  23675. });
  23676. sse.set_reconnect_interval(50);
  23677. sse.set_max_reconnect_attempts(1);
  23678. sse.start_async();
  23679. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23680. sse.stop();
  23681. EXPECT_TRUE(error_called.load());
  23682. EXPECT_NE(received_error, Error::Success);
  23683. }
  23684. // Test: Last-Event-ID header sent on reconnect
  23685. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23686. // Endpoint that sends event with ID
  23687. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23688. res.set_chunked_content_provider(
  23689. "text/event-stream", [](size_t offset, DataSink &sink) {
  23690. if (offset == 0) {
  23691. std::string event = "id: evt-123\ndata: test\n\n";
  23692. sink.write(event.data(), event.size());
  23693. }
  23694. return false;
  23695. });
  23696. });
  23697. Client client("localhost", get_port());
  23698. sse::SSEClient sse(client, "/event-with-id");
  23699. std::atomic<bool> id_received{false};
  23700. sse.on_message([&](const sse::SSEMessage &msg) {
  23701. if (!msg.id.empty()) { id_received.store(true); }
  23702. });
  23703. sse.set_reconnect_interval(100);
  23704. sse.set_max_reconnect_attempts(1);
  23705. sse.start_async();
  23706. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23707. sse.stop();
  23708. EXPECT_TRUE(id_received.load());
  23709. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23710. }
  23711. // Test: last_event_id() read from another thread while start_async() runs
  23712. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23713. // Ids of every length up to 200, so the stored id keeps changing size
  23714. server_->Get("/many-ids", [](const Request &, Response &res) {
  23715. res.set_chunked_content_provider(
  23716. "text/event-stream", [](size_t offset, DataSink &sink) {
  23717. if (offset == 0) {
  23718. std::string events;
  23719. for (size_t i = 0; i < 2000; i++) {
  23720. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23721. events += "data: x\n\n";
  23722. }
  23723. events += "id: end\ndata: x\n\n";
  23724. sink.write(events.data(), events.size());
  23725. }
  23726. return false;
  23727. });
  23728. });
  23729. Client client("localhost", get_port());
  23730. sse::SSEClient sse(client, "/many-ids");
  23731. // Wait out the rest of the test rather than replay the stream
  23732. sse.set_reconnect_interval(10000);
  23733. sse.set_max_reconnect_attempts(1);
  23734. sse.start_async();
  23735. auto well_formed = true;
  23736. std::string id;
  23737. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23738. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23739. id = sse.last_event_id();
  23740. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23741. well_formed = false;
  23742. }
  23743. }
  23744. sse.stop();
  23745. EXPECT_TRUE(well_formed);
  23746. EXPECT_EQ(sse.last_event_id(), "end");
  23747. }
  23748. // Test: Manual stop
  23749. TEST_F(SSEIntegrationTest, ManualStop) {
  23750. // Endpoint that sends one event and stays open briefly. The server outlives
  23751. // this test body, so the provider uses the fixture's flag, not a local.
  23752. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23753. res.set_chunked_content_provider(
  23754. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23755. if (offset == 0) {
  23756. std::string event = "data: connected\n\n";
  23757. sink.write(event.data(), event.size());
  23758. }
  23759. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23760. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23761. }
  23762. return false;
  23763. });
  23764. });
  23765. Client client("localhost", get_port());
  23766. sse::SSEClient sse(client, "/stay-open");
  23767. std::atomic<bool> connected{false};
  23768. sse.on_open([&connected]() { connected.store(true); });
  23769. sse.set_reconnect_interval(100);
  23770. sse.set_max_reconnect_attempts(1);
  23771. sse.start_async();
  23772. // Wait for connection to establish
  23773. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23774. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23775. }
  23776. EXPECT_TRUE(connected.load());
  23777. EXPECT_TRUE(sse.is_connected());
  23778. // Signal handler to stop
  23779. stop_server_.store(true);
  23780. // Stop SSE client
  23781. sse.stop();
  23782. EXPECT_FALSE(sse.is_connected());
  23783. }
  23784. // Sends one event, then nothing until stop is set
  23785. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23786. return [&stop](const Request &, Response &res) {
  23787. res.set_chunked_content_provider(
  23788. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23789. if (offset == 0) {
  23790. std::string event = "data: hello\n\n";
  23791. sink.write(event.data(), event.size());
  23792. }
  23793. while (!stop.load()) {
  23794. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23795. }
  23796. return false;
  23797. });
  23798. };
  23799. }
  23800. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23801. static void check_stop_interrupts_blocked_read(Client &client) {
  23802. client.set_read_timeout(30, 0);
  23803. for (auto by_destructor : {false, true}) {
  23804. std::atomic<bool> received{false};
  23805. std::chrono::steady_clock::time_point start;
  23806. {
  23807. sse::SSEClient sse(client, "/idle-stream");
  23808. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23809. sse.start_async();
  23810. for (int i = 0; i < 500 && !received.load(); ++i) {
  23811. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23812. }
  23813. ASSERT_TRUE(received.load());
  23814. // Let the client block in the next read
  23815. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23816. start = std::chrono::steady_clock::now();
  23817. if (!by_destructor) { sse.stop(); }
  23818. }
  23819. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23820. std::chrono::seconds(2));
  23821. }
  23822. }
  23823. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23824. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23825. Client client("localhost", get_port());
  23826. check_stop_interrupts_blocked_read(client);
  23827. }
  23828. #ifdef CPPHTTPLIB_SSL_ENABLED
  23829. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23830. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23831. std::atomic<bool> done{false};
  23832. svr.Get("/idle-stream", idle_event_stream(done));
  23833. auto port = svr.bind_to_any_port(HOST);
  23834. std::thread t([&] { svr.listen_after_bind(); });
  23835. auto se = detail::scope_exit([&] {
  23836. done.store(true);
  23837. svr.stop();
  23838. t.join();
  23839. });
  23840. svr.wait_until_ready();
  23841. Client client("https://localhost:" + std::to_string(port));
  23842. client.enable_server_certificate_verification(false);
  23843. check_stop_interrupts_blocked_read(client);
  23844. }
  23845. #endif
  23846. // Test: SSEClient with custom headers
  23847. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23848. // Setup a server endpoint that checks for custom header
  23849. std::atomic<bool> header_received{false};
  23850. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23851. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23852. header_received.store(true);
  23853. }
  23854. res.set_chunked_content_provider("text/event-stream",
  23855. [](size_t, DataSink &) { return false; });
  23856. });
  23857. Client client("localhost", get_port());
  23858. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23859. sse::SSEClient sse(client, "/header-check", headers);
  23860. sse.set_max_reconnect_attempts(1);
  23861. sse.start_async();
  23862. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23863. sse.stop();
  23864. EXPECT_TRUE(header_received.load());
  23865. }
  23866. // Test: Reconnect interval configuration
  23867. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23868. Client client("localhost", get_port());
  23869. sse::SSEClient sse(client, "/events");
  23870. auto &result = sse.set_reconnect_interval(500);
  23871. // Builder pattern should return reference to self
  23872. EXPECT_EQ(&result, &sse);
  23873. }
  23874. // Test: Max reconnect attempts
  23875. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23876. // Connect to non-existent port to force reconnects
  23877. Client client("localhost", 59998);
  23878. sse::SSEClient sse(client, "/events");
  23879. std::atomic<int> error_count{0};
  23880. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23881. sse.set_reconnect_interval(50);
  23882. sse.set_max_reconnect_attempts(2);
  23883. auto start = std::chrono::steady_clock::now();
  23884. sse.start(); // Blocking call
  23885. auto end = std::chrono::steady_clock::now();
  23886. // Should have stopped after 2 failed attempts
  23887. EXPECT_GE(error_count.load(), 2);
  23888. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23889. auto duration =
  23890. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23891. #ifdef _WIN32
  23892. // Windows is much slower for socket connection failures
  23893. EXPECT_LT(duration.count(), 7000);
  23894. #else
  23895. EXPECT_LT(duration.count(), 1000);
  23896. #endif
  23897. }
  23898. // Test: Multi-line data in integration
  23899. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23900. // Endpoint with multi-line data
  23901. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23902. res.set_chunked_content_provider(
  23903. "text/event-stream", [](size_t offset, DataSink &sink) {
  23904. if (offset == 0) {
  23905. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23906. sink.write(event.data(), event.size());
  23907. }
  23908. return false;
  23909. });
  23910. });
  23911. Client client("localhost", get_port());
  23912. sse::SSEClient sse(client, "/multiline-data");
  23913. std::string received_data;
  23914. std::mutex data_mutex;
  23915. sse.on_message([&](const sse::SSEMessage &msg) {
  23916. std::lock_guard<std::mutex> lock(data_mutex);
  23917. received_data = msg.data;
  23918. });
  23919. sse.set_reconnect_interval(100);
  23920. sse.set_max_reconnect_attempts(1);
  23921. sse.start_async();
  23922. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23923. sse.stop();
  23924. std::lock_guard<std::mutex> lock(data_mutex);
  23925. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23926. }
  23927. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23928. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23929. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23930. DataSink &sink) {
  23931. if (offset == 0) {
  23932. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23933. sink.write(events.data(), events.size());
  23934. }
  23935. return false;
  23936. });
  23937. });
  23938. Client client("localhost", get_port());
  23939. sse::SSEClient sse(client, "/empty-data-lines");
  23940. std::mutex mutex;
  23941. std::condition_variable cv;
  23942. std::vector<std::string> received;
  23943. sse.on_message([&](const sse::SSEMessage &msg) {
  23944. std::lock_guard<std::mutex> lock(mutex);
  23945. received.push_back(msg.data);
  23946. cv.notify_all();
  23947. });
  23948. sse.set_max_reconnect_attempts(1);
  23949. sse.start_async();
  23950. {
  23951. std::unique_lock<std::mutex> lock(mutex);
  23952. cv.wait_for(lock, std::chrono::seconds(2),
  23953. [&] { return received.size() >= 3; });
  23954. }
  23955. sse.stop();
  23956. ASSERT_GE(received.size(), 3u);
  23957. EXPECT_EQ(received[0], "");
  23958. EXPECT_EQ(received[1], "\nhello");
  23959. EXPECT_EQ(received[2], "");
  23960. }
  23961. // Test: Auto-reconnect after server disconnection
  23962. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23963. std::atomic<int> connection_count{0};
  23964. std::atomic<int> message_count{0};
  23965. // Endpoint that sends one event and closes, forcing reconnect
  23966. server_->Get("/reconnect-test",
  23967. [&connection_count](const Request &, Response &res) {
  23968. connection_count.fetch_add(1);
  23969. res.set_chunked_content_provider(
  23970. "text/event-stream", [](size_t offset, DataSink &sink) {
  23971. if (offset == 0) {
  23972. std::string event = "data: hello\n\n";
  23973. sink.write(event.data(), event.size());
  23974. }
  23975. return false; // Close connection after sending
  23976. });
  23977. });
  23978. Client client("localhost", get_port());
  23979. sse::SSEClient sse(client, "/reconnect-test");
  23980. sse.on_message([&message_count](const sse::SSEMessage &) {
  23981. message_count.fetch_add(1);
  23982. });
  23983. sse.set_reconnect_interval(100);
  23984. sse.set_max_reconnect_attempts(3);
  23985. sse.start_async();
  23986. // Wait long enough for multiple reconnects
  23987. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23988. sse.stop();
  23989. // Should have connected multiple times (initial + reconnects)
  23990. EXPECT_GE(connection_count.load(), 2);
  23991. // Should have received messages from multiple connections
  23992. EXPECT_GE(message_count.load(), 2);
  23993. }
  23994. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23995. std::atomic<int> connection_count{0};
  23996. // Neither Content-Length nor chunked: the close ends the stream
  23997. server_->Get("/close-delimited",
  23998. [&connection_count](const Request &, Response &res) {
  23999. connection_count.fetch_add(1);
  24000. res.set_content_provider(
  24001. "text/event-stream", [](size_t offset, DataSink &sink) {
  24002. if (offset == 0) {
  24003. std::string event = "data: hello\n\n";
  24004. sink.write(event.data(), event.size());
  24005. } else {
  24006. sink.done();
  24007. }
  24008. return true;
  24009. });
  24010. });
  24011. Client client("localhost", get_port());
  24012. sse::SSEClient sse(client, "/close-delimited");
  24013. std::atomic<int> error_count{0};
  24014. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  24015. sse.set_reconnect_interval(100);
  24016. sse.start_async();
  24017. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  24018. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24019. }
  24020. sse.stop();
  24021. // Reconnects as after any end of the stream, but reports no error
  24022. EXPECT_GE(connection_count.load(), 2);
  24023. EXPECT_EQ(0, error_count.load());
  24024. }
  24025. // Test: A retry field of all ASCII digits sets the reconnection time
  24026. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  24027. std::mutex mutex;
  24028. std::condition_variable cv;
  24029. std::vector<std::chrono::steady_clock::time_point> connected_at;
  24030. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  24031. {
  24032. std::lock_guard<std::mutex> lock(mutex);
  24033. connected_at.push_back(std::chrono::steady_clock::now());
  24034. cv.notify_all();
  24035. }
  24036. res.set_chunked_content_provider(
  24037. "text/event-stream", [](size_t offset, DataSink &sink) {
  24038. if (offset == 0) {
  24039. std::string event = "retry: 0\ndata: hello\n\n";
  24040. sink.write(event.data(), event.size());
  24041. }
  24042. return false;
  24043. });
  24044. });
  24045. Client client("localhost", get_port());
  24046. sse::SSEClient sse(client, "/zero-retry");
  24047. sse.set_reconnect_interval(10000);
  24048. sse.start_async();
  24049. {
  24050. std::unique_lock<std::mutex> lock(mutex);
  24051. cv.wait_for(lock, std::chrono::seconds(5),
  24052. [&] { return connected_at.size() >= 2; });
  24053. }
  24054. sse.stop();
  24055. // The server-supplied interval is applied, but never below 100ms, so
  24056. // "retry: 0" does not cause a busy reconnect loop
  24057. std::lock_guard<std::mutex> lock(mutex);
  24058. ASSERT_GE(connected_at.size(), 2u);
  24059. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  24060. connected_at[1] - connected_at[0])
  24061. .count();
  24062. EXPECT_GE(interval_ms, 100);
  24063. }
  24064. // Test: Last-Event-ID sent on reconnect
  24065. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  24066. std::atomic<int> connection_count{0};
  24067. std::vector<std::string> received_last_event_ids;
  24068. std::mutex id_mutex;
  24069. // Endpoint that checks Last-Event-ID header and sends event with ID
  24070. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  24071. int conn = connection_count.fetch_add(1);
  24072. // Capture the Last-Event-ID header from each connection
  24073. {
  24074. std::lock_guard<std::mutex> lock(id_mutex);
  24075. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  24076. }
  24077. res.set_chunked_content_provider(
  24078. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  24079. if (offset == 0) {
  24080. std::string event =
  24081. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  24082. sink.write(event.data(), event.size());
  24083. }
  24084. return false;
  24085. });
  24086. });
  24087. Client client("localhost", get_port());
  24088. sse::SSEClient sse(client, "/reconnect-with-id");
  24089. sse.set_reconnect_interval(100);
  24090. sse.set_max_reconnect_attempts(3);
  24091. sse.start_async();
  24092. // Wait for at least 2 connections
  24093. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  24094. sse.stop();
  24095. // Verify behavior
  24096. std::lock_guard<std::mutex> lock(id_mutex);
  24097. EXPECT_GE(received_last_event_ids.size(), 2u);
  24098. // First connection should have no Last-Event-ID
  24099. if (!received_last_event_ids.empty()) {
  24100. EXPECT_EQ(received_last_event_ids[0], "");
  24101. }
  24102. // Second connection should have Last-Event-ID from first connection
  24103. if (received_last_event_ids.size() >= 2) {
  24104. EXPECT_EQ(received_last_event_ids[1], "event-0");
  24105. }
  24106. }
  24107. // Test: set_headers updates headers used on reconnect
  24108. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  24109. std::vector<std::string> received_tokens;
  24110. std::mutex token_mutex;
  24111. // Endpoint that captures Authorization header
  24112. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  24113. {
  24114. std::lock_guard<std::mutex> lock(token_mutex);
  24115. received_tokens.push_back(req.get_header_value("Authorization"));
  24116. }
  24117. res.set_chunked_content_provider(
  24118. "text/event-stream", [](size_t offset, DataSink &sink) {
  24119. if (offset == 0) {
  24120. std::string event = "data: hello\n\n";
  24121. sink.write(event.data(), event.size());
  24122. }
  24123. return false; // Close connection to trigger reconnect
  24124. });
  24125. });
  24126. Client client("localhost", get_port());
  24127. Headers headers = {{"Authorization", "Bearer old-token"}};
  24128. sse::SSEClient sse(client, "/auth-check", headers);
  24129. // Update headers on each successful connection
  24130. sse.on_open(
  24131. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  24132. sse.set_reconnect_interval(100);
  24133. sse.set_max_reconnect_attempts(3);
  24134. sse.start_async();
  24135. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  24136. sse.stop();
  24137. std::lock_guard<std::mutex> lock(token_mutex);
  24138. ASSERT_GE(received_tokens.size(), 2u);
  24139. // First connection uses original header
  24140. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  24141. // Second connection uses updated header from set_headers
  24142. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  24143. }
  24144. // Test: 401 allows reconnection (so on_error can refresh headers)
  24145. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  24146. std::atomic<int> connection_count{0};
  24147. // Endpoint: returns 401 on first attempt, 200 on second
  24148. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  24149. int conn = connection_count.fetch_add(1);
  24150. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  24151. res.status = StatusCode::Unauthorized_401;
  24152. res.set_content("Unauthorized", "text/plain");
  24153. return;
  24154. }
  24155. res.set_chunked_content_provider(
  24156. "text/event-stream", [](size_t offset, DataSink &sink) {
  24157. if (offset == 0) {
  24158. std::string event = "data: authenticated\n\n";
  24159. sink.write(event.data(), event.size());
  24160. }
  24161. return false;
  24162. });
  24163. });
  24164. Client client("localhost", get_port());
  24165. Headers headers = {{"Authorization", "Bearer expired"}};
  24166. sse::SSEClient sse(client, "/auth-retry", headers);
  24167. std::atomic<bool> message_received{false};
  24168. // Refresh token on error
  24169. sse.on_error(
  24170. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  24171. sse.on_message([&](const sse::SSEMessage &msg) {
  24172. if (msg.data == "authenticated") { message_received.store(true); }
  24173. });
  24174. sse.set_reconnect_interval(100);
  24175. sse.set_max_reconnect_attempts(3);
  24176. sse.start_async();
  24177. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  24178. sse.stop();
  24179. // Should have reconnected after 401 and succeeded with new token
  24180. EXPECT_GE(connection_count.load(), 2);
  24181. EXPECT_TRUE(message_received.load());
  24182. }
  24183. TEST(Issue2318Test, EmptyHostString) {
  24184. {
  24185. httplib::Client cli_empty("", PORT);
  24186. auto res = cli_empty.Get("/");
  24187. ASSERT_FALSE(res);
  24188. EXPECT_EQ(httplib::Error::Connection, res.error());
  24189. }
  24190. {
  24191. httplib::Client cli(" ", PORT);
  24192. auto res = cli.Get("/");
  24193. ASSERT_FALSE(res);
  24194. EXPECT_EQ(httplib::Error::Connection, res.error());
  24195. }
  24196. }
  24197. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  24198. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  24199. Server svr;
  24200. // Set a small payload limit (1KB)
  24201. svr.set_payload_max_length(1024);
  24202. svr.Post("/test", [&](const Request &req, Response &res) {
  24203. res.set_content("Body size: " + std::to_string(req.body.size()),
  24204. "text/plain");
  24205. });
  24206. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  24207. auto se = detail::scope_exit([&] {
  24208. svr.stop();
  24209. listen_thread.join();
  24210. });
  24211. svr.wait_until_ready();
  24212. // Create data that compresses well but exceeds limit when decompressed
  24213. // 8KB of repeated null bytes compresses to a very small size
  24214. std::string original_data(8 * 1024, '\0');
  24215. // Compress the data using gzip
  24216. std::string compressed_data;
  24217. detail::gzip_compressor compressor;
  24218. compressor.compress(original_data.data(), original_data.size(), true,
  24219. [&](const char *data, size_t size) {
  24220. compressed_data.append(data, size);
  24221. return true;
  24222. });
  24223. // Verify compression worked (compressed should be much smaller)
  24224. ASSERT_LT(compressed_data.size(), original_data.size());
  24225. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  24226. // Send compressed data with Content-Encoding: gzip
  24227. Client cli(HOST, PORT);
  24228. Headers headers = {{"Content-Encoding", "gzip"}};
  24229. auto res =
  24230. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  24231. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  24232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24233. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  24234. }
  24235. #endif
  24236. // ============================================================================
  24237. // OpenSSL-Specific Tests
  24238. // ============================================================================
  24239. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24240. X509 *readCertificate(const std::string &strFileName) {
  24241. std::ifstream inStream(strFileName);
  24242. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  24243. std::istreambuf_iterator<char>());
  24244. if (strCertPEM.empty()) return (nullptr);
  24245. BIO *pbCert = BIO_new(BIO_s_mem());
  24246. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  24247. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  24248. BIO_free(pbCert);
  24249. return (pCert);
  24250. }
  24251. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  24252. std::ifstream inStream(strFileName);
  24253. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  24254. std::istreambuf_iterator<char>());
  24255. if (strPrivateKeyPEM.empty()) return (nullptr);
  24256. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  24257. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  24258. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  24259. BIO_free(pbPrivKey);
  24260. return (pPrivateKey);
  24261. }
  24262. TEST(BindServerTest, UpdateCerts) {
  24263. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24264. int port = svr.bind_to_any_port("0.0.0.0");
  24265. ASSERT_TRUE(svr.is_valid());
  24266. ASSERT_TRUE(port > 0);
  24267. X509 *cert = readCertificate(SERVER_CERT_FILE);
  24268. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  24269. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  24270. ASSERT_TRUE(cert != nullptr);
  24271. ASSERT_TRUE(ca_cert != nullptr);
  24272. ASSERT_TRUE(key != nullptr);
  24273. X509_STORE *cert_store = X509_STORE_new();
  24274. X509_STORE_add_cert(cert_store, ca_cert);
  24275. // svr.update_certs(cert, key, cert_store); // deprecated
  24276. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  24277. CLIENT_CA_CERT_FILE);
  24278. ASSERT_TRUE(svr.is_valid());
  24279. svr.stop();
  24280. X509_STORE_free(cert_store);
  24281. X509_free(cert);
  24282. X509_free(ca_cert);
  24283. EVP_PKEY_free(key);
  24284. }
  24285. // Test that update_certs() updates client CA list correctly
  24286. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  24287. // Start with file-based constructor
  24288. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24289. ASSERT_TRUE(svr.is_valid());
  24290. // Initially no client CA list should be set
  24291. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24292. ASSERT_TRUE(ssl_ctx != nullptr);
  24293. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  24294. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  24295. // Now update with client CA (PEM string)
  24296. std::string cert_pem, key_pem, ca_pem;
  24297. read_file(SERVER_CERT_FILE, cert_pem);
  24298. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  24299. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  24300. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  24301. ASSERT_TRUE(svr.is_valid());
  24302. // Now client CA list should be set
  24303. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  24304. ASSERT_TRUE(ca_list_after != nullptr);
  24305. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  24306. }
  24307. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  24308. // Test that the file-path SSLServer constructor properly sets the client CA
  24309. // list that is sent to clients during the TLS handshake (CertificateRequest)
  24310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24311. ASSERT_TRUE(svr.is_valid());
  24312. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24313. ASSERT_TRUE(ssl_ctx != nullptr);
  24314. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  24315. ASSERT_TRUE(ca_list != nullptr);
  24316. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  24317. }
  24318. #endif
  24319. // ============================================================================
  24320. // MbedTLS-Specific Tests
  24321. // ============================================================================
  24322. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  24323. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  24324. using namespace httplib::tls;
  24325. // Track if callback was invoked
  24326. bool callback_invoked = false;
  24327. // The callback receives void* ctx which is actually MbedTlsContext*
  24328. // We can access the mbedtls_ssl_config via the context
  24329. auto setup_callback = [&callback_invoked](void *ctx) {
  24330. callback_invoked = true;
  24331. // Cast to MbedTlsContext* to access the ssl config
  24332. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  24333. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24334. // Use static variables to hold certificate data (simplified for test)
  24335. static mbedtls_x509_crt own_cert;
  24336. static mbedtls_pk_context own_key;
  24337. static mbedtls_x509_crt ca_chain;
  24338. static bool initialized = false;
  24339. if (!initialized) {
  24340. mbedtls_x509_crt_init(&own_cert);
  24341. mbedtls_pk_init(&own_key);
  24342. mbedtls_x509_crt_init(&ca_chain);
  24343. // Load server certificate
  24344. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24345. return false;
  24346. }
  24347. // Load server private key.
  24348. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24349. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24350. #if MBEDTLS_VERSION_MAJOR == 3
  24351. ,
  24352. mbedtls_ctr_drbg_random, nullptr
  24353. #endif
  24354. ) != 0) {
  24355. return false;
  24356. }
  24357. // Load CA chain for client verification
  24358. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24359. return false;
  24360. }
  24361. initialized = true;
  24362. }
  24363. // Configure the SSL config
  24364. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24365. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24366. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24367. // Set minimum TLS version using mbedTLS native API
  24368. #if MBEDTLS_VERSION_MAJOR >= 3
  24369. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24370. #else
  24371. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24372. MBEDTLS_SSL_MINOR_VERSION_3);
  24373. #endif
  24374. return true;
  24375. };
  24376. SSLServer svr(setup_callback);
  24377. ASSERT_TRUE(svr.is_valid());
  24378. ASSERT_TRUE(callback_invoked);
  24379. svr.Get("/test", [&](const Request &req, Response &res) {
  24380. res.set_content("test", "text/plain");
  24381. auto cert = req.peer_cert();
  24382. ASSERT_TRUE(static_cast<bool>(cert));
  24383. auto common_name = cert.subject_cn();
  24384. EXPECT_EQ("Common Name", common_name);
  24385. });
  24386. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24387. auto se = detail::scope_exit([&] {
  24388. svr.stop();
  24389. t.join();
  24390. ASSERT_FALSE(svr.is_running());
  24391. });
  24392. svr.wait_until_ready();
  24393. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24394. cli.enable_server_certificate_verification(false);
  24395. cli.set_connection_timeout(30);
  24396. auto res = cli.Get("/test");
  24397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24398. ASSERT_EQ(StatusCode::OK_200, res->status);
  24399. }
  24400. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24401. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24402. // keep-alive SSL session, which reads through that config in
  24403. // mbedtls_ssl_close_notify.
  24404. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24405. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24406. ASSERT_TRUE(svr.is_valid());
  24407. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24408. res.set_content("test", "text/plain");
  24409. });
  24410. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24411. auto se = detail::scope_exit([&] {
  24412. svr.stop();
  24413. t.join();
  24414. ASSERT_FALSE(svr.is_running());
  24415. });
  24416. svr.wait_until_ready();
  24417. {
  24418. SSLClient cli(HOST, PORT);
  24419. cli.enable_server_certificate_verification(false);
  24420. cli.set_keep_alive(true);
  24421. auto res = cli.Get("/test");
  24422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24423. ASSERT_EQ(StatusCode::OK_200, res->status);
  24424. // cli is destructed here with the keep-alive SSL session still open.
  24425. }
  24426. }
  24427. #endif
  24428. // WebSocket Tests
  24429. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24430. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24431. // defining the meaning of these bits has been negotiated.
  24432. auto make_frame = [](uint8_t first_byte) {
  24433. std::string frame;
  24434. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24435. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24436. frame += "Hello";
  24437. return frame;
  24438. };
  24439. // RSV1 set (0x40)
  24440. {
  24441. detail::BufferStream strm;
  24442. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24443. ws::Opcode opcode;
  24444. std::string payload;
  24445. bool fin;
  24446. EXPECT_EQ(
  24447. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24448. ws::impl::FrameRead::ProtocolError);
  24449. }
  24450. // RSV2 set (0x20)
  24451. {
  24452. detail::BufferStream strm;
  24453. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24454. ws::Opcode opcode;
  24455. std::string payload;
  24456. bool fin;
  24457. EXPECT_EQ(
  24458. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24459. ws::impl::FrameRead::ProtocolError);
  24460. }
  24461. // RSV3 set (0x10)
  24462. {
  24463. detail::BufferStream strm;
  24464. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24465. ws::Opcode opcode;
  24466. std::string payload;
  24467. bool fin;
  24468. EXPECT_EQ(
  24469. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24470. ws::impl::FrameRead::ProtocolError);
  24471. }
  24472. // No RSV bits set - should succeed
  24473. {
  24474. detail::BufferStream strm;
  24475. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24476. ws::Opcode opcode;
  24477. std::string payload;
  24478. bool fin;
  24479. EXPECT_EQ(
  24480. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24481. ws::impl::FrameRead::Ok);
  24482. EXPECT_EQ(ws::Opcode::Text, opcode);
  24483. EXPECT_EQ("Hello", payload);
  24484. EXPECT_TRUE(fin);
  24485. }
  24486. }
  24487. TEST(WebSocketTest, ControlFrameValidation) {
  24488. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24489. // payload length <= 125.
  24490. // Ping with FIN=0 - must be rejected
  24491. {
  24492. detail::BufferStream strm;
  24493. std::string frame;
  24494. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24495. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24496. strm.write(frame.data(), frame.size());
  24497. ws::Opcode opcode;
  24498. std::string payload;
  24499. bool fin;
  24500. EXPECT_EQ(
  24501. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24502. ws::impl::FrameRead::ProtocolError);
  24503. }
  24504. // Close with FIN=0 - must be rejected
  24505. {
  24506. detail::BufferStream strm;
  24507. std::string frame;
  24508. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24509. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24510. strm.write(frame.data(), frame.size());
  24511. ws::Opcode opcode;
  24512. std::string payload;
  24513. bool fin;
  24514. EXPECT_EQ(
  24515. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24516. ws::impl::FrameRead::ProtocolError);
  24517. }
  24518. // Ping with payload_len=126 (extended length) - must be rejected
  24519. {
  24520. detail::BufferStream strm;
  24521. std::string frame;
  24522. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24523. frame += static_cast<char>(126); // payload_len=126 (>125)
  24524. frame += static_cast<char>(0x00); // extended length high byte
  24525. frame += static_cast<char>(126); // extended length low byte
  24526. frame += std::string(126, 'x');
  24527. strm.write(frame.data(), frame.size());
  24528. ws::Opcode opcode;
  24529. std::string payload;
  24530. bool fin;
  24531. EXPECT_EQ(
  24532. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24533. ws::impl::FrameRead::ProtocolError);
  24534. }
  24535. // Ping with FIN=1 and payload_len=125 - should succeed
  24536. {
  24537. detail::BufferStream strm;
  24538. std::string frame;
  24539. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24540. frame += static_cast<char>(125); // payload_len=125
  24541. frame += std::string(125, 'x');
  24542. strm.write(frame.data(), frame.size());
  24543. ws::Opcode opcode;
  24544. std::string payload;
  24545. bool fin;
  24546. EXPECT_EQ(
  24547. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24548. ws::impl::FrameRead::Ok);
  24549. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24550. EXPECT_EQ(125u, payload.size());
  24551. EXPECT_TRUE(fin);
  24552. }
  24553. }
  24554. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24555. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24556. // length MUST be 0.
  24557. // MSB set - must be rejected
  24558. {
  24559. detail::BufferStream strm;
  24560. std::string frame;
  24561. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24562. frame += static_cast<char>(127); // 64-bit extended length
  24563. frame += static_cast<char>(0x80); // MSB set (invalid)
  24564. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24565. strm.write(frame.data(), frame.size());
  24566. ws::Opcode opcode;
  24567. std::string payload;
  24568. bool fin;
  24569. EXPECT_EQ(
  24570. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24571. ws::impl::FrameRead::ProtocolError);
  24572. }
  24573. // MSB clear - should pass length parsing (will be rejected by max_len,
  24574. // but that's a different check; use a small length to verify)
  24575. {
  24576. detail::BufferStream strm;
  24577. std::string frame;
  24578. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24579. frame += static_cast<char>(127); // 64-bit extended length
  24580. frame += std::string(7, '\0'); // high bytes = 0
  24581. frame += static_cast<char>(0x03); // length = 3
  24582. frame += "abc";
  24583. strm.write(frame.data(), frame.size());
  24584. ws::Opcode opcode;
  24585. std::string payload;
  24586. bool fin;
  24587. EXPECT_EQ(
  24588. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24589. ws::impl::FrameRead::Ok);
  24590. EXPECT_EQ(ws::Opcode::Text, opcode);
  24591. EXPECT_EQ("abc", payload);
  24592. }
  24593. }
  24594. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24595. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24596. // Valid UTF-8
  24597. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24598. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24599. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24600. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24601. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24602. // Invalid UTF-8
  24603. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24604. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24605. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24606. EXPECT_FALSE(
  24607. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24608. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24609. }
  24610. TEST(WebSocketTest, ConnectAndDisconnect) {
  24611. Server svr;
  24612. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24613. std::string msg;
  24614. while (ws.read(msg)) {}
  24615. });
  24616. auto port = svr.bind_to_any_port(HOST);
  24617. std::thread t([&]() { svr.listen_after_bind(); });
  24618. svr.wait_until_ready();
  24619. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24620. auto res = client.connect();
  24621. ASSERT_TRUE(res);
  24622. EXPECT_EQ(Error::Success, res.error());
  24623. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24624. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24625. EXPECT_TRUE(client.is_open());
  24626. client.close();
  24627. EXPECT_FALSE(client.is_open());
  24628. svr.stop();
  24629. t.join();
  24630. }
  24631. TEST(WebSocketTest, ValidURL) {
  24632. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24633. EXPECT_TRUE(ws1.is_valid());
  24634. ws::WebSocketClient ws2("ws://example.com/path");
  24635. EXPECT_TRUE(ws2.is_valid());
  24636. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24637. EXPECT_TRUE(ws3.is_valid());
  24638. #ifdef CPPHTTPLIB_SSL_ENABLED
  24639. ws::WebSocketClient wss1("wss://example.com/path");
  24640. EXPECT_TRUE(wss1.is_valid());
  24641. ws::WebSocketClient wss2("wss://example.com:443/path");
  24642. EXPECT_TRUE(wss2.is_valid());
  24643. #endif
  24644. }
  24645. TEST(WebSocketTest, InvalidURL) {
  24646. // No scheme
  24647. ws::WebSocketClient ws1("localhost:8080/path");
  24648. EXPECT_FALSE(ws1.is_valid());
  24649. // No path
  24650. ws::WebSocketClient ws2("ws://localhost:8080");
  24651. EXPECT_FALSE(ws2.is_valid());
  24652. // Empty string
  24653. ws::WebSocketClient ws3("");
  24654. EXPECT_FALSE(ws3.is_valid());
  24655. // Missing host
  24656. ws::WebSocketClient ws4("ws://:8080/path");
  24657. EXPECT_FALSE(ws4.is_valid());
  24658. // Port number overflow — should not crash
  24659. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24660. EXPECT_FALSE(ws5.is_valid());
  24661. // Port out of range
  24662. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24663. EXPECT_FALSE(ws6.is_valid());
  24664. }
  24665. TEST(WebSocketTest, UnsupportedScheme) {
  24666. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24667. ws::WebSocketClient ws1("http://localhost:8080/path");
  24668. EXPECT_FALSE(ws1.is_valid());
  24669. ws::WebSocketClient ws2("https://localhost:8080/path");
  24670. EXPECT_FALSE(ws2.is_valid());
  24671. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24672. EXPECT_FALSE(ws3.is_valid());
  24673. #else
  24674. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24675. std::invalid_argument);
  24676. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24677. std::invalid_argument);
  24678. #endif
  24679. }
  24680. TEST(WebSocketTest, ConnectWhenInvalid) {
  24681. ws::WebSocketClient ws("not a valid url");
  24682. EXPECT_FALSE(ws.is_valid());
  24683. auto res = ws.connect();
  24684. EXPECT_FALSE(res);
  24685. EXPECT_EQ(Error::Connection, res.error());
  24686. EXPECT_EQ(-1, res.status());
  24687. }
  24688. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24689. // Grab a port that is free, then close it again so nothing listens there
  24690. Server svr;
  24691. auto port = svr.bind_to_any_port(HOST);
  24692. svr.stop();
  24693. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24694. auto res = client.connect();
  24695. ASSERT_FALSE(res);
  24696. EXPECT_EQ(Error::Connection, res.error());
  24697. EXPECT_EQ(-1, res.status());
  24698. }
  24699. TEST(WebSocketTest, DefaultPort) {
  24700. ws::WebSocketClient ws1("ws://example.com/path");
  24701. EXPECT_TRUE(ws1.is_valid());
  24702. // ws:// defaults to port 80 (verified by successful parse)
  24703. #ifdef CPPHTTPLIB_SSL_ENABLED
  24704. ws::WebSocketClient ws2("wss://example.com/path");
  24705. EXPECT_TRUE(ws2.is_valid());
  24706. // wss:// defaults to port 443 (verified by successful parse)
  24707. #endif
  24708. }
  24709. TEST(WebSocketTest, IPv6LiteralAddress) {
  24710. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24711. EXPECT_TRUE(ws1.is_valid());
  24712. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24713. EXPECT_TRUE(ws2.is_valid());
  24714. }
  24715. TEST(WebSocketTest, ComplexPath) {
  24716. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24717. EXPECT_TRUE(ws1.is_valid());
  24718. ws::WebSocketClient ws2("ws://localhost:8080/");
  24719. EXPECT_TRUE(ws2.is_valid());
  24720. }
  24721. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24722. Server svr;
  24723. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24724. std::string msg;
  24725. while (ws.read(msg)) {}
  24726. });
  24727. auto port = svr.bind_to_any_port(HOST);
  24728. std::thread t([&]() { svr.listen_after_bind(); });
  24729. svr.wait_until_ready();
  24730. auto another_host = "example.com";
  24731. auto wrong_ip = "192.0.2.1";
  24732. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24733. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24734. ASSERT_TRUE(client.connect());
  24735. EXPECT_TRUE(client.is_open());
  24736. client.close();
  24737. svr.stop();
  24738. t.join();
  24739. }
  24740. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24741. Server svr;
  24742. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24743. std::string msg;
  24744. while (ws.read(msg)) {}
  24745. });
  24746. auto port = svr.bind_to_any_port(HOST);
  24747. std::thread t([&]() { svr.listen_after_bind(); });
  24748. svr.wait_until_ready();
  24749. auto wrong_ip = "192.0.2.1";
  24750. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24751. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24752. client.set_connection_timeout(1);
  24753. client.set_read_timeout(1);
  24754. client.set_write_timeout(1);
  24755. EXPECT_FALSE(client.connect());
  24756. EXPECT_FALSE(client.is_open());
  24757. svr.stop();
  24758. t.join();
  24759. }
  24760. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24761. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24762. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24763. // (RFC 6761) is only a map key and the Host header value.
  24764. auto host = "target.invalid";
  24765. Server svr;
  24766. std::string received_host;
  24767. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24768. received_host = req.get_header_value("Host");
  24769. std::string msg;
  24770. while (ws.read(msg)) {}
  24771. });
  24772. auto port = svr.bind_to_any_port(HOST);
  24773. std::thread t([&]() { svr.listen_after_bind(); });
  24774. // ASSERT_* below returns from the test body, which would leave t joinable
  24775. // and make ~thread call std::terminate.
  24776. auto se = detail::scope_exit([&] {
  24777. svr.stop();
  24778. if (t.joinable()) { t.join(); }
  24779. });
  24780. svr.wait_until_ready();
  24781. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24782. std::to_string(port) + "/ws");
  24783. client.set_direct_hostname_addr_map({{host, HOST}});
  24784. ASSERT_TRUE(client.connect());
  24785. EXPECT_TRUE(client.is_open());
  24786. client.close();
  24787. svr.stop();
  24788. t.join();
  24789. // The mapping only redirects the connection; the identity stays host_.
  24790. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24791. }
  24792. class WebSocketIntegrationTest : public ::testing::Test {
  24793. protected:
  24794. void SetUp() override {
  24795. server_ = httplib::detail::make_unique<Server>();
  24796. setup_server();
  24797. start_server();
  24798. }
  24799. void TearDown() override {
  24800. server_->stop();
  24801. if (server_thread_.joinable()) { server_thread_.join(); }
  24802. }
  24803. void setup_server() {
  24804. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24805. std::string msg;
  24806. ws::ReadResult ret;
  24807. while ((ret = ws.read(msg))) {
  24808. if (ret == ws::Binary) {
  24809. ws.send(msg.data(), msg.size());
  24810. } else {
  24811. ws.send(msg);
  24812. }
  24813. }
  24814. });
  24815. server_->WebSocket("/ws-echo-string",
  24816. [](const Request &, ws::WebSocket &ws) {
  24817. std::string msg;
  24818. while (ws.read(msg)) {
  24819. ws.send("echo: " + msg);
  24820. }
  24821. });
  24822. server_->WebSocket(
  24823. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24824. // Echo back request metadata
  24825. ws.send("path:" + req.path);
  24826. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24827. std::string msg;
  24828. while (ws.read(msg)) {}
  24829. });
  24830. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24831. std::string msg;
  24832. ws.read(msg); // wait for a message
  24833. ws.close();
  24834. });
  24835. server_->WebSocket("/ws-close-status",
  24836. [](const Request &, ws::WebSocket &ws) {
  24837. std::string msg;
  24838. ws.read(msg); // wait for a message
  24839. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24840. });
  24841. server_->WebSocket(
  24842. "/ws-subprotocol",
  24843. [](const Request &, ws::WebSocket &ws) {
  24844. std::string msg;
  24845. while (ws.read(msg)) {
  24846. ws.send(msg);
  24847. }
  24848. },
  24849. [](const std::vector<std::string> &protocols) -> std::string {
  24850. for (const auto &p : protocols) {
  24851. if (p == "graphql-ws") { return p; }
  24852. }
  24853. return "";
  24854. });
  24855. server_->WebSocket(
  24856. "/ws-subprotocol-unoffered",
  24857. [](const Request &, ws::WebSocket &ws) {
  24858. std::string msg;
  24859. while (ws.read(msg)) {
  24860. ws.send(msg);
  24861. }
  24862. },
  24863. [](const std::vector<std::string> &) -> std::string {
  24864. return "admin";
  24865. });
  24866. }
  24867. void start_server() {
  24868. port_ = server_->bind_to_any_port(HOST);
  24869. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24870. server_->wait_until_ready();
  24871. }
  24872. std::unique_ptr<Server> server_;
  24873. std::thread server_thread_;
  24874. int port_ = 0;
  24875. };
  24876. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24877. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24878. "/ws-echo");
  24879. ASSERT_TRUE(client.connect());
  24880. ASSERT_TRUE(client.is_open());
  24881. ASSERT_TRUE(client.send("Hello WebSocket"));
  24882. std::string msg;
  24883. EXPECT_EQ(ws::Text, client.read(msg));
  24884. EXPECT_EQ("Hello WebSocket", msg);
  24885. client.close();
  24886. }
  24887. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24888. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24889. "/ws-echo");
  24890. ASSERT_TRUE(client.connect());
  24891. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24892. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24893. std::string msg;
  24894. EXPECT_EQ(ws::Binary, client.read(msg));
  24895. EXPECT_EQ(binary_data, msg);
  24896. client.close();
  24897. }
  24898. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24899. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24900. "/ws-echo");
  24901. ASSERT_TRUE(client.connect());
  24902. for (int i = 0; i < 10; i++) {
  24903. auto text = "message " + std::to_string(i);
  24904. ASSERT_TRUE(client.send(text));
  24905. std::string msg;
  24906. ASSERT_TRUE(client.read(msg));
  24907. EXPECT_EQ(text, msg);
  24908. }
  24909. client.close();
  24910. }
  24911. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24912. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24913. "/ws-close");
  24914. ASSERT_TRUE(client.connect());
  24915. // Send a message to trigger the server to close
  24916. ASSERT_TRUE(client.send("trigger close"));
  24917. // The server will close, so read should return false
  24918. std::string msg;
  24919. EXPECT_FALSE(client.read(msg));
  24920. EXPECT_FALSE(client.is_open());
  24921. EXPECT_EQ(ws::CloseStatus::Normal, client.close_status());
  24922. EXPECT_EQ("", client.close_reason());
  24923. }
  24924. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24925. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24926. "/ws-echo");
  24927. ASSERT_TRUE(client.connect());
  24928. // 128KB message
  24929. std::string large_data(128 * 1024, 'X');
  24930. ASSERT_TRUE(client.send(large_data));
  24931. std::string msg;
  24932. ASSERT_TRUE(client.read(msg));
  24933. EXPECT_EQ(large_data, msg);
  24934. client.close();
  24935. }
  24936. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24937. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24938. "/ws-echo");
  24939. ASSERT_TRUE(client.connect());
  24940. const int num_threads = 4;
  24941. std::vector<std::thread> threads;
  24942. std::atomic<int> send_count{0};
  24943. for (int t = 0; t < num_threads; t++) {
  24944. threads.emplace_back([&client, &send_count, t]() {
  24945. for (int i = 0; i < 5; i++) {
  24946. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24947. if (client.send(text)) { send_count++; }
  24948. }
  24949. });
  24950. }
  24951. for (auto &th : threads) {
  24952. th.join();
  24953. }
  24954. int received = 0;
  24955. std::string msg;
  24956. while (received < send_count.load()) {
  24957. if (!client.read(msg)) { break; }
  24958. received++;
  24959. }
  24960. EXPECT_EQ(send_count.load(), received);
  24961. client.close();
  24962. }
  24963. TEST_F(WebSocketIntegrationTest, ReadString) {
  24964. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24965. "/ws-echo-string");
  24966. ASSERT_TRUE(client.connect());
  24967. ASSERT_TRUE(client.send("hello"));
  24968. std::string msg;
  24969. ASSERT_TRUE(client.read(msg));
  24970. EXPECT_EQ("echo: hello", msg);
  24971. ASSERT_TRUE(client.send("world"));
  24972. ASSERT_TRUE(client.read(msg));
  24973. EXPECT_EQ("echo: world", msg);
  24974. client.close();
  24975. }
  24976. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24977. Headers headers = {{"X-Test-Header", "test-value"}};
  24978. ws::WebSocketClient client(
  24979. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24980. ASSERT_TRUE(client.connect());
  24981. std::string msg;
  24982. ASSERT_TRUE(client.read(msg));
  24983. EXPECT_EQ("path:/ws-request-info", msg);
  24984. ASSERT_TRUE(client.read(msg));
  24985. EXPECT_EQ("header:test-value", msg);
  24986. client.close();
  24987. }
  24988. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24989. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24990. "/ws-echo");
  24991. client.set_read_timeout(1, 0); // 1 second
  24992. ASSERT_TRUE(client.connect());
  24993. // Don't send anything — server echo handler waits for a message, so read()
  24994. // should time out. The connection survives it: nothing was consumed.
  24995. std::string msg;
  24996. EXPECT_EQ(client.read(msg), ws::Timeout);
  24997. EXPECT_TRUE(client.is_open());
  24998. // And it is still usable afterwards.
  24999. EXPECT_TRUE(client.send("after timeout"));
  25000. EXPECT_EQ(client.read(msg), ws::Text);
  25001. EXPECT_EQ(msg, "after timeout");
  25002. }
  25003. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  25004. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25005. "/ws-echo");
  25006. client.set_read_timeout(1, 0);
  25007. ASSERT_TRUE(client.connect());
  25008. ASSERT_TRUE(client.send("first"));
  25009. std::string msg;
  25010. ASSERT_EQ(client.read(msg), ws::Text);
  25011. ASSERT_EQ(msg, "first");
  25012. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  25013. // not be used with a read timeout: it would reprocess the previous message.
  25014. EXPECT_EQ(client.read(msg), ws::Timeout);
  25015. EXPECT_EQ(msg, "first");
  25016. }
  25017. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  25018. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25019. "/ws-echo");
  25020. ASSERT_TRUE(client.connect());
  25021. // Setting it once the connection is open reaches the live stream, not just
  25022. // the seed for the next connect().
  25023. client.set_read_timeout(1, 0);
  25024. std::string msg;
  25025. EXPECT_EQ(client.read(msg), ws::Timeout);
  25026. EXPECT_TRUE(client.is_open());
  25027. }
  25028. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  25029. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25030. "/nonexistent");
  25031. auto res = client.connect();
  25032. EXPECT_FALSE(res);
  25033. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25034. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  25035. EXPECT_FALSE(client.is_open());
  25036. }
  25037. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  25038. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25039. "/ws-echo");
  25040. ASSERT_TRUE(client.connect());
  25041. ASSERT_TRUE(client.send(""));
  25042. std::string msg;
  25043. EXPECT_EQ(ws::Text, client.read(msg));
  25044. EXPECT_EQ("", msg);
  25045. client.close();
  25046. }
  25047. TEST_F(WebSocketIntegrationTest, Reconnect) {
  25048. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25049. "/ws-echo");
  25050. // First connection
  25051. ASSERT_TRUE(client.connect());
  25052. ASSERT_TRUE(client.send("first"));
  25053. std::string msg;
  25054. ASSERT_TRUE(client.read(msg));
  25055. EXPECT_EQ("first", msg);
  25056. client.close();
  25057. EXPECT_FALSE(client.is_open());
  25058. // Reconnect using the same client object
  25059. ASSERT_TRUE(client.connect());
  25060. ASSERT_TRUE(client.is_open());
  25061. ASSERT_TRUE(client.send("second"));
  25062. ASSERT_TRUE(client.read(msg));
  25063. EXPECT_EQ("second", msg);
  25064. client.close();
  25065. }
  25066. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  25067. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25068. "/ws-close-status");
  25069. ASSERT_TRUE(client.connect());
  25070. // Trigger the server to close with GoingAway status
  25071. ASSERT_TRUE(client.send("trigger"));
  25072. // read() should return false after receiving the close frame
  25073. std::string msg;
  25074. EXPECT_FALSE(client.read(msg));
  25075. EXPECT_FALSE(client.is_open());
  25076. EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
  25077. EXPECT_EQ("shutting down", client.close_reason());
  25078. // A copy, so it outlives a reconnect that replaces the connection
  25079. static_assert(
  25080. std::is_same<decltype(client.close_reason()), std::string>::value, "");
  25081. }
  25082. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  25083. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25084. "/ws-echo");
  25085. EXPECT_EQ(ws::CloseStatus::Abnormal, client.close_status());
  25086. ASSERT_TRUE(client.connect());
  25087. client.close(ws::CloseStatus::GoingAway, "client leaving");
  25088. EXPECT_FALSE(client.is_open());
  25089. // The server echoes the Close it receives
  25090. EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
  25091. EXPECT_EQ("client leaving", client.close_reason());
  25092. }
  25093. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  25094. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  25095. ws::WebSocketClient client(
  25096. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  25097. ASSERT_TRUE(client.connect());
  25098. // Server should have selected graphql-ws
  25099. EXPECT_EQ("graphql-ws", client.subprotocol());
  25100. client.close();
  25101. }
  25102. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  25103. Headers headers;
  25104. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  25105. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  25106. ws::WebSocketClient client(
  25107. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  25108. ASSERT_TRUE(client.connect());
  25109. // The offer on the second field line counts too, so graphql-ws is selected
  25110. EXPECT_EQ("graphql-ws", client.subprotocol());
  25111. client.close();
  25112. }
  25113. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  25114. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  25115. ws::WebSocketClient client(
  25116. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  25117. ASSERT_TRUE(client.connect());
  25118. // Server should not have selected any subprotocol
  25119. EXPECT_TRUE(client.subprotocol().empty());
  25120. client.close();
  25121. }
  25122. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  25123. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25124. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25125. "/ws-subprotocol-unoffered",
  25126. headers);
  25127. ASSERT_TRUE(client.connect());
  25128. EXPECT_TRUE(client.subprotocol().empty());
  25129. client.close();
  25130. }
  25131. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  25132. // Connect without requesting any subprotocol
  25133. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25134. "/ws-subprotocol");
  25135. ASSERT_TRUE(client.connect());
  25136. EXPECT_TRUE(client.subprotocol().empty());
  25137. client.close();
  25138. }
  25139. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  25140. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25141. "/ws-echo");
  25142. client.set_tcp_nodelay(true);
  25143. client.set_connection_timeout(3, 0);
  25144. bool socket_options_called = false;
  25145. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  25146. ASSERT_TRUE(client.connect());
  25147. ASSERT_TRUE(client.is_open());
  25148. EXPECT_TRUE(socket_options_called);
  25149. ASSERT_TRUE(client.send("hello"));
  25150. std::string msg;
  25151. auto result = client.read(msg);
  25152. EXPECT_EQ(result, ws::ReadResult::Text);
  25153. EXPECT_EQ(msg, "hello");
  25154. client.close();
  25155. }
  25156. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  25157. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  25158. "/ws-echo");
  25159. client.set_connection_timeout(std::chrono::seconds(3));
  25160. client.set_write_timeout(std::chrono::seconds(3));
  25161. // A sub-second remainder exercises the seconds/microseconds split.
  25162. client.set_read_timeout(std::chrono::milliseconds(1500));
  25163. ASSERT_TRUE(client.connect());
  25164. auto start = std::chrono::steady_clock::now();
  25165. std::string msg;
  25166. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  25167. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  25168. std::chrono::steady_clock::now() - start)
  25169. .count();
  25170. // Above 1s so that dropping the microseconds half of the split fails here.
  25171. // Ignoring the setter altogether would not reach this line at all: a client
  25172. // waits forever by default.
  25173. EXPECT_GE(elapsed, 1400);
  25174. EXPECT_LT(elapsed, 30000);
  25175. }
  25176. #ifndef _WIN32
  25177. // A send() that times out after part of the data went out returns the count
  25178. // written so far. Every byte of the frame must still be sent, or the peer reads
  25179. // the next frame's header and payload as the rest of this one.
  25180. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  25181. signal(SIGPIPE, SIG_IGN);
  25182. const std::string large(4 * 1024 * 1024, 'A');
  25183. std::atomic<bool> large_sent{false};
  25184. std::atomic<bool> small_sent{false};
  25185. Server svr;
  25186. svr.set_write_timeout(0, 500000);
  25187. svr.set_socket_options([](socket_t sock) {
  25188. int size = 8192;
  25189. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25190. reinterpret_cast<const char *>(&size), sizeof(size));
  25191. });
  25192. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25193. large_sent = ws.send(large.data(), large.size());
  25194. small_sent = ws.send("after");
  25195. std::string msg;
  25196. while (ws.read(msg)) {}
  25197. });
  25198. auto port = svr.bind_to_any_port(HOST);
  25199. std::thread t([&]() { svr.listen_after_bind(); });
  25200. auto se = detail::scope_exit([&] {
  25201. svr.stop();
  25202. t.join();
  25203. });
  25204. svr.wait_until_ready();
  25205. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25206. std::to_string(port) + "/ws");
  25207. client.set_read_timeout(5);
  25208. client.set_socket_options([](socket_t sock) {
  25209. int size = 8192;
  25210. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25211. reinterpret_cast<const char *>(&size), sizeof(size));
  25212. });
  25213. ASSERT_TRUE(client.connect());
  25214. // Outlast the server's write timeout, then drain.
  25215. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  25216. std::string msg;
  25217. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  25218. EXPECT_TRUE(msg == large);
  25219. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  25220. EXPECT_EQ("after", msg);
  25221. EXPECT_TRUE(large_sent);
  25222. EXPECT_TRUE(small_sent);
  25223. client.close();
  25224. }
  25225. // A send() that fails partway leaves a frame on the wire whose header announces
  25226. // more than was sent. Nothing may follow it, or the peer reads the next frames
  25227. // as the rest of it and a later payload's bytes as a frame of their own.
  25228. TEST(WebSocketPartialWriteTest, FailedWriteClosesConnection) {
  25229. signal(SIGPIPE, SIG_IGN);
  25230. const std::string large(4 * 1024 * 1024, 'A');
  25231. std::atomic<bool> large_sent{true};
  25232. std::atomic<bool> open_after_failure{true};
  25233. std::atomic<bool> handler_done{false};
  25234. Server svr;
  25235. svr.set_write_timeout(0, 200000);
  25236. svr.set_socket_options([](socket_t sock) {
  25237. int size = 8192;
  25238. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25239. reinterpret_cast<const char *>(&size), sizeof(size));
  25240. });
  25241. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25242. large_sent = ws.send(large.data(), large.size());
  25243. open_after_failure = ws.is_open();
  25244. handler_done = true;
  25245. });
  25246. auto port = svr.bind_to_any_port(HOST);
  25247. std::thread t([&]() { svr.listen_after_bind(); });
  25248. auto se = detail::scope_exit([&] {
  25249. svr.stop();
  25250. t.join();
  25251. });
  25252. svr.wait_until_ready();
  25253. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25254. std::to_string(port) + "/ws");
  25255. client.set_socket_options([](socket_t sock) {
  25256. int size = 8192;
  25257. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25258. reinterpret_cast<const char *>(&size), sizeof(size));
  25259. });
  25260. ASSERT_TRUE(client.connect());
  25261. // Read nothing, so the server's write times out partway through the frame.
  25262. for (int i = 0; i < 100 && !handler_done; i++) {
  25263. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  25264. }
  25265. ASSERT_TRUE(handler_done);
  25266. ASSERT_FALSE(large_sent);
  25267. EXPECT_FALSE(open_after_failure);
  25268. client.close();
  25269. }
  25270. #endif
  25271. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  25272. Server svr;
  25273. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25274. if (!req.has_header("Authorization")) {
  25275. res.status = StatusCode::Unauthorized_401;
  25276. res.set_content("Unauthorized", "text/plain");
  25277. return Server::HandlerResponse::Handled;
  25278. }
  25279. return Server::HandlerResponse::Unhandled;
  25280. });
  25281. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25282. std::string msg;
  25283. while (ws.read(msg)) {
  25284. ws.send(msg);
  25285. }
  25286. });
  25287. auto port = svr.bind_to_any_port("localhost");
  25288. std::thread t([&]() { svr.listen_after_bind(); });
  25289. svr.wait_until_ready();
  25290. // Without Authorization header - should be rejected before upgrade
  25291. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  25292. EXPECT_FALSE(client1.connect());
  25293. // The rejection is framed like any other HTTP response
  25294. {
  25295. Client cli("localhost", port);
  25296. Headers headers = {{"Upgrade", "websocket"},
  25297. {"Connection", "Upgrade"},
  25298. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25299. {"Sec-WebSocket-Version", "13"}};
  25300. auto res = cli.Get("/ws", headers);
  25301. ASSERT_TRUE(res);
  25302. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25303. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25304. EXPECT_EQ("Unauthorized", res->body);
  25305. }
  25306. // With Authorization header - should succeed
  25307. Headers headers = {{"Authorization", "Bearer token123"}};
  25308. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  25309. headers);
  25310. ASSERT_TRUE(client2.connect());
  25311. ASSERT_TRUE(client2.send("hello"));
  25312. std::string msg;
  25313. ASSERT_TRUE(client2.read(msg));
  25314. EXPECT_EQ("hello", msg);
  25315. client2.close();
  25316. svr.stop();
  25317. t.join();
  25318. }
  25319. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  25320. Server svr;
  25321. std::atomic<int> pre_routing_calls{0};
  25322. std::atomic<int> pre_request_calls{0};
  25323. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  25324. pre_routing_calls++;
  25325. if (req.path == "/handled") {
  25326. res.set_content("handled", "text/plain");
  25327. return Server::HandlerResponse::Handled;
  25328. }
  25329. return Server::HandlerResponse::Unhandled;
  25330. });
  25331. svr.set_pre_request_handler([&](const Request &, Response &) {
  25332. pre_request_calls++;
  25333. return Server::HandlerResponse::Unhandled;
  25334. });
  25335. svr.Get("/http", [](const Request &, Response &res) {
  25336. res.set_content("http", "text/plain");
  25337. });
  25338. svr.WebSocket("/ws",
  25339. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25340. auto port = svr.bind_to_any_port("localhost");
  25341. std::thread t([&]() { svr.listen_after_bind(); });
  25342. auto se = detail::scope_exit([&] {
  25343. svr.stop();
  25344. t.join();
  25345. });
  25346. svr.wait_until_ready();
  25347. Headers upgrade = {{"Upgrade", "websocket"},
  25348. {"Connection", "Upgrade"},
  25349. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25350. {"Sec-WebSocket-Version", "13"}};
  25351. auto get = [&](const char *path) {
  25352. pre_routing_calls = 0;
  25353. return Client("localhost", port).Get(path, upgrade);
  25354. };
  25355. // No WebSocket route, but an HTTP one
  25356. auto res = get("/http");
  25357. ASSERT_TRUE(res);
  25358. EXPECT_EQ(StatusCode::OK_200, res->status);
  25359. EXPECT_EQ("http", res->body);
  25360. EXPECT_EQ(1, pre_routing_calls);
  25361. EXPECT_EQ(1, pre_request_calls);
  25362. // No route at all
  25363. res = get("/none");
  25364. ASSERT_TRUE(res);
  25365. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25366. EXPECT_EQ(1, pre_routing_calls);
  25367. // Answered by the pre-routing handler
  25368. res = get("/handled");
  25369. ASSERT_TRUE(res);
  25370. EXPECT_EQ(StatusCode::OK_200, res->status);
  25371. EXPECT_EQ("handled", res->body);
  25372. EXPECT_EQ(1, pre_routing_calls);
  25373. // A WebSocket route
  25374. pre_routing_calls = 0;
  25375. pre_request_calls = 0;
  25376. {
  25377. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25378. "/ws");
  25379. ASSERT_TRUE(client.connect());
  25380. std::string msg;
  25381. ASSERT_TRUE(client.read(msg));
  25382. EXPECT_EQ("ws", msg);
  25383. client.close();
  25384. }
  25385. EXPECT_EQ(1, pre_routing_calls);
  25386. EXPECT_EQ(1, pre_request_calls);
  25387. }
  25388. // An upgrade request answered by a hook leaves its body unread, so that body
  25389. // must not be served as the next request on the connection.
  25390. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25391. Server svr;
  25392. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25393. if (req.path == "/pre-routing") {
  25394. res.set_content("pre-routing", "text/plain");
  25395. return Server::HandlerResponse::Handled;
  25396. }
  25397. return Server::HandlerResponse::Unhandled;
  25398. });
  25399. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25400. if (req.matched_route == "/pre-request") {
  25401. res.set_content("pre-request", "text/plain");
  25402. return Server::HandlerResponse::Handled;
  25403. }
  25404. return Server::HandlerResponse::Unhandled;
  25405. });
  25406. svr.Get("/smuggled", [](const Request &, Response &res) {
  25407. res.set_content("smuggled", "text/plain");
  25408. });
  25409. svr.WebSocket("/pre-request",
  25410. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25411. auto port = svr.bind_to_any_port(HOST);
  25412. std::thread t([&]() { svr.listen_after_bind(); });
  25413. auto se = detail::scope_exit([&] {
  25414. svr.stop();
  25415. t.join();
  25416. });
  25417. svr.wait_until_ready();
  25418. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25419. for (auto path : {"/pre-routing", "/pre-request"}) {
  25420. std::string req = std::string("GET ") + path +
  25421. " HTTP/1.1\r\n"
  25422. "Host: localhost\r\n"
  25423. "Upgrade: websocket\r\n"
  25424. "Connection: Upgrade\r\n"
  25425. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25426. "Sec-WebSocket-Version: 13\r\n"
  25427. "Content-Length: " +
  25428. std::to_string(body.size()) + "\r\n\r\n" + body;
  25429. std::string res;
  25430. ASSERT_TRUE(send_request(5, req, &res, port));
  25431. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25432. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25433. // Only one response, and the body was not served as a request
  25434. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25435. }
  25436. }
  25437. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25438. Server svr;
  25439. std::atomic<int> pre_request_calls{0};
  25440. std::atomic<bool> route_matched{false};
  25441. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25442. pre_request_calls++;
  25443. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25444. if (req.get_header_value("Authorization") != "Bearer token123") {
  25445. res.status = StatusCode::Unauthorized_401;
  25446. res.set_content("Unauthorized", "text/plain");
  25447. return Server::HandlerResponse::Handled;
  25448. }
  25449. return Server::HandlerResponse::Unhandled;
  25450. });
  25451. std::atomic<bool> handler_called{false};
  25452. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25453. handler_called = true;
  25454. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25455. });
  25456. auto port = svr.bind_to_any_port("localhost");
  25457. std::thread t([&]() { svr.listen_after_bind(); });
  25458. svr.wait_until_ready();
  25459. // Without Authorization header - should be rejected before upgrade
  25460. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25461. "/ws/1");
  25462. EXPECT_FALSE(client1.connect());
  25463. EXPECT_FALSE(handler_called);
  25464. EXPECT_EQ(1, pre_request_calls);
  25465. EXPECT_TRUE(route_matched);
  25466. // The rejection is an ordinary HTTP response, not a protocol switch
  25467. {
  25468. Client cli("localhost", port);
  25469. Headers headers = {{"Upgrade", "websocket"},
  25470. {"Connection", "Upgrade"},
  25471. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25472. {"Sec-WebSocket-Version", "13"}};
  25473. auto res = cli.Get("/ws/1", headers);
  25474. ASSERT_TRUE(res);
  25475. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25476. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25477. EXPECT_EQ("Unauthorized", res->body);
  25478. }
  25479. EXPECT_FALSE(handler_called);
  25480. // With Authorization header - should succeed
  25481. Headers headers = {{"Authorization", "Bearer token123"}};
  25482. ws::WebSocketClient client2(
  25483. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25484. ASSERT_TRUE(client2.connect());
  25485. std::string msg;
  25486. ASSERT_TRUE(client2.read(msg));
  25487. EXPECT_EQ("/ws/:id 2", msg);
  25488. EXPECT_TRUE(handler_called);
  25489. client2.close();
  25490. svr.stop();
  25491. t.join();
  25492. }
  25493. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25494. static Headers websocket_upgrade_headers() {
  25495. return {{"Upgrade", "websocket"},
  25496. {"Connection", "Upgrade"},
  25497. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25498. {"Sec-WebSocket-Version", "13"},
  25499. {"Sec-WebSocket-Protocol", "chat"}};
  25500. }
  25501. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25502. Server svr;
  25503. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25504. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25505. return Server::HandlerResponse::Unhandled;
  25506. });
  25507. svr.set_pre_request_handler([](const Request &req, Response &) {
  25508. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25509. return Server::HandlerResponse::Unhandled;
  25510. });
  25511. svr.set_exception_handler(
  25512. [](const Request &, Response &res, std::exception_ptr ep) {
  25513. try {
  25514. std::rethrow_exception(ep);
  25515. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25516. });
  25517. auto handler = [](const Request &, ws::WebSocket &) {};
  25518. svr.WebSocket("/pre-routing", handler);
  25519. svr.WebSocket("/pre-request", handler);
  25520. svr.WebSocket("/sub-protocol", handler,
  25521. [](const std::vector<std::string> &) -> std::string {
  25522. throw std::runtime_error("/sub-protocol");
  25523. });
  25524. auto port = svr.bind_to_any_port(HOST);
  25525. ASSERT_GT(port, 0);
  25526. thread t = thread([&] { svr.listen_after_bind(); });
  25527. auto se = detail::scope_exit([&] {
  25528. svr.stop();
  25529. t.join();
  25530. ASSERT_FALSE(svr.is_running());
  25531. });
  25532. svr.wait_until_ready();
  25533. Client cli(HOST, port);
  25534. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25535. auto res = cli.Get(path, websocket_upgrade_headers());
  25536. if (!res) {
  25537. ADD_FAILURE() << path << ": " << to_string(res.error());
  25538. continue;
  25539. }
  25540. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25541. EXPECT_EQ(path, res->body);
  25542. }
  25543. }
  25544. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25545. Server svr;
  25546. svr.set_pre_routing_handler(
  25547. [](const Request &, Response &) -> Server::HandlerResponse {
  25548. throw std::runtime_error("pre-routing");
  25549. });
  25550. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25551. auto port = svr.bind_to_any_port(HOST);
  25552. ASSERT_GT(port, 0);
  25553. thread t = thread([&] { svr.listen_after_bind(); });
  25554. auto se = detail::scope_exit([&] {
  25555. svr.stop();
  25556. t.join();
  25557. ASSERT_FALSE(svr.is_running());
  25558. });
  25559. svr.wait_until_ready();
  25560. Client cli(HOST, port);
  25561. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25562. ASSERT_TRUE(res) << to_string(res.error());
  25563. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25564. }
  25565. #endif
  25566. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25567. Server svr;
  25568. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25569. // A read timeout is how a handler gets control back. Without it, a handler
  25570. // parked in read() can never write on the connection it is reading.
  25571. ws.set_read_timeout(std::chrono::milliseconds(100));
  25572. std::string msg;
  25573. while (ws.is_open()) {
  25574. auto r = ws.read(msg);
  25575. if (r == httplib::ws::Timeout) {
  25576. ws.send("tick");
  25577. continue;
  25578. }
  25579. if (r == httplib::ws::Fail) { break; }
  25580. ws.send(msg);
  25581. }
  25582. });
  25583. auto port = svr.bind_to_any_port("localhost");
  25584. std::thread t([&]() { svr.listen_after_bind(); });
  25585. svr.wait_until_ready();
  25586. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25587. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25588. ASSERT_TRUE(client.connect());
  25589. // The client sends nothing, so anything it receives came out of the
  25590. // handler's timeout path.
  25591. std::string msg;
  25592. ASSERT_EQ(client.read(msg), ws::Text);
  25593. EXPECT_EQ("tick", msg);
  25594. client.close();
  25595. svr.stop();
  25596. t.join();
  25597. }
  25598. // Stream::read may return fewer bytes than asked for. This is that contract at
  25599. // its worst -- one byte per call -- which is what a frame header straddling a
  25600. // read buffer's boundary looks like to the frame parser.
  25601. class WsByteAtATimeStream : public Stream {
  25602. public:
  25603. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25604. bool is_readable() const override { return true; }
  25605. bool wait_readable() const override { return true; }
  25606. bool wait_writable() const override { return true; }
  25607. ssize_t read(char *ptr, size_t size) override {
  25608. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25609. *ptr = data_[pos_++];
  25610. return 1;
  25611. }
  25612. ssize_t write(const char *, size_t size) override {
  25613. return static_cast<ssize_t>(size);
  25614. }
  25615. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25616. ip = "127.0.0.1";
  25617. port = 0;
  25618. }
  25619. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25620. ip = "127.0.0.1";
  25621. port = 0;
  25622. }
  25623. socket_t socket() const override { return INVALID_SOCKET; }
  25624. time_t duration() const override { return 0; }
  25625. private:
  25626. std::string data_;
  25627. size_t pos_ = 0;
  25628. };
  25629. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25630. // The payload uses the 16-bit extended length, so the header, the length
  25631. // and the mask key are all multi-byte fields here. Each used to be read
  25632. // with a single read() call, which fails as soon as one is split. The
  25633. // payload is also a little over one read chunk, so it is read in two.
  25634. std::string body;
  25635. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25636. body += static_cast<char>(i % 251);
  25637. }
  25638. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25639. std::string frame;
  25640. frame += static_cast<char>(0x81); // FIN + Text
  25641. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25642. frame += static_cast<char>(body.size() >> 8);
  25643. frame += static_cast<char>(body.size() & 0xff);
  25644. for (size_t i = 0; i < 4; i++) {
  25645. frame += static_cast<char>(mask[i]);
  25646. }
  25647. for (size_t i = 0; i < body.size(); i++) {
  25648. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25649. }
  25650. WsByteAtATimeStream strm(frame);
  25651. ws::Opcode opcode;
  25652. std::string payload;
  25653. bool fin = false;
  25654. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25655. /*expect_masked=*/true, body.size()),
  25656. ws::impl::FrameRead::Ok);
  25657. EXPECT_TRUE(fin);
  25658. EXPECT_EQ(opcode, ws::Opcode::Text);
  25659. EXPECT_EQ(payload, body);
  25660. }
  25661. // Keeps what is written, counting the writes, and reads it back.
  25662. class WsWriteCountingStream : public Stream {
  25663. public:
  25664. bool is_readable() const override { return true; }
  25665. bool wait_readable() const override { return true; }
  25666. bool wait_writable() const override { return true; }
  25667. ssize_t read(char *ptr, size_t size) override {
  25668. auto n = (std::min)(size, data_.size() - pos_);
  25669. if (n == 0) { return 0; }
  25670. memcpy(ptr, data_.data() + pos_, n);
  25671. pos_ += n;
  25672. return static_cast<ssize_t>(n);
  25673. }
  25674. ssize_t write(const char *ptr, size_t size) override {
  25675. writes++;
  25676. data_.append(ptr, size);
  25677. return static_cast<ssize_t>(size);
  25678. }
  25679. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25680. ip = "127.0.0.1";
  25681. port = 0;
  25682. }
  25683. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25684. ip = "127.0.0.1";
  25685. port = 0;
  25686. }
  25687. socket_t socket() const override { return INVALID_SOCKET; }
  25688. time_t duration() const override { return 0; }
  25689. int writes = 0;
  25690. private:
  25691. std::string data_;
  25692. size_t pos_ = 0;
  25693. };
  25694. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25695. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25696. // masked and not, reads back as written; a payload over one chunk follows
  25697. // its first in more writes.
  25698. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25699. for (auto mask : {false, true}) {
  25700. std::string body(len, '\0');
  25701. for (size_t i = 0; i < len; i++) {
  25702. body[i] = static_cast<char>(i % 251);
  25703. }
  25704. WsWriteCountingStream strm;
  25705. ASSERT_TRUE(detail::write_websocket_frame(
  25706. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25707. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25708. ws::Opcode opcode;
  25709. std::string payload;
  25710. bool fin = false;
  25711. ASSERT_EQ(
  25712. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25713. ws::impl::FrameRead::Ok)
  25714. << len << " " << mask;
  25715. EXPECT_TRUE(fin);
  25716. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25717. EXPECT_EQ(body, payload) << len << " " << mask;
  25718. }
  25719. }
  25720. }
  25721. // Hands out its pieces one read at a time, timing out between each two.
  25722. class WsTimeoutBetweenPiecesStream : public Stream {
  25723. public:
  25724. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25725. : pieces_(std::move(pieces)) {}
  25726. bool is_readable() const override { return true; }
  25727. bool wait_readable() const override { return true; }
  25728. bool wait_writable() const override { return true; }
  25729. ssize_t read(char *ptr, size_t size) override {
  25730. if (time_out_) {
  25731. time_out_ = false;
  25732. error_ = Error::Timeout;
  25733. return -1;
  25734. }
  25735. if (i_ >= pieces_.size()) {
  25736. error_ = Error::ConnectionClosed;
  25737. return 0;
  25738. }
  25739. auto &piece = pieces_[i_];
  25740. auto n = (std::min)(size, piece.size() - at_);
  25741. memcpy(ptr, piece.data() + at_, n);
  25742. at_ += n;
  25743. if (at_ == piece.size()) {
  25744. i_++;
  25745. at_ = 0;
  25746. time_out_ = true;
  25747. }
  25748. return static_cast<ssize_t>(n);
  25749. }
  25750. ssize_t write(const char *, size_t size) override {
  25751. return static_cast<ssize_t>(size);
  25752. }
  25753. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25754. ip = "127.0.0.1";
  25755. port = 0;
  25756. }
  25757. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25758. ip = "127.0.0.1";
  25759. port = 0;
  25760. }
  25761. socket_t socket() const override { return INVALID_SOCKET; }
  25762. time_t duration() const override { return 0; }
  25763. private:
  25764. std::vector<std::string> pieces_;
  25765. size_t i_ = 0;
  25766. size_t at_ = 0;
  25767. bool time_out_ = false;
  25768. };
  25769. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25770. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25771. std::string frame = "\x81\x85";
  25772. frame.append(4, '\0');
  25773. frame += "Hello";
  25774. // The header's first byte, then its second with half the mask key, then
  25775. // the rest
  25776. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25777. frame.substr(4)};
  25778. WsTimeoutBetweenPiecesStream strm(pieces);
  25779. ws::impl::FrameReader reader;
  25780. ws::Opcode opcode;
  25781. std::string payload;
  25782. bool fin = false;
  25783. for (int i = 0; i < 2; i++) {
  25784. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25785. reader.read(strm, opcode, payload, fin, true, 0));
  25786. EXPECT_TRUE(reader.begun());
  25787. }
  25788. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25789. reader.read(strm, opcode, payload, fin, true, 0));
  25790. EXPECT_FALSE(reader.begun());
  25791. EXPECT_TRUE(fin);
  25792. EXPECT_EQ(ws::Opcode::Text, opcode);
  25793. EXPECT_EQ("Hello", payload);
  25794. // Read in one go, the frame cannot be gone on with after a timeout
  25795. WsTimeoutBetweenPiecesStream again(pieces);
  25796. EXPECT_EQ(
  25797. ws::impl::FrameRead::Fail,
  25798. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25799. }
  25800. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25801. std::string body(2000, 'x');
  25802. std::string frame;
  25803. frame += static_cast<char>(0x82); // FIN + Binary
  25804. frame += static_cast<char>(126); // 16-bit length follows
  25805. frame += static_cast<char>(body.size() >> 8);
  25806. frame += static_cast<char>(body.size() & 0xff);
  25807. frame += body;
  25808. detail::BufferStream strm;
  25809. strm.write(frame.data(), frame.size());
  25810. ws::Opcode opcode;
  25811. std::string payload;
  25812. bool fin;
  25813. EXPECT_EQ(
  25814. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25815. ws::impl::FrameRead::Ok);
  25816. EXPECT_EQ(body, payload);
  25817. }
  25818. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25819. // The header announces the largest payload allowed, and only 3 bytes of it
  25820. // ever arrive.
  25821. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25822. std::string frame;
  25823. frame += static_cast<char>(0x82); // FIN + Binary
  25824. frame += static_cast<char>(127); // 64-bit length follows
  25825. for (int shift = 56; shift >= 0; shift -= 8) {
  25826. frame += static_cast<char>((len >> shift) & 0xff);
  25827. }
  25828. frame += "abc";
  25829. detail::BufferStream strm;
  25830. strm.write(frame.data(), frame.size());
  25831. ws::Opcode opcode;
  25832. std::string payload;
  25833. bool fin;
  25834. EXPECT_EQ(
  25835. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25836. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25837. ws::impl::FrameRead::Fail);
  25838. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25839. }
  25840. TEST(WebSocketTest, QueryStringInHandshake) {
  25841. Server svr;
  25842. std::mutex mtx;
  25843. std::string received_target;
  25844. std::string received_token;
  25845. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25846. {
  25847. std::lock_guard<std::mutex> lock(mtx);
  25848. received_target = req.target;
  25849. if (req.has_param("token")) {
  25850. received_token = req.get_param_value("token");
  25851. }
  25852. }
  25853. std::string msg;
  25854. while (ws.read(msg)) {
  25855. ws.send(msg);
  25856. }
  25857. });
  25858. auto port = svr.bind_to_any_port("localhost");
  25859. std::thread t([&]() { svr.listen_after_bind(); });
  25860. svr.wait_until_ready();
  25861. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25862. "/ws?token=ABC&session=123");
  25863. ASSERT_TRUE(client.connect());
  25864. // Round-trip ensures the handler has run and captured the request.
  25865. ASSERT_TRUE(client.send("hello"));
  25866. std::string msg;
  25867. ASSERT_TRUE(client.read(msg));
  25868. EXPECT_EQ("hello", msg);
  25869. client.close();
  25870. {
  25871. std::lock_guard<std::mutex> lock(mtx);
  25872. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25873. EXPECT_EQ("ABC", received_token);
  25874. }
  25875. svr.stop();
  25876. t.join();
  25877. }
  25878. // Run a handshake against a throwaway server and hand the request the server
  25879. // received back to the caller, so tests can assert on the headers the client
  25880. // actually put on the wire.
  25881. static void capture_websocket_handshake_request(
  25882. const Headers &client_headers,
  25883. std::function<void(const Request &, int port)> verify) {
  25884. Server svr;
  25885. std::mutex mtx;
  25886. Request received;
  25887. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25888. {
  25889. std::lock_guard<std::mutex> lock(mtx);
  25890. received = req;
  25891. }
  25892. std::string msg;
  25893. while (ws.read(msg)) {
  25894. ws.send(msg);
  25895. }
  25896. });
  25897. auto port = svr.bind_to_any_port("localhost");
  25898. std::thread t([&]() { svr.listen_after_bind(); });
  25899. auto se = detail::scope_exit([&] {
  25900. svr.stop();
  25901. t.join();
  25902. });
  25903. svr.wait_until_ready();
  25904. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25905. client_headers);
  25906. ASSERT_TRUE(client.connect());
  25907. ASSERT_TRUE(client.send("hello"));
  25908. std::string msg;
  25909. ASSERT_TRUE(client.read(msg));
  25910. client.close();
  25911. {
  25912. std::lock_guard<std::mutex> lock(mtx);
  25913. verify(received, port);
  25914. }
  25915. }
  25916. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25917. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25918. // Non-default port must be present in the Host header. Default ports
  25919. // (80/443) are omitted; that logic is covered by
  25920. // MakeHostAndPortStringTest.
  25921. EXPECT_EQ("localhost:" + std::to_string(port),
  25922. req.get_header_value("Host"));
  25923. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25924. req.get_header_value("User-Agent"));
  25925. EXPECT_FALSE(req.has_header("Accept"));
  25926. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25927. EXPECT_FALSE(req.has_header("Content-Length"));
  25928. });
  25929. }
  25930. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25931. capture_websocket_handshake_request(
  25932. {{"Host", "example.com"},
  25933. {"User-Agent", "custom-agent"},
  25934. {"X-Custom", "value"}},
  25935. [](const Request &req, int) {
  25936. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25937. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25938. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25939. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25940. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25941. });
  25942. }
  25943. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25944. capture_websocket_handshake_request(
  25945. {{"Upgrade", "bogus"},
  25946. {"Connection", "close"},
  25947. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25948. {"Sec-WebSocket-Version", "8"}},
  25949. [](const Request &req, int) {
  25950. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25951. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25952. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25953. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25954. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25955. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25956. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25957. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25958. req.get_header_value("Sec-WebSocket-Key"));
  25959. });
  25960. }
  25961. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25962. // A header the client refuses to send must abort the handshake before any
  25963. // part of it reaches the wire; a lone request line would otherwise sit in
  25964. // the peer's buffer as a truncated request.
  25965. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25966. ASSERT_NE(INVALID_SOCKET, srv);
  25967. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25968. sockaddr_in addr{};
  25969. addr.sin_family = AF_INET;
  25970. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25971. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25972. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25973. ASSERT_EQ(0, ::listen(srv, 1));
  25974. sockaddr_in bound{};
  25975. socklen_t bound_len = sizeof(bound);
  25976. ASSERT_EQ(
  25977. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25978. auto port = ntohs(bound.sin_port);
  25979. ssize_t received = -1;
  25980. std::thread t([&] {
  25981. // Bound every blocking call so a regression fails the test with a bad
  25982. // value instead of hanging the suite.
  25983. fd_set rfds;
  25984. FD_ZERO(&rfds);
  25985. FD_SET(srv, &rfds);
  25986. timeval tv{5, 0};
  25987. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25988. 0) {
  25989. return;
  25990. }
  25991. sockaddr_in cli_addr{};
  25992. socklen_t cli_len = sizeof(cli_addr);
  25993. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25994. if (cli == INVALID_SOCKET) { return; }
  25995. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25996. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25997. char buf[4096];
  25998. received = ::recv(cli, buf, sizeof(buf), 0);
  25999. });
  26000. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  26001. // connect() has already shut the socket down by the time it returns false,
  26002. // so the peer sees EOF without waiting for the client to be destroyed.
  26003. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  26004. {{"X-Bad", "a\r\nInjected: 1"}});
  26005. EXPECT_FALSE(client.connect());
  26006. t.join();
  26007. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  26008. EXPECT_EQ(0, received);
  26009. }
  26010. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  26011. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  26012. // contains "upgrade" as a substring is a different token and must not
  26013. // start a WebSocket handshake.
  26014. auto make_request = [](const std::vector<std::string> &connection_values) {
  26015. Request req;
  26016. req.method = "GET";
  26017. req.headers.emplace("Upgrade", "websocket");
  26018. for (const auto &value : connection_values) {
  26019. req.headers.emplace("Connection", value);
  26020. }
  26021. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  26022. req.headers.emplace("Sec-WebSocket-Version", "13");
  26023. return req;
  26024. };
  26025. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  26026. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  26027. EXPECT_TRUE(
  26028. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  26029. EXPECT_TRUE(
  26030. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  26031. EXPECT_TRUE(
  26032. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  26033. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  26034. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  26035. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  26036. EXPECT_FALSE(
  26037. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  26038. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  26039. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  26040. }
  26041. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  26042. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  26043. // asks recipients to match each protocol-name case-insensitively, and RFC
  26044. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  26045. // client naming websocket alongside another protocol, or on a second field
  26046. // line, is offering websocket; a value that merely contains "websocket" as a
  26047. // substring is a different protocol name and is not.
  26048. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  26049. Request req;
  26050. req.method = "GET";
  26051. for (const auto &value : upgrade_values) {
  26052. req.headers.emplace("Upgrade", value);
  26053. }
  26054. req.headers.emplace("Connection", "Upgrade");
  26055. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  26056. req.headers.emplace("Sec-WebSocket-Version", "13");
  26057. return req;
  26058. };
  26059. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  26060. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  26061. EXPECT_TRUE(
  26062. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  26063. EXPECT_TRUE(
  26064. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  26065. EXPECT_TRUE(
  26066. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  26067. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  26068. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  26069. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  26070. EXPECT_FALSE(
  26071. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  26072. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  26073. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  26074. }
  26075. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  26076. Server svr;
  26077. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  26078. auto port = svr.bind_to_any_port("localhost");
  26079. std::thread t([&]() { svr.listen_after_bind(); });
  26080. auto se = detail::scope_exit([&] {
  26081. svr.stop();
  26082. t.join();
  26083. });
  26084. svr.wait_until_ready();
  26085. Headers headers = {{"Upgrade", "websocket"},
  26086. {"Connection", "notupgrade"},
  26087. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  26088. {"Sec-WebSocket-Version", "13"}};
  26089. Client cli("localhost", port);
  26090. auto res = cli.Get("/ws", headers);
  26091. // The route exists only as a WebSocket route, so a request that fails the
  26092. // handshake check falls through to ordinary routing.
  26093. ASSERT_TRUE(res);
  26094. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  26095. }
  26096. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  26097. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  26098. // Connection value is the only thing left for the client to reject.
  26099. Server svr;
  26100. svr.Get("/ws", [](const Request &req, Response &res) {
  26101. res.status = StatusCode::SwitchingProtocol_101;
  26102. res.set_header("Upgrade", "websocket");
  26103. res.set_header("Connection", "notupgrade");
  26104. res.set_header("Sec-WebSocket-Accept",
  26105. detail::websocket_accept_key(
  26106. req.get_header_value("Sec-WebSocket-Key")));
  26107. });
  26108. auto port = svr.bind_to_any_port("localhost");
  26109. std::thread t([&]() { svr.listen_after_bind(); });
  26110. auto se = detail::scope_exit([&] {
  26111. svr.stop();
  26112. t.join();
  26113. });
  26114. svr.wait_until_ready();
  26115. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  26116. auto res = client.connect();
  26117. EXPECT_FALSE(res);
  26118. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  26119. EXPECT_FALSE(client.is_open());
  26120. }
  26121. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  26122. Server svr;
  26123. svr.Get("/ws", [](const Request &req, Response &res) {
  26124. res.status = StatusCode::SwitchingProtocol_101;
  26125. res.set_header("Upgrade", "websocket");
  26126. res.set_header("Connection", "Upgrade");
  26127. res.set_header("Sec-WebSocket-Accept",
  26128. detail::websocket_accept_key(
  26129. req.get_header_value("Sec-WebSocket-Key")));
  26130. res.set_header("Sec-WebSocket-Protocol", "admin");
  26131. });
  26132. auto port = svr.bind_to_any_port("localhost");
  26133. std::thread t([&]() { svr.listen_after_bind(); });
  26134. auto se = detail::scope_exit([&] {
  26135. svr.stop();
  26136. t.join();
  26137. });
  26138. svr.wait_until_ready();
  26139. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  26140. // Server selects a subprotocol the client never offered
  26141. {
  26142. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  26143. ws::WebSocketClient client(url, headers);
  26144. auto res = client.connect();
  26145. EXPECT_FALSE(res);
  26146. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  26147. EXPECT_FALSE(client.is_open());
  26148. EXPECT_TRUE(client.subprotocol().empty());
  26149. }
  26150. // Client offered none but the server named one anyway
  26151. {
  26152. ws::WebSocketClient client(url);
  26153. auto res = client.connect();
  26154. EXPECT_FALSE(res);
  26155. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  26156. EXPECT_FALSE(client.is_open());
  26157. EXPECT_TRUE(client.subprotocol().empty());
  26158. }
  26159. }
  26160. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  26161. // The socket path doubles as the URL host, so it must not contain '/'.
  26162. const char *shard = getenv("GTEST_SHARD_INDEX");
  26163. const std::string sock_path =
  26164. shard ? std::string("httplib-ws-") + shard + ".sock"
  26165. : std::string("httplib-ws.sock");
  26166. std::remove(sock_path.c_str());
  26167. Server svr;
  26168. std::mutex mtx;
  26169. std::string received_host;
  26170. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  26171. {
  26172. std::lock_guard<std::mutex> lock(mtx);
  26173. received_host = req.get_header_value("Host");
  26174. }
  26175. std::string msg;
  26176. while (ws.read(msg)) {
  26177. ws.send(msg);
  26178. }
  26179. });
  26180. svr.set_address_family(AF_UNIX);
  26181. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  26182. auto se = detail::scope_exit([&] {
  26183. svr.stop();
  26184. t.join();
  26185. std::remove(sock_path.c_str());
  26186. });
  26187. svr.wait_until_ready();
  26188. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  26189. client.set_address_family(AF_UNIX);
  26190. ASSERT_TRUE(client.connect());
  26191. ASSERT_TRUE(client.send("hello"));
  26192. std::string msg;
  26193. ASSERT_TRUE(client.read(msg));
  26194. client.close();
  26195. {
  26196. std::lock_guard<std::mutex> lock(mtx);
  26197. // There is no host:port for a Unix socket, so the same "localhost"
  26198. // placeholder the HTTP client uses is expected.
  26199. EXPECT_EQ("localhost", received_host);
  26200. }
  26201. }
  26202. // Two threads must never parse WebSocket frames from the same stream.
  26203. // close() used to read the peer's Close reply with its own frame read, so it
  26204. // raced a reader thread that was in the middle of a payload: the payload loop
  26205. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  26206. // so bytes taken by close() were replaced with bytes from further along the
  26207. // stream. The message kept its length and silently changed content.
  26208. //
  26209. // The raw peer below sends a frame header plus part of the payload, waits for
  26210. // the handler to call close(), and only then sends the rest. Whichever thread
  26211. // would win the race for those bytes, the message must arrive intact, because
  26212. // close() must not touch the stream while read() owns it.
  26213. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  26214. #ifndef _WIN32
  26215. signal(SIGPIPE, SIG_IGN);
  26216. #endif
  26217. const size_t payload_len = 120; // fits the 7-bit length field
  26218. const size_t prefix_len = 8;
  26219. const int attempts = 8;
  26220. std::string expected(payload_len, '\0');
  26221. for (size_t i = 0; i < payload_len; i++) {
  26222. expected[i] = static_cast<char>('a' + i % 26);
  26223. }
  26224. std::atomic<bool> peer_stalled{false};
  26225. std::atomic<bool> handler_done{false};
  26226. std::mutex received_mutex;
  26227. std::vector<std::string> received;
  26228. // Bound every wait, so a regression fails the test instead of hanging the
  26229. // suite.
  26230. auto wait_for = [](const std::atomic<bool> &flag) {
  26231. for (int i = 0; i < 500 && !flag; i++) {
  26232. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26233. }
  26234. };
  26235. Server svr;
  26236. svr.set_websocket_ping_interval(0);
  26237. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26238. std::thread reader([&]() {
  26239. std::string msg;
  26240. while (ws.read(msg)) {
  26241. std::lock_guard<std::mutex> guard(received_mutex);
  26242. received.push_back(msg);
  26243. }
  26244. });
  26245. // Wait until the peer stalls mid-payload, so the reader thread is parked
  26246. // inside a frame when close() runs.
  26247. wait_for(peer_stalled);
  26248. ws.close();
  26249. reader.join();
  26250. handler_done = true;
  26251. });
  26252. auto port = svr.bind_to_any_port("127.0.0.1");
  26253. std::thread t([&]() { svr.listen_after_bind(); });
  26254. auto se = detail::scope_exit([&] {
  26255. svr.stop();
  26256. t.join();
  26257. });
  26258. svr.wait_until_ready();
  26259. auto send_bytes = [](socket_t s, const std::string &data) {
  26260. #ifdef _WIN32
  26261. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  26262. #else
  26263. auto n = ::send(s, data.data(), data.size(), 0);
  26264. #endif
  26265. return n == static_cast<decltype(n)>(data.size());
  26266. };
  26267. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  26268. // Every length used here fits the 7-bit length field.
  26269. auto masked_header = [](uint8_t first_byte, size_t len) {
  26270. std::string h;
  26271. h += static_cast<char>(first_byte);
  26272. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  26273. h.append(4, '\0'); // mask key
  26274. return h;
  26275. };
  26276. for (int attempt = 0; attempt < attempts; attempt++) {
  26277. peer_stalled = false;
  26278. handler_done = false;
  26279. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26280. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  26281. auto se_sock = detail::scope_exit([&] {
  26282. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  26283. });
  26284. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26285. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  26286. sockaddr_in addr{};
  26287. addr.sin_family = AF_INET;
  26288. addr.sin_port = htons(static_cast<uint16_t>(port));
  26289. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26290. ASSERT_EQ(
  26291. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  26292. << "attempt " << attempt;
  26293. ASSERT_TRUE(send_bytes(sock,
  26294. "GET /ws HTTP/1.1\r\n"
  26295. "Host: 127.0.0.1\r\n"
  26296. "Upgrade: websocket\r\n"
  26297. "Connection: Upgrade\r\n"
  26298. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26299. "Sec-WebSocket-Version: 13\r\n"
  26300. "\r\n"))
  26301. << "attempt " << attempt;
  26302. std::string response;
  26303. while (response.find("\r\n\r\n") == std::string::npos) {
  26304. char buf[512];
  26305. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  26306. if (n <= 0) { break; }
  26307. response.append(buf, static_cast<size_t>(n));
  26308. }
  26309. ASSERT_NE(std::string::npos, response.find(" 101 "))
  26310. << "attempt " << attempt;
  26311. // Send the header of a Binary message but only the first prefix_len bytes
  26312. // of its payload, leaving the reader thread stalled inside the payload.
  26313. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  26314. expected.substr(0, prefix_len)))
  26315. << "attempt " << attempt;
  26316. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26317. peer_stalled = true;
  26318. // Let close() send its Close frame and park in its own read before the
  26319. // rest of the payload arrives, so both threads are waiting for it.
  26320. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26321. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  26322. close_frame += static_cast<char>(0x03); // status 1000
  26323. close_frame += static_cast<char>(0xE8);
  26324. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  26325. << "attempt " << attempt;
  26326. // Closing the peer releases the reader thread even on the buggy path,
  26327. // where it waits for bytes another thread already consumed.
  26328. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26329. detail::close_socket(sock);
  26330. sock = INVALID_SOCKET;
  26331. wait_for(handler_done);
  26332. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  26333. }
  26334. std::lock_guard<std::mutex> guard(received_mutex);
  26335. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  26336. << "a message in flight when close() ran was dropped";
  26337. for (size_t i = 0; i < received.size(); i++) {
  26338. EXPECT_EQ(expected, received[i]) << "message " << i;
  26339. }
  26340. }
  26341. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  26342. // returning the socket, or INVALID_SOCKET.
  26343. static socket_t connect_raw_websocket(int port, const std::string &path) {
  26344. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26345. if (sock == INVALID_SOCKET) { return sock; }
  26346. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26347. sockaddr_in addr{};
  26348. addr.sin_family = AF_INET;
  26349. addr.sin_port = htons(static_cast<uint16_t>(port));
  26350. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26351. std::string req = "GET " + path +
  26352. " HTTP/1.1\r\n"
  26353. "Host: 127.0.0.1\r\n"
  26354. "Upgrade: websocket\r\n"
  26355. "Connection: Upgrade\r\n"
  26356. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26357. "Sec-WebSocket-Version: 13\r\n"
  26358. "\r\n";
  26359. std::string res;
  26360. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  26361. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26362. static_cast<ssize_t>(req.size())) {
  26363. char c;
  26364. while (res.find("\r\n\r\n") == std::string::npos &&
  26365. ::recv(sock, &c, 1, 0) == 1) {
  26366. res += c;
  26367. }
  26368. }
  26369. if (res.find(" 101 ") == std::string::npos) {
  26370. detail::close_socket(sock);
  26371. return INVALID_SOCKET;
  26372. }
  26373. return sock;
  26374. }
  26375. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26376. // The payload must fit the 7-bit length field.
  26377. static std::string masked_frame(uint8_t first_byte,
  26378. const std::string &payload) {
  26379. std::string f;
  26380. f += static_cast<char>(first_byte);
  26381. f += static_cast<char>(0x80 | payload.size());
  26382. f.append(4, '\0');
  26383. return f + payload;
  26384. }
  26385. // Sends frames on a new raw connection to /ws and returns the first n bytes the
  26386. // server sends back, or what came before it closed.
  26387. static std::string raw_websocket_reply(int port, const std::string &frames,
  26388. size_t n) {
  26389. auto sock = connect_raw_websocket(port, "/ws");
  26390. if (sock == INVALID_SOCKET) { return std::string(); }
  26391. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26392. std::string reply;
  26393. char buf[256];
  26394. while (reply.size() < n) {
  26395. auto got = ::recv(sock, buf, sizeof(buf), 0);
  26396. if (got <= 0) { break; }
  26397. reply.append(buf, static_cast<size_t>(got));
  26398. }
  26399. detail::close_socket(sock);
  26400. return reply;
  26401. }
  26402. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26403. std::atomic<bool> done{false};
  26404. std::string received;
  26405. Server svr;
  26406. svr.set_websocket_ping_interval(0);
  26407. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26408. std::string msg;
  26409. if (ws.read(msg) == ws::Binary) { received = msg; }
  26410. done = true;
  26411. });
  26412. auto port = svr.bind_to_any_port("127.0.0.1");
  26413. std::thread t([&]() { svr.listen_after_bind(); });
  26414. auto se = detail::scope_exit([&] {
  26415. svr.stop();
  26416. t.join();
  26417. });
  26418. svr.wait_until_ready();
  26419. auto sock = connect_raw_websocket(port, "/ws");
  26420. ASSERT_NE(INVALID_SOCKET, sock);
  26421. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26422. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26423. masked_frame(0x89, "p") + // FIN + Ping
  26424. masked_frame(0x80, "lo"); // FIN + Continuation
  26425. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26426. for (int i = 0; i < 500 && !done; i++) {
  26427. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26428. }
  26429. ASSERT_TRUE(done);
  26430. EXPECT_EQ("Hello", received);
  26431. // The Ping between the fragments is answered with a Pong.
  26432. char pong[3];
  26433. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26434. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26435. }
  26436. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26437. #ifndef _WIN32
  26438. signal(SIGPIPE, SIG_IGN);
  26439. #endif
  26440. std::atomic<bool> read_ended{false};
  26441. std::atomic<bool> sending{true};
  26442. Server svr;
  26443. svr.set_websocket_ping_interval(0);
  26444. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26445. std::thread reader([&]() {
  26446. std::string msg;
  26447. while (ws.read(msg)) {}
  26448. read_ended = true;
  26449. });
  26450. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26451. ws.close();
  26452. reader.join();
  26453. });
  26454. auto port = svr.bind_to_any_port("127.0.0.1");
  26455. std::thread t([&]() { svr.listen_after_bind(); });
  26456. auto se = detail::scope_exit([&] {
  26457. svr.stop();
  26458. t.join();
  26459. });
  26460. svr.wait_until_ready();
  26461. auto sock = connect_raw_websocket(port, "/ws");
  26462. ASSERT_NE(INVALID_SOCKET, sock);
  26463. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26464. // A Text message whose empty continuation frames never end
  26465. std::thread sender([&]() {
  26466. auto data = masked_frame(0x01, "");
  26467. while (sending) {
  26468. data += masked_frame(0x00, "");
  26469. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26470. return;
  26471. }
  26472. data.clear();
  26473. }
  26474. });
  26475. for (int i = 0; i < 300 && !read_ended; i++) {
  26476. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26477. }
  26478. sending = false;
  26479. sender.join();
  26480. EXPECT_TRUE(read_ended);
  26481. }
  26482. TEST(WebSocketTest, ServerMaxMessageLength) {
  26483. Server svr;
  26484. svr.set_websocket_ping_interval(0);
  26485. svr.set_websocket_max_message_length(100);
  26486. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26487. std::string msg;
  26488. while (ws.read(msg)) {
  26489. ws.send(msg);
  26490. }
  26491. });
  26492. auto port = svr.bind_to_any_port("127.0.0.1");
  26493. std::thread t([&]() { svr.listen_after_bind(); });
  26494. auto se = detail::scope_exit([&] {
  26495. svr.stop();
  26496. t.join();
  26497. });
  26498. svr.wait_until_ready();
  26499. const std::string ping(110, 'p');
  26500. const std::string half(50, 'a');
  26501. const std::string over(60, 'b');
  26502. const std::string too_big("\x88\x02\x03\xf1"); // Close 1009
  26503. // A Ping longer than the limit is answered, since the limit is for
  26504. // messages. A message at the limit is echoed, and one over it is refused
  26505. // although each of its frames is within it.
  26506. EXPECT_EQ(std::string("\x8a\x6e") + ping + "\x81\x64" + half + half + too_big,
  26507. raw_websocket_reply(
  26508. port,
  26509. masked_frame(0x89, ping) + masked_frame(0x01, half) +
  26510. masked_frame(0x80, half) + masked_frame(0x01, over) +
  26511. masked_frame(0x80, over),
  26512. 2 + ping.size() + 2 + 2 * half.size() + too_big.size()));
  26513. // A header that announces more than the limit is refused before its payload
  26514. EXPECT_EQ(too_big, raw_websocket_reply(port,
  26515. std::string("\x82\xfe\x03\xe8", 4) +
  26516. std::string(4, '\0'),
  26517. too_big.size()));
  26518. }
  26519. TEST(WebSocketTest, ClientMaxMessageLength) {
  26520. Server svr;
  26521. svr.set_websocket_ping_interval(0);
  26522. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26523. ws.send(std::string(1024, 'a'));
  26524. ws.send(std::string(2048, 'b'));
  26525. std::string msg;
  26526. while (ws.read(msg)) {}
  26527. });
  26528. auto port = svr.bind_to_any_port(HOST);
  26529. std::thread t([&]() { svr.listen_after_bind(); });
  26530. auto se = detail::scope_exit([&] {
  26531. svr.stop();
  26532. t.join();
  26533. });
  26534. svr.wait_until_ready();
  26535. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  26536. client.set_read_timeout(5, 0);
  26537. client.set_websocket_max_message_length(1024);
  26538. ASSERT_TRUE(client.connect());
  26539. std::string msg;
  26540. ASSERT_EQ(ws::Text, client.read(msg));
  26541. EXPECT_EQ(1024u, msg.size());
  26542. EXPECT_EQ(ws::Fail, client.read(msg));
  26543. EXPECT_FALSE(client.is_open());
  26544. // 0 lifts the limit
  26545. client.set_websocket_max_message_length(0);
  26546. ASSERT_TRUE(client.connect());
  26547. EXPECT_EQ(ws::Text, client.read(msg));
  26548. EXPECT_EQ(ws::Text, client.read(msg));
  26549. EXPECT_EQ(2048u, msg.size());
  26550. }
  26551. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26552. Server svr;
  26553. svr.set_websocket_ping_interval(-1);
  26554. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26555. std::string msg;
  26556. while (ws.read(msg)) {}
  26557. });
  26558. auto port = svr.bind_to_any_port("127.0.0.1");
  26559. std::thread t([&]() { svr.listen_after_bind(); });
  26560. auto se = detail::scope_exit([&] {
  26561. svr.stop();
  26562. t.join();
  26563. });
  26564. svr.wait_until_ready();
  26565. auto sock = connect_raw_websocket(port, "/ws");
  26566. ASSERT_NE(INVALID_SOCKET, sock);
  26567. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26568. // Nothing comes while the client stays quiet.
  26569. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26570. char c;
  26571. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26572. }
  26573. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26574. // and that has to end a read() already waiting on the peer, on every platform.
  26575. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26576. // The peer sends no pings, and its handler never calls read(), which is
  26577. // where pongs are written.
  26578. std::mutex mutex;
  26579. std::condition_variable cv;
  26580. auto release = false;
  26581. svr.set_websocket_ping_interval(0);
  26582. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26583. std::unique_lock<std::mutex> lock(mutex);
  26584. cv.wait(lock, [&] { return release; });
  26585. });
  26586. auto port = svr.bind_to_any_port(HOST);
  26587. std::thread t([&]() { svr.listen_after_bind(); });
  26588. auto se = detail::scope_exit([&] {
  26589. {
  26590. std::lock_guard<std::mutex> lock(mutex);
  26591. release = true;
  26592. }
  26593. cv.notify_all();
  26594. svr.stop();
  26595. t.join();
  26596. });
  26597. svr.wait_until_ready();
  26598. ws::WebSocketClient client(std::string(scheme) +
  26599. "://localhost:" + std::to_string(port) + "/ws");
  26600. #ifdef CPPHTTPLIB_SSL_ENABLED
  26601. client.enable_server_certificate_verification(false);
  26602. #endif
  26603. // A ping a second, given up on after two go unanswered: about 3s
  26604. client.set_websocket_ping_interval(1);
  26605. client.set_websocket_max_missed_pongs(2);
  26606. // Well past that, so that a read the timeout ends instead stands out
  26607. client.set_read_timeout(10);
  26608. ASSERT_TRUE(client.connect());
  26609. auto start = std::chrono::steady_clock::now();
  26610. std::string msg;
  26611. EXPECT_EQ(ws::Fail, client.read(msg));
  26612. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26613. std::chrono::steady_clock::now() - start)
  26614. .count(),
  26615. 6000);
  26616. EXPECT_FALSE(client.is_open());
  26617. }
  26618. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26619. Server svr;
  26620. check_pong_timeout_ends_read(svr, "ws");
  26621. }
  26622. #ifdef CPPHTTPLIB_SSL_ENABLED
  26623. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26625. ASSERT_TRUE(svr.is_valid());
  26626. check_pong_timeout_ends_read(svr, "wss");
  26627. }
  26628. #endif
  26629. // listen() returns only after every handler has, so Server::stop() has to end
  26630. // a WebSocket handler's read() waiting on a client that stays connected and
  26631. // quiet, whether or not the handler bounded its reads, and the client's
  26632. // connection ends with it.
  26633. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26634. bool bounded) {
  26635. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26636. if (bounded) { ws.set_read_timeout(0, 50000); }
  26637. std::string msg;
  26638. while (ws.read(msg) != ws::Fail) {}
  26639. });
  26640. auto port = svr.bind_to_any_port(HOST);
  26641. std::thread t([&]() { svr.listen_after_bind(); });
  26642. auto se = detail::scope_exit([&] {
  26643. if (t.joinable()) {
  26644. svr.stop();
  26645. t.join();
  26646. }
  26647. });
  26648. svr.wait_until_ready();
  26649. ws::WebSocketClient client(std::string(scheme) +
  26650. "://localhost:" + std::to_string(port) + "/ws");
  26651. #ifdef CPPHTTPLIB_SSL_ENABLED
  26652. client.enable_server_certificate_verification(false);
  26653. #endif
  26654. client.set_read_timeout(2);
  26655. ASSERT_TRUE(client.connect());
  26656. auto stopped = std::async(std::launch::async, [&] {
  26657. svr.stop();
  26658. t.join();
  26659. });
  26660. std::string msg;
  26661. EXPECT_EQ(ws::Fail, client.read(msg));
  26662. EXPECT_FALSE(client.is_open());
  26663. auto in_time =
  26664. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26665. // A handler the stop did not reach ends when the client leaves
  26666. if (!in_time) { client.close(); }
  26667. stopped.wait();
  26668. EXPECT_TRUE(in_time);
  26669. }
  26670. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26671. Server svr;
  26672. check_stop_ends_websocket_read(svr, "ws", false);
  26673. }
  26674. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26675. Server svr;
  26676. check_stop_ends_websocket_read(svr, "ws", true);
  26677. }
  26678. #ifdef CPPHTTPLIB_SSL_ENABLED
  26679. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26680. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26681. ASSERT_TRUE(svr.is_valid());
  26682. check_stop_ends_websocket_read(svr, "wss", false);
  26683. }
  26684. #endif
  26685. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26686. // dropped connection, whether the handler waits for a message or for the rest
  26687. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26688. // time out inside the message as well, and the stop ends them too.
  26689. static void check_stop_closes_with_going_away(const std::string &sent,
  26690. bool bounded = false) {
  26691. Server svr;
  26692. svr.set_websocket_ping_interval(0);
  26693. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26694. if (bounded) { ws.set_read_timeout(0, 10000); }
  26695. std::string msg;
  26696. while (ws.read(msg) != ws::Fail) {}
  26697. });
  26698. auto port = svr.bind_to_any_port("127.0.0.1");
  26699. std::thread t([&]() { svr.listen_after_bind(); });
  26700. auto se = detail::scope_exit([&] {
  26701. svr.stop();
  26702. t.join();
  26703. });
  26704. svr.wait_until_ready();
  26705. // Closed before the join above, which a handler the stop did not reach
  26706. // would otherwise hold up.
  26707. auto sock = connect_raw_websocket(port, "/ws");
  26708. ASSERT_NE(INVALID_SOCKET, sock);
  26709. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26710. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26711. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26712. // Let the handler take what was sent and wait for more
  26713. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26714. svr.stop();
  26715. // FIN + Close, its length, then the code: unmasked, from a server
  26716. std::string head;
  26717. char c;
  26718. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26719. head += c;
  26720. }
  26721. const std::string reason = "server stopping";
  26722. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26723. "\x03\xe9",
  26724. head);
  26725. }
  26726. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26727. check_stop_closes_with_going_away("");
  26728. }
  26729. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26730. // A Text frame without FIN: the first fragment of a message
  26731. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26732. }
  26733. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26734. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26735. /*bounded=*/true);
  26736. }
  26737. // A handler that bounds its reads gets control back within its timeout even
  26738. // while a message arrives in pieces, and the message whole once the last has
  26739. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26740. // sent once read() has timed out twice since the one before was sent, so the
  26741. // second timeout came from a read() that had that piece to take.
  26742. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26743. const std::string &expected) {
  26744. std::atomic<bool> done{false};
  26745. std::atomic<int> timeouts{0};
  26746. std::string received;
  26747. Server svr;
  26748. svr.set_websocket_ping_interval(0);
  26749. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26750. ws.set_read_timeout(0, 10000);
  26751. std::string msg;
  26752. ws::ReadResult r;
  26753. while ((r = ws.read(msg)) == ws::Timeout) {
  26754. timeouts++;
  26755. }
  26756. if (r == ws::Text) { received = msg; }
  26757. done = true;
  26758. });
  26759. auto port = svr.bind_to_any_port("127.0.0.1");
  26760. std::thread t([&]() { svr.listen_after_bind(); });
  26761. auto se = detail::scope_exit([&] {
  26762. svr.stop();
  26763. t.join();
  26764. });
  26765. svr.wait_until_ready();
  26766. auto sock = connect_raw_websocket(port, "/ws");
  26767. ASSERT_NE(INVALID_SOCKET, sock);
  26768. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26769. // Each piece goes out at once, not held back by Nagle's algorithm
  26770. ASSERT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  26771. for (size_t i = 0; i < pieces.size(); i++) {
  26772. ASSERT_EQ(static_cast<ssize_t>(pieces[i].size()),
  26773. detail::send_socket(sock, pieces[i].data(), pieces[i].size(), 0));
  26774. if (i + 1 == pieces.size()) { break; }
  26775. auto before = timeouts.load();
  26776. for (int j = 0; j < 5000 && timeouts < before + 2; j++) {
  26777. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  26778. }
  26779. ASSERT_GE(timeouts.load(), before + 2) << "piece " << i;
  26780. }
  26781. for (int i = 0; i < 5000 && !done; i++) {
  26782. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  26783. }
  26784. ASSERT_TRUE(done);
  26785. EXPECT_EQ(expected, received);
  26786. }
  26787. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26788. // The header's first byte, then its second with half the mask key, then
  26789. // the rest: what a frame written in several writes may look like when
  26790. // Nagle's algorithm holds the later ones back for an ACK.
  26791. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26792. check_bounded_read_resumes(
  26793. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26794. }
  26795. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26796. check_bounded_read_resumes(
  26797. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26798. }
  26799. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26800. Server svr;
  26801. svr.set_websocket_ping_interval(0);
  26802. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26803. std::string msg;
  26804. while (ws.read(msg)) {}
  26805. });
  26806. auto port = svr.bind_to_any_port("127.0.0.1");
  26807. std::thread t([&]() { svr.listen_after_bind(); });
  26808. auto se = detail::scope_exit([&] {
  26809. svr.stop();
  26810. t.join();
  26811. });
  26812. svr.wait_until_ready();
  26813. // Each Close payload and the reply it should get: an echo when valid, 1002
  26814. // otherwise.
  26815. std::vector<std::pair<std::string, std::string>> cases = {
  26816. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26817. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26818. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26819. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26820. };
  26821. // Also between the fragments of a message.
  26822. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26823. for (const auto &c : cases) {
  26824. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26825. c.second,
  26826. raw_websocket_reply(port, prefix + masked_frame(0x88, c.first),
  26827. 2 + c.second.size()));
  26828. }
  26829. }
  26830. }
  26831. TEST(WebSocketTest, FailsABadFrameWithACloseStatus) {
  26832. Server svr;
  26833. svr.set_websocket_ping_interval(0);
  26834. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26835. std::string msg;
  26836. while (ws.read(msg)) {}
  26837. });
  26838. auto port = svr.bind_to_any_port("127.0.0.1");
  26839. std::thread t([&]() { svr.listen_after_bind(); });
  26840. auto se = detail::scope_exit([&] {
  26841. svr.stop();
  26842. t.join();
  26843. });
  26844. svr.wait_until_ready();
  26845. // A header that announces one byte over the limit, and none of its payload
  26846. std::string too_big = "\x82\xff";
  26847. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1;
  26848. for (int shift = 56; shift >= 0; shift -= 8) {
  26849. too_big += static_cast<char>((len >> shift) & 0xff);
  26850. }
  26851. too_big.append(4, '\0');
  26852. const std::string protocol_error("\x03\xea"); // 1002
  26853. const std::string too_big_error("\x03\xf1"); // 1009
  26854. // What the client sends and the status the server closes with
  26855. std::vector<std::pair<std::string, std::string>> cases = {
  26856. {masked_frame(0xc1, "a"), protocol_error}, // RSV1
  26857. {std::string("\x81\x01") + "a", protocol_error}, // not masked
  26858. {masked_frame(0x09, ""), protocol_error}, // fragmented Ping
  26859. {masked_frame(0x83, ""), protocol_error}, // reserved opcode
  26860. {masked_frame(0x8b, ""), protocol_error}, // reserved control opcode
  26861. {masked_frame(0x80, "a"), protocol_error}, // continuation, no start
  26862. {masked_frame(0x01, "a") + masked_frame(0x81, "b"),
  26863. protocol_error}, // a new message inside a fragmented one
  26864. {std::string("\x81\xff\x80", 3) + std::string(11, '\0'),
  26865. protocol_error}, // 64-bit length with its top bit set
  26866. {too_big, too_big_error},
  26867. };
  26868. for (const auto &c : cases) {
  26869. EXPECT_EQ(std::string("\x88\x02") + c.second,
  26870. raw_websocket_reply(port, c.first, 4));
  26871. }
  26872. }
  26873. TEST(WebSocketTest, ClientFailsAMaskedFrameWithProtocolError) {
  26874. SilentListener listener;
  26875. ASSERT_NE(INVALID_SOCKET, listener.sock);
  26876. // A peer that completes the handshake, then sends a masked frame, which a
  26877. // server must never do, and keeps what the client sends back.
  26878. std::string reply;
  26879. std::thread peer([&]() {
  26880. auto sock = listener.accept();
  26881. if (sock == INVALID_SOCKET) { return; }
  26882. std::string req;
  26883. char c;
  26884. while (req.find("\r\n\r\n") == std::string::npos &&
  26885. ::recv(sock, &c, 1, 0) == 1) {
  26886. req += c;
  26887. }
  26888. const std::string field = "Sec-WebSocket-Key: ";
  26889. auto pos = req.find(field);
  26890. if (pos != std::string::npos) {
  26891. pos += field.size();
  26892. auto key = req.substr(pos, req.find("\r\n", pos) - pos);
  26893. auto res = "HTTP/1.1 101 Switching Protocols\r\n"
  26894. "Upgrade: websocket\r\n"
  26895. "Connection: Upgrade\r\n"
  26896. "Sec-WebSocket-Accept: " +
  26897. detail::websocket_accept_key(key) + "\r\n\r\n" +
  26898. masked_frame(0x81, "a");
  26899. detail::send_socket(sock, res.data(), res.size(), 0);
  26900. // FIN + Close, masked with a length of 2, the mask key, the code
  26901. char buf[256];
  26902. while (reply.size() < 8) {
  26903. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26904. if (n <= 0) { break; }
  26905. reply.append(buf, static_cast<size_t>(n));
  26906. }
  26907. }
  26908. detail::close_socket(sock);
  26909. });
  26910. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(listener.port) +
  26911. "/ws");
  26912. auto connected = static_cast<bool>(client.connect());
  26913. std::string msg;
  26914. auto r = connected ? client.read(msg) : ws::Fail;
  26915. peer.join();
  26916. ASSERT_TRUE(connected);
  26917. EXPECT_EQ(ws::Fail, r);
  26918. detail::BufferStream strm;
  26919. strm.write(reply.data(), reply.size());
  26920. ws::Opcode opcode;
  26921. std::string payload;
  26922. bool fin;
  26923. ASSERT_EQ(
  26924. ws::impl::FrameRead::Ok,
  26925. ws::impl::read_websocket_frame(strm, opcode, payload, fin, true, 125));
  26926. EXPECT_EQ(ws::Opcode::Close, opcode);
  26927. EXPECT_EQ(std::string("\x03\xea"), payload);
  26928. }
  26929. // What a handler sees of the peer's close once read() has failed
  26930. TEST(WebSocketTest, HandlerSeesThePeersClose) {
  26931. std::mutex m;
  26932. std::condition_variable cv;
  26933. size_t handled = 0;
  26934. uint16_t seen_status = 0;
  26935. std::string seen_reason;
  26936. Server svr;
  26937. svr.set_websocket_ping_interval(0);
  26938. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26939. std::string msg;
  26940. while (ws.read(msg)) {}
  26941. std::lock_guard<std::mutex> lock(m);
  26942. seen_status = static_cast<uint16_t>(ws.close_status());
  26943. seen_reason = ws.close_reason();
  26944. handled++;
  26945. cv.notify_one();
  26946. });
  26947. auto port = svr.bind_to_any_port("127.0.0.1");
  26948. std::thread t([&]() { svr.listen_after_bind(); });
  26949. auto se = detail::scope_exit([&] {
  26950. svr.stop();
  26951. t.join();
  26952. });
  26953. svr.wait_until_ready();
  26954. auto expect_seen = [&](size_t n, uint16_t status, const std::string &reason,
  26955. const char *label) {
  26956. std::unique_lock<std::mutex> lock(m);
  26957. ASSERT_TRUE(cv.wait_for(lock, std::chrono::seconds(5), [&] {
  26958. return handled == n;
  26959. })) << label;
  26960. EXPECT_EQ(status, seen_status) << label;
  26961. EXPECT_EQ(reason, seen_reason) << label;
  26962. };
  26963. // What a raw client sends before it drops the connection
  26964. struct Case {
  26965. const char *label;
  26966. std::string sent;
  26967. uint16_t status;
  26968. std::string reason;
  26969. };
  26970. std::vector<Case> cases = {
  26971. {"application code", masked_frame(0x88, "\x0f\xa1logout"), 4001,
  26972. "logout"},
  26973. {"normal", masked_frame(0x88, "\x03\xe8"), 1000, ""},
  26974. {"no status", masked_frame(0x88, ""), 1005, ""},
  26975. {"malformed", masked_frame(0x88, "\x03"), 1002, ""},
  26976. {"no Close", masked_frame(0x81, "hi"), 1006, ""},
  26977. };
  26978. for (size_t i = 0; i < cases.size(); i++) {
  26979. auto sock = connect_raw_websocket(port, "/ws");
  26980. ASSERT_NE(INVALID_SOCKET, sock);
  26981. detail::send_socket(sock, cases[i].sent.data(), cases[i].sent.size(), 0);
  26982. detail::close_socket(sock);
  26983. expect_seen(i + 1, cases[i].status, cases[i].reason, cases[i].label);
  26984. }
  26985. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws");
  26986. ASSERT_TRUE(client.connect());
  26987. client.close(static_cast<ws::CloseStatus>(4001), "logout");
  26988. expect_seen(cases.size() + 1, 4001, "logout", "WebSocketClient");
  26989. }
  26990. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26991. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26992. protected:
  26993. void SetUp() override {
  26994. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26995. SERVER_PRIVATE_KEY_FILE);
  26996. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26997. std::string msg;
  26998. ws::ReadResult ret;
  26999. while ((ret = ws.read(msg))) {
  27000. if (ret == ws::Binary) {
  27001. ws.send(msg.data(), msg.size());
  27002. } else {
  27003. ws.send(msg);
  27004. }
  27005. }
  27006. });
  27007. port_ = server_->bind_to_any_port(HOST);
  27008. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27009. server_->wait_until_ready();
  27010. }
  27011. void TearDown() override {
  27012. server_->stop();
  27013. if (server_thread_.joinable()) { server_thread_.join(); }
  27014. }
  27015. std::unique_ptr<SSLServer> server_;
  27016. std::thread server_thread_;
  27017. int port_ = 0;
  27018. };
  27019. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  27020. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  27021. {
  27022. ws::WebSocketClient client(url);
  27023. client.enable_server_certificate_verification(false);
  27024. auto calls = 0;
  27025. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  27026. calls++;
  27027. return false;
  27028. });
  27029. EXPECT_FALSE(client.connect());
  27030. EXPECT_GT(calls, 0);
  27031. }
  27032. {
  27033. ws::WebSocketClient client(url);
  27034. client.enable_server_certificate_verification(false);
  27035. client.set_session_verifier([](tls::session_t) {
  27036. return SSLVerifierResponse::CertificateRejected;
  27037. });
  27038. EXPECT_FALSE(client.connect());
  27039. }
  27040. {
  27041. ws::WebSocketClient client(url);
  27042. client.enable_server_certificate_verification(false);
  27043. client.set_session_verifier([](tls::session_t) {
  27044. return SSLVerifierResponse::CertificateAccepted;
  27045. });
  27046. EXPECT_TRUE(client.connect());
  27047. }
  27048. }
  27049. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  27050. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  27051. "/ws-echo");
  27052. client.enable_server_certificate_verification(false);
  27053. ASSERT_TRUE(client.connect());
  27054. ASSERT_TRUE(client.is_open());
  27055. ASSERT_TRUE(client.send("Hello WSS"));
  27056. std::string msg;
  27057. EXPECT_EQ(ws::Text, client.read(msg));
  27058. EXPECT_EQ("Hello WSS", msg);
  27059. client.close();
  27060. }
  27061. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  27062. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  27063. "/ws-echo");
  27064. client.enable_server_certificate_verification(false);
  27065. EXPECT_TRUE(client.connect());
  27066. }
  27067. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  27068. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  27069. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  27070. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  27071. // client (without calling close() first) is the only path that runs
  27072. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  27073. // bug exactly.
  27074. //
  27075. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  27076. // when linked against an instrumented libssl; run under Valgrind to catch it
  27077. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  27078. // suite (the freed session otherwise stalls on the close handshake) — this test
  27079. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  27080. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  27081. {
  27082. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  27083. "/ws-echo");
  27084. client.enable_server_certificate_verification(false);
  27085. client.set_read_timeout(2, 0);
  27086. client.set_write_timeout(2, 0);
  27087. ASSERT_TRUE(client.connect());
  27088. ASSERT_TRUE(client.is_open());
  27089. ASSERT_TRUE(client.send("still open"));
  27090. // Intentionally do NOT call client.close(): leaving scope runs
  27091. // shutdown_and_close() with the WebSocket still open, which must send the
  27092. // close frame while the TLS session is still alive.
  27093. }
  27094. }
  27095. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  27096. // shutdown_and_close() at the start of connect(), reproducing the same
  27097. // use-after-free within the test body rather than at scope exit. The second
  27098. // connect must succeed and echo, proving the close handshake ran over a live
  27099. // session. See the note above about memory-tool requirements.
  27100. TEST_F(WebSocketSSLIntegrationTest,
  27101. ReconnectWhileOpenSendsCloseOverLiveSession) {
  27102. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  27103. "/ws-echo");
  27104. client.enable_server_certificate_verification(false);
  27105. client.set_read_timeout(2, 0);
  27106. client.set_write_timeout(2, 0);
  27107. ASSERT_TRUE(client.connect());
  27108. ASSERT_TRUE(client.is_open());
  27109. ASSERT_TRUE(client.send("still open"));
  27110. // Reconnect without closing first: connect() calls shutdown_and_close() on
  27111. // the still-open connection, which must not touch a freed TLS session.
  27112. ASSERT_TRUE(client.connect());
  27113. ASSERT_TRUE(client.is_open());
  27114. ASSERT_TRUE(client.send("after reconnect"));
  27115. std::string msg;
  27116. EXPECT_EQ(ws::Text, client.read(msg));
  27117. EXPECT_EQ("after reconnect", msg);
  27118. client.close();
  27119. }
  27120. #endif
  27121. #ifdef CPPHTTPLIB_SSL_ENABLED
  27122. class WebSocketSSLCATest : public ::testing::Test {
  27123. protected:
  27124. void SetUp() override {
  27125. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  27126. SERVER_PRIVATE_KEY_FILE);
  27127. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27128. std::string msg;
  27129. while (ws.read(msg)) {
  27130. ws.send(msg);
  27131. }
  27132. });
  27133. port_ = server_->bind_to_any_port("127.0.0.1");
  27134. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27135. server_->wait_until_ready();
  27136. }
  27137. void TearDown() override {
  27138. server_->stop();
  27139. if (server_thread_.joinable()) { server_thread_.join(); }
  27140. }
  27141. std::string url() const {
  27142. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  27143. }
  27144. std::unique_ptr<SSLServer> server_;
  27145. std::thread server_thread_;
  27146. int port_ = 0;
  27147. };
  27148. // A custom CA loaded as PEM verifies the server with full certificate
  27149. // verification enabled
  27150. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  27151. ws::WebSocketClient client(url());
  27152. std::string cert;
  27153. read_file(SERVER_CERT2_FILE, cert);
  27154. client.load_ca_cert_store(cert.c_str(), cert.size());
  27155. ASSERT_TRUE(client.connect());
  27156. ASSERT_TRUE(client.send("hello"));
  27157. std::string msg;
  27158. EXPECT_EQ(ws::Text, client.read(msg));
  27159. EXPECT_EQ("hello", msg);
  27160. client.close();
  27161. }
  27162. // A custom CA that does not cover the server must fail verification (the
  27163. // custom CA is exclusive; system certs are not loaded alongside it)
  27164. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  27165. ws::WebSocketClient client(url());
  27166. std::string cert;
  27167. read_file(CLIENT_CA_CERT_FILE, cert);
  27168. client.load_ca_cert_store(cert.c_str(), cert.size());
  27169. auto res = client.connect();
  27170. ASSERT_FALSE(res);
  27171. EXPECT_EQ(Error::SSLServerVerification, res.error());
  27172. EXPECT_EQ(-1, res.status());
  27173. EXPECT_NE(0u, res.ssl_backend_error());
  27174. }
  27175. // The same CA as a file path rather than PEM in memory
  27176. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  27177. ws::WebSocketClient client(url());
  27178. client.set_ca_cert_path(SERVER_CERT2_FILE);
  27179. ASSERT_TRUE(client.connect());
  27180. ASSERT_TRUE(client.send("hello"));
  27181. std::string msg;
  27182. EXPECT_EQ(ws::Text, client.read(msg));
  27183. EXPECT_EQ("hello", msg);
  27184. client.close();
  27185. }
  27186. // ...and a CA file that does not cover the server still fails, so it is the
  27187. // path above that decides the outcome
  27188. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  27189. ws::WebSocketClient client(url());
  27190. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  27191. ASSERT_FALSE(client.connect());
  27192. }
  27193. // Regression test: reconnecting with a native custom CA store used to reuse
  27194. // a store handle the previous TLS context had already freed (use-after-free
  27195. // under the OpenSSL backend). The context now lives as long as the client.
  27196. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  27197. ws::WebSocketClient client(url());
  27198. std::string cert;
  27199. read_file(SERVER_CERT2_FILE, cert);
  27200. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  27201. ASSERT_TRUE(client.connect());
  27202. client.close();
  27203. ASSERT_TRUE(client.connect());
  27204. ASSERT_TRUE(client.send("again"));
  27205. std::string msg;
  27206. EXPECT_EQ(ws::Text, client.read(msg));
  27207. EXPECT_EQ("again", msg);
  27208. client.close();
  27209. }
  27210. // Regression test: a certificate with a trusted chain but no identity match
  27211. // for the server IP must be rejected. The Mbed TLS backend used to skip
  27212. // verification entirely for IP hosts, so this connection succeeded there.
  27213. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  27214. // chain verification while the identity check must still fail.
  27215. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  27216. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  27217. ASSERT_TRUE(svr.is_valid());
  27218. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27219. std::string msg;
  27220. while (ws.read(msg)) {
  27221. ws.send(msg);
  27222. }
  27223. });
  27224. auto port = svr.bind_to_any_port("127.0.0.1");
  27225. auto t = std::thread([&]() { svr.listen_after_bind(); });
  27226. auto se = detail::scope_exit([&] {
  27227. svr.stop();
  27228. t.join();
  27229. });
  27230. svr.wait_until_ready();
  27231. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  27232. "/echo");
  27233. std::string cert;
  27234. read_file(SERVER_CERT_FILE, cert);
  27235. client.load_ca_cert_store(cert.c_str(), cert.size());
  27236. ASSERT_FALSE(client.connect());
  27237. }
  27238. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  27239. // SNI, so nothing binds the host name to the TLS session. These bind the
  27240. // server to "localhost" instead, the only shape that exercises the SNI and
  27241. // hostname-verification path with certificate verification left enabled.
  27242. class WebSocketSSLDnsHostTest : public ::testing::Test {
  27243. protected:
  27244. void Start(const char *cert_file) {
  27245. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  27246. SERVER_PRIVATE_KEY_FILE);
  27247. ASSERT_TRUE(server_->is_valid());
  27248. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27249. std::string msg;
  27250. while (ws.read(msg)) {
  27251. ws.send(msg);
  27252. }
  27253. });
  27254. port_ = server_->bind_to_any_port("localhost");
  27255. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27256. server_->wait_until_ready();
  27257. }
  27258. void TearDown() override {
  27259. if (server_) { server_->stop(); }
  27260. if (server_thread_.joinable()) { server_thread_.join(); }
  27261. }
  27262. std::string url() const {
  27263. return "wss://localhost:" + std::to_string(port_) + "/echo";
  27264. }
  27265. std::unique_ptr<SSLServer> server_;
  27266. std::thread server_thread_;
  27267. int port_ = 0;
  27268. };
  27269. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  27270. // out and the connection is usable
  27271. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  27272. Start(SERVER_CERT2_FILE);
  27273. ws::WebSocketClient client(url());
  27274. client.set_ca_cert_path(SERVER_CERT2_FILE);
  27275. ASSERT_TRUE(client.connect());
  27276. ASSERT_TRUE(client.send("hello"));
  27277. std::string msg;
  27278. EXPECT_EQ(ws::Text, client.read(msg));
  27279. EXPECT_EQ("hello", msg);
  27280. client.close();
  27281. }
  27282. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  27283. // while the identity check must still reject "localhost"
  27284. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  27285. Start(SERVER_CERT_FILE);
  27286. ws::WebSocketClient client(url());
  27287. client.set_ca_cert_path(SERVER_CERT_FILE);
  27288. auto res = client.connect();
  27289. ASSERT_FALSE(res);
  27290. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  27291. EXPECT_EQ(-1, res.status());
  27292. }
  27293. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  27294. // disabled: the chain is still checked, only the identity check is skipped
  27295. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  27296. Start(SERVER_CERT_FILE);
  27297. ws::WebSocketClient client(url());
  27298. client.set_ca_cert_path(SERVER_CERT_FILE);
  27299. client.enable_server_hostname_verification(false);
  27300. ASSERT_TRUE(client.connect());
  27301. ASSERT_TRUE(client.send("hello"));
  27302. std::string msg;
  27303. EXPECT_EQ(ws::Text, client.read(msg));
  27304. EXPECT_EQ("hello", msg);
  27305. client.close();
  27306. }
  27307. // A CA that did not sign the server certificate fails the chain, even though
  27308. // the name would match
  27309. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  27310. Start(SERVER_CERT2_FILE);
  27311. ws::WebSocketClient client(url());
  27312. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  27313. ASSERT_FALSE(client.connect());
  27314. }
  27315. // With verification disabled, neither the chain nor the name is checked
  27316. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  27317. Start(SERVER_CERT_FILE);
  27318. ws::WebSocketClient client(url());
  27319. client.enable_server_certificate_verification(false);
  27320. ASSERT_TRUE(client.connect());
  27321. ASSERT_TRUE(client.send("hello"));
  27322. std::string msg;
  27323. EXPECT_EQ(ws::Text, client.read(msg));
  27324. EXPECT_EQ("hello", msg);
  27325. client.close();
  27326. }
  27327. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  27328. protected:
  27329. void SetUp() override {
  27330. server_ = httplib::detail::make_unique<SSLServer>(
  27331. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  27332. ASSERT_TRUE(server_->is_valid());
  27333. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  27334. std::string msg;
  27335. while (ws.read(msg)) {
  27336. ws.send(msg);
  27337. }
  27338. });
  27339. port_ = server_->bind_to_any_port("localhost");
  27340. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27341. server_->wait_until_ready();
  27342. }
  27343. void TearDown() override {
  27344. server_->stop();
  27345. if (server_thread_.joinable()) { server_thread_.join(); }
  27346. }
  27347. std::string url() const {
  27348. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  27349. }
  27350. void ConnectWithClientCert(const std::string &client_cert_file,
  27351. const std::string &client_private_key_file,
  27352. const char *private_key_password) {
  27353. std::string cert_pem, key_pem;
  27354. read_file(client_cert_file, cert_pem);
  27355. read_file(client_private_key_file, key_pem);
  27356. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  27357. key_pem.c_str(), key_pem.size(),
  27358. private_key_password};
  27359. ConnectWithPem(pem);
  27360. }
  27361. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  27362. ws::WebSocketClient client(url(), pem);
  27363. ASSERT_TRUE(client.is_valid());
  27364. client.enable_server_certificate_verification(false);
  27365. ASSERT_TRUE(client.connect());
  27366. ASSERT_TRUE(client.send("hello"));
  27367. std::string msg;
  27368. EXPECT_EQ(ws::Text, client.read(msg));
  27369. EXPECT_EQ("hello", msg);
  27370. client.close();
  27371. }
  27372. std::unique_ptr<SSLServer> server_;
  27373. std::thread server_thread_;
  27374. int port_ = 0;
  27375. };
  27376. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  27377. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  27378. }
  27379. // Control for the tests above: the fixture's server really does require a
  27380. // client certificate, so it is the PEM the constructor installed that decides
  27381. // the outcome.
  27382. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  27383. ws::WebSocketClient client(url());
  27384. ASSERT_TRUE(client.is_valid());
  27385. client.enable_server_certificate_verification(false);
  27386. EXPECT_FALSE(client.connect());
  27387. }
  27388. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  27389. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  27390. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  27391. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  27392. }
  27393. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  27394. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  27395. std::string cert_pem, key_pem;
  27396. read_file(CLIENT_CERT_FILE, cert_pem);
  27397. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  27398. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  27399. std::vector<char> key(key_pem.begin(), key_pem.end());
  27400. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  27401. key.size(), nullptr};
  27402. ConnectWithPem(pem);
  27403. }
  27404. #endif
  27405. #if !defined(_WIN32)
  27406. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  27407. auto secret_dir = std::string("./symlink_test_secret");
  27408. auto served_dir = std::string("./symlink_test_served");
  27409. auto secret_file = secret_dir + "/secret.txt";
  27410. auto symlink_path = served_dir + "/escape";
  27411. // Setup: create directories and files
  27412. mkdir(secret_dir.c_str(), 0755);
  27413. mkdir(served_dir.c_str(), 0755);
  27414. {
  27415. std::ofstream ofs(secret_file);
  27416. ofs << "SECRET_DATA";
  27417. }
  27418. // Create symlink using absolute path so it resolves correctly
  27419. #ifdef PATH_MAX
  27420. char abs_secret[PATH_MAX];
  27421. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  27422. #else
  27423. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  27424. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  27425. ASSERT_NE(nullptr, abs_secret);
  27426. #endif
  27427. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  27428. auto se = detail::scope_exit([&] {
  27429. unlink(symlink_path.c_str());
  27430. unlink(secret_file.c_str());
  27431. rmdir(served_dir.c_str());
  27432. rmdir(secret_dir.c_str());
  27433. });
  27434. Server svr;
  27435. svr.set_mount_point("/", served_dir);
  27436. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27437. auto se2 = detail::scope_exit([&] {
  27438. svr.stop();
  27439. listen_thread.join();
  27440. });
  27441. svr.wait_until_ready();
  27442. Client cli("localhost", PORT);
  27443. // Symlink pointing outside base dir should be blocked
  27444. auto res = cli.Get("/escape/secret.txt");
  27445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27446. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27447. }
  27448. #else
  27449. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  27450. auto secret_dir = std::string("junction_test_secret");
  27451. auto served_dir = std::string("junction_test_served");
  27452. auto secret_file = secret_dir + "\\secret.txt";
  27453. auto junction_path = served_dir + "\\escape";
  27454. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  27455. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  27456. {
  27457. std::ofstream ofs(secret_file);
  27458. ofs << "SECRET_DATA";
  27459. }
  27460. // A junction needs no privilege to create, unlike a symlink
  27461. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  27462. ASSERT_EQ(0, std::system(cmd.c_str()));
  27463. auto se = detail::scope_exit([&] {
  27464. ::RemoveDirectoryA(junction_path.c_str());
  27465. std::remove(secret_file.c_str());
  27466. ::RemoveDirectoryA(served_dir.c_str());
  27467. ::RemoveDirectoryA(secret_dir.c_str());
  27468. });
  27469. Server svr;
  27470. svr.set_mount_point("/", served_dir);
  27471. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27472. auto se2 = detail::scope_exit([&] {
  27473. svr.stop();
  27474. listen_thread.join();
  27475. });
  27476. svr.wait_until_ready();
  27477. Client cli("localhost", PORT);
  27478. // Junction pointing outside base dir should be blocked
  27479. auto res = cli.Get("/escape/secret.txt");
  27480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27481. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27482. }
  27483. #endif
  27484. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  27485. // "GET /smuggled" request), reads the first response, and only then sends the
  27486. // embedded request as the body. Returns how many times /smuggled ran.
  27487. //
  27488. // The body is sent AFTER receiving the first response (as in the original
  27489. // PoC) so that the stream_line_reader cannot buffer it together with the
  27490. // headers of the first request.
  27491. static int count_smuggled_requests(const std::string &outer_head,
  27492. std::string &first_response) {
  27493. Server svr;
  27494. svr.set_mount_point("/", "./www");
  27495. std::atomic<int> smuggled_count(0);
  27496. svr.Get("/smuggled", [&](const Request &, Response &res) {
  27497. smuggled_count++;
  27498. res.set_content("oops", "text/plain");
  27499. });
  27500. svr.Post("/post", [&](const Request &req, Response &res) {
  27501. res.set_content(req.body, "text/plain");
  27502. });
  27503. auto port = svr.bind_to_any_port("localhost");
  27504. thread t = thread([&] { svr.listen_after_bind(); });
  27505. auto se = detail::scope_exit([&] {
  27506. svr.stop();
  27507. t.join();
  27508. });
  27509. svr.wait_until_ready();
  27510. auto error = Error::Success;
  27511. auto sock = detail::create_client_socket(
  27512. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  27513. /*connection_timeout_sec=*/2, 0,
  27514. /*read_timeout_sec=*/2, 0,
  27515. /*write_timeout_sec=*/2, 0, std::string(), error);
  27516. EXPECT_NE(INVALID_SOCKET, sock);
  27517. if (sock == INVALID_SOCKET) { return -1; }
  27518. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27519. // The "smuggled" request will be sent as the body of the outer request
  27520. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  27521. "Host: localhost\r\n"
  27522. "Connection: close\r\n"
  27523. "\r\n";
  27524. auto head = outer_head;
  27525. auto len = std::to_string(smuggled.size());
  27526. for (auto pos = head.find("{len}"); pos != std::string::npos;
  27527. pos = head.find("{len}", pos + len.size())) {
  27528. head.replace(pos, 5, len);
  27529. }
  27530. // Step 1: Send only the outer request headers (no body yet)
  27531. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  27532. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  27533. // Step 2: Read the first response
  27534. char buf[4096];
  27535. for (;;) {
  27536. auto n = recv(sock, buf, sizeof(buf), 0);
  27537. if (n <= 0) break;
  27538. first_response.append(buf, static_cast<size_t>(n));
  27539. // Stop once we have a complete response (headers + body)
  27540. auto hdr_end = first_response.find("\r\n\r\n");
  27541. if (hdr_end != std::string::npos) {
  27542. // Check for Content-Length to know when the body is complete
  27543. auto cl_pos = first_response.find("Content-Length:");
  27544. if (cl_pos != std::string::npos) {
  27545. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  27546. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  27547. auto cl = std::stoul(
  27548. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  27549. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  27550. } else {
  27551. break; // No Content-Length, assume headers-only response
  27552. }
  27553. }
  27554. }
  27555. // Step 3: Now send the body, which looks like a new HTTP request. On a
  27556. // vulnerable server the keep-alive loop reads this as a second request. The
  27557. // server may already have closed the connection, so the result is ignored.
  27558. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  27559. // Half-close so that a server which drained the body sees EOF and closes,
  27560. // instead of the read below waiting for the read timeout.
  27561. #ifdef _WIN32
  27562. ::shutdown(sock, SD_SEND);
  27563. #else
  27564. ::shutdown(sock, SHUT_WR);
  27565. #endif
  27566. // Step 4: Read until the server closes the connection
  27567. for (;;) {
  27568. auto n = recv(sock, buf, sizeof(buf), 0);
  27569. if (n <= 0) break;
  27570. }
  27571. return smuggled_count.load();
  27572. }
  27573. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  27574. // A GET request with Content-Length to a static file handler must have its
  27575. // body drained before the keep-alive connection is reused. Otherwise the
  27576. // unread body bytes are interpreted as the next HTTP request.
  27577. std::string first_response;
  27578. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27579. "Host: localhost\r\n"
  27580. "Content-Length: {len}\r\n"
  27581. "\r\n",
  27582. first_response));
  27583. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  27584. }
  27585. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  27586. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  27587. // be answered with 400 and the connection closed. Treating it as "no body"
  27588. // leaves the body to be parsed as the next request.
  27589. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  27590. const char *targets[] = {
  27591. "GET /file", // handler that never reads the body
  27592. "GET /not-found", // no handler matches (404)
  27593. "POST /post", // handler that reads the body
  27594. };
  27595. for (auto target : targets) {
  27596. for (auto value : values) {
  27597. std::string first_response;
  27598. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  27599. " HTTP/1.1\r\n"
  27600. "Host: localhost\r\n"
  27601. "Content-Length: " +
  27602. value + "\r\n\r\n",
  27603. first_response))
  27604. << target << " with Content-Length: " << value;
  27605. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27606. << target << " with Content-Length: " << value;
  27607. }
  27608. }
  27609. }
  27610. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27611. // A 400 for an unparseable request line leaves the rest of the message
  27612. // unread, so the connection must be closed rather than reused.
  27613. std::string first_response;
  27614. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27615. "Host: localhost\r\n"
  27616. "Content-Length: {len}\r\n"
  27617. "\r\n",
  27618. first_response));
  27619. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27620. }
  27621. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27622. // Same as above for a header block that fails to parse.
  27623. std::string first_response;
  27624. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27625. "Host: localhost\r\n"
  27626. "Bad Header\r\n"
  27627. "Content-Length: {len}\r\n"
  27628. "\r\n",
  27629. first_response));
  27630. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27631. }
  27632. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27633. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27634. // server must not read another request on that connection, even when the
  27635. // request had no body to drain.
  27636. std::string first_response;
  27637. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27638. "Host: localhost\r\n"
  27639. "\r\n",
  27640. first_response));
  27641. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27642. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27643. }
  27644. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27645. // A content reader that stops early leaves the stream inside the body.
  27646. // Draining the whole Content-Length from there, or reading the body again,
  27647. // reads into the next request, and whatever follows is parsed as a request
  27648. // of its own.
  27649. Server svr;
  27650. std::atomic<int> smuggled_count(0);
  27651. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27652. svr.Post("/upload", [](const Request &req, Response &res,
  27653. const ContentReader &content_reader) {
  27654. // Stop at the last chunk, so the whole body has been read however it
  27655. // arrives.
  27656. auto length = req.get_header_value_u64("Content-Length");
  27657. size_t total = 0;
  27658. auto consumed = content_reader([&](const char *, size_t n) {
  27659. total += n;
  27660. return total < length;
  27661. });
  27662. EXPECT_FALSE(consumed);
  27663. if (req.has_param("retry")) {
  27664. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27665. }
  27666. // Replace the 400 the aborted read set, which would close the connection.
  27667. res.set_redirect("/done");
  27668. });
  27669. auto port = svr.bind_to_any_port(HOST);
  27670. thread t = thread([&] { svr.listen_after_bind(); });
  27671. auto se = detail::scope_exit([&] {
  27672. svr.stop();
  27673. t.join();
  27674. });
  27675. svr.wait_until_ready();
  27676. // A front end sees the second request as a POST whose body is the GET. The
  27677. // first body is as long as the POST's headers, so draining it again reads
  27678. // exactly those and leaves the GET to be parsed next.
  27679. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27680. "Host: localhost\r\n"
  27681. "\r\n";
  27682. std::string second_head = "POST /post HTTP/1.1\r\n"
  27683. "Host: localhost\r\n"
  27684. "Content-Length: " +
  27685. std::to_string(inner.size()) +
  27686. "\r\n"
  27687. "\r\n";
  27688. for (auto target : {"/upload", "/upload?retry"}) {
  27689. smuggled_count = 0;
  27690. std::string request = "POST " + std::string(target) +
  27691. " HTTP/1.1\r\n"
  27692. "Host: localhost\r\n"
  27693. "Content-Length: " +
  27694. std::to_string(second_head.size()) +
  27695. "\r\n"
  27696. "\r\n" +
  27697. std::string(second_head.size(), 'A') + second_head +
  27698. inner;
  27699. std::string response;
  27700. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27701. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27702. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27703. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27704. EXPECT_EQ(0, smuggled_count.load()) << target;
  27705. }
  27706. }
  27707. // An error response closes the connection anyway, so the body is left unread
  27708. // with a redirect, such as one to a login page.
  27709. static void serve_redirects(Server &svr,
  27710. const std::function<void(int)> &client) {
  27711. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27712. res.set_redirect("/login");
  27713. return Server::HandlerResponse::Handled;
  27714. });
  27715. auto port = svr.bind_to_any_port(HOST);
  27716. ASSERT_GT(port, 0);
  27717. thread t = thread([&] { svr.listen_after_bind(); });
  27718. auto se = detail::scope_exit([&] {
  27719. svr.stop();
  27720. t.join();
  27721. ASSERT_FALSE(svr.is_running());
  27722. });
  27723. svr.wait_until_ready();
  27724. client(port);
  27725. }
  27726. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27727. Server svr;
  27728. serve_redirects(svr, [](int port) {
  27729. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27730. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27731. std::to_string(body.size()) + "\r\n\r\n" + body +
  27732. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27733. std::string resp;
  27734. ASSERT_TRUE(send_request(1, req, &resp, port));
  27735. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27736. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27737. });
  27738. }
  27739. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27740. Server svr;
  27741. svr.set_read_timeout(0, 200000);
  27742. serve_redirects(svr, [](int port) {
  27743. // A byte every 100 ms keeps each read within the read timeout, but not the
  27744. // body as a whole, so the server closes and the bytes sent after that fail.
  27745. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27746. "Content-Length: 10\r\n\r\n"};
  27747. parts.resize(11, "x");
  27748. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27749. });
  27750. }
  27751. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27752. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27753. // must be rejected with 400 Bad Request.
  27754. Server svr;
  27755. svr.Post("/test", [&](const Request &, Response &res) {
  27756. res.set_content("ok", "text/plain");
  27757. });
  27758. thread t = thread([&] { svr.listen(HOST, PORT); });
  27759. auto se = detail::scope_exit([&] {
  27760. svr.stop();
  27761. t.join();
  27762. ASSERT_FALSE(svr.is_running());
  27763. });
  27764. svr.wait_until_ready();
  27765. // Exact "chunked"
  27766. {
  27767. auto req = "POST /test HTTP/1.1\r\n"
  27768. "Host: localhost\r\n"
  27769. "Content-Length: 5\r\n"
  27770. "Transfer-Encoding: chunked\r\n"
  27771. "Connection: close\r\n"
  27772. "\r\n"
  27773. "hello";
  27774. std::string response;
  27775. ASSERT_TRUE(send_request(1, req, &response));
  27776. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27777. response.substr(0, response.find("\r\n")));
  27778. }
  27779. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27780. {
  27781. auto req = "POST /test HTTP/1.1\r\n"
  27782. "Host: localhost\r\n"
  27783. "Content-Length: 5\r\n"
  27784. "Transfer-Encoding: gzip, chunked\r\n"
  27785. "Connection: close\r\n"
  27786. "\r\n"
  27787. "hello";
  27788. std::string response;
  27789. ASSERT_TRUE(send_request(1, req, &response));
  27790. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27791. response.substr(0, response.find("\r\n")));
  27792. }
  27793. }
  27794. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27795. Server svr;
  27796. svr.Post("/test", [&](const Request &, Response &res) {
  27797. res.set_content("ok", "text/plain");
  27798. });
  27799. thread t = thread([&] { svr.listen(HOST, PORT); });
  27800. auto se = detail::scope_exit([&] {
  27801. svr.stop();
  27802. t.join();
  27803. ASSERT_FALSE(svr.is_running());
  27804. });
  27805. svr.wait_until_ready();
  27806. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27807. // length cannot be determined, so the server must answer 400 and close
  27808. // rather than treat the request as bodyless and leave the body in the
  27809. // socket for the next request to pick up.
  27810. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27811. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27812. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27813. std::string response;
  27814. ASSERT_TRUE(send_request(1, req, &response));
  27815. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27816. response.substr(0, response.find("\r\n")))
  27817. << transfer_encoding;
  27818. }
  27819. // RFC 9110 5.3: the codings may also be split across several
  27820. // Transfer-Encoding lines, which combine in the order they were received.
  27821. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27822. // just like the single-line "chunked, gzip" above.
  27823. {
  27824. auto req = "POST /test HTTP/1.1\r\n"
  27825. "Host: localhost\r\n"
  27826. "Transfer-Encoding: chunked\r\n"
  27827. "Transfer-Encoding: gzip\r\n"
  27828. "\r\n"
  27829. "0\r\n\r\n";
  27830. std::string response;
  27831. ASSERT_TRUE(send_request(1, req, &response));
  27832. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27833. response.substr(0, response.find("\r\n")));
  27834. }
  27835. }
  27836. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27837. Server svr;
  27838. svr.Post("/test", [&](const Request &, Response &res) {
  27839. res.set_content("ok", "text/plain");
  27840. });
  27841. auto port = svr.bind_to_any_port(HOST);
  27842. ASSERT_GT(port, 0);
  27843. thread t = thread([&] { svr.listen_after_bind(); });
  27844. auto se = detail::scope_exit([&] {
  27845. svr.stop();
  27846. t.join();
  27847. ASSERT_FALSE(svr.is_running());
  27848. });
  27849. svr.wait_until_ready();
  27850. for (auto transfer_encoding :
  27851. {"Transfer-Encoding: gzip, chunked\r\n",
  27852. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27853. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27854. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27855. transfer_encoding + "\r\n0\r\n\r\n";
  27856. std::string response;
  27857. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27858. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27859. response.substr(0, response.find("\r\n")))
  27860. << transfer_encoding;
  27861. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27862. << transfer_encoding;
  27863. }
  27864. }
  27865. // Regression for issue #2450: a DELETE without Content-Length on a
  27866. // keep-alive connection must not let the post-response drain consume the
  27867. // next request's bytes.
  27868. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27869. Server svr;
  27870. std::atomic<int> delete_count(0);
  27871. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27872. delete_count++;
  27873. res.status = StatusCode::NoContent_204;
  27874. });
  27875. auto port = svr.bind_to_any_port(HOST);
  27876. thread t = thread([&] { svr.listen_after_bind(); });
  27877. auto se = detail::scope_exit([&] {
  27878. svr.stop();
  27879. t.join();
  27880. });
  27881. svr.wait_until_ready();
  27882. auto error = Error::Success;
  27883. auto sock = detail::create_client_socket(
  27884. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27885. /*connection_timeout_sec=*/2, 0,
  27886. /*read_timeout_sec=*/2, 0,
  27887. /*write_timeout_sec=*/2, 0, std::string(), error);
  27888. ASSERT_NE(INVALID_SOCKET, sock);
  27889. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27890. auto send_request_and_read_response = [&](const std::string &req,
  27891. std::string &out) -> bool {
  27892. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27893. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27894. char buf[4096];
  27895. for (;;) {
  27896. auto n = recv(sock, buf, sizeof(buf), 0);
  27897. if (n <= 0) { return !out.empty(); }
  27898. out.append(buf, static_cast<size_t>(n));
  27899. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27900. }
  27901. };
  27902. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27903. "Host: localhost\r\n"
  27904. "\r\n";
  27905. std::string resp1;
  27906. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27907. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27908. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27909. "Host: localhost\r\n"
  27910. "Connection: close\r\n"
  27911. "\r\n";
  27912. std::string resp2;
  27913. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27914. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27915. EXPECT_EQ(2, delete_count.load());
  27916. }
  27917. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27918. Server svr;
  27919. svr.Post("/ingest", [&](const Request &, Response &res,
  27920. const ContentReader &content_reader) {
  27921. auto consumed = content_reader([](const char *, size_t) { return false; });
  27922. EXPECT_FALSE(consumed);
  27923. res.status = StatusCode::Conflict_409;
  27924. res.set_header("Connection", "close");
  27925. });
  27926. auto port = svr.bind_to_any_port(HOST);
  27927. thread t = thread([&] { svr.listen_after_bind(); });
  27928. auto se = detail::scope_exit([&] {
  27929. svr.stop();
  27930. t.join();
  27931. });
  27932. svr.wait_until_ready();
  27933. auto error = Error::Success;
  27934. auto sock = detail::create_client_socket(
  27935. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27936. /*connection_timeout_sec=*/2, 0,
  27937. /*read_timeout_sec=*/1, 0,
  27938. /*write_timeout_sec=*/2, 0, std::string(), error);
  27939. ASSERT_NE(INVALID_SOCKET, sock);
  27940. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27941. std::string request = "POST /ingest HTTP/1.1\r\n"
  27942. "Host: localhost\r\n"
  27943. "Transfer-Encoding: chunked\r\n"
  27944. "\r\n"
  27945. "4\r\n"
  27946. "data\r\n";
  27947. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27948. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27949. std::string response;
  27950. ssize_t received = 0;
  27951. do {
  27952. char buf[4096];
  27953. received = recv(sock, buf, sizeof(buf), 0);
  27954. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27955. } while (received > 0);
  27956. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27957. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27958. EXPECT_EQ(0, received);
  27959. }
  27960. namespace no_proxy_test {
  27961. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27962. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27963. // calling listen().
  27964. class ScopedServer {
  27965. public:
  27966. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27967. ~ScopedServer() {
  27968. svr_.stop();
  27969. if (th_.joinable()) { th_.join(); }
  27970. }
  27971. Server &svr() { return svr_; }
  27972. int port() const { return port_; }
  27973. void listen() {
  27974. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27975. svr_.wait_until_ready();
  27976. }
  27977. private:
  27978. Server svr_;
  27979. std::thread th_;
  27980. int port_ = 0;
  27981. };
  27982. class ProxyAndTargetServers {
  27983. public:
  27984. ProxyAndTargetServers() {
  27985. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27986. proxy_hits_++;
  27987. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27988. res.set_content("via-proxy", "text/plain");
  27989. });
  27990. target_.Get(".*", [this](const Request &req, Response &res) {
  27991. target_hits_++;
  27992. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27993. res.set_content("direct", "text/plain");
  27994. });
  27995. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27996. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27997. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27998. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27999. proxy_mock_.wait_until_ready();
  28000. target_.wait_until_ready();
  28001. }
  28002. ~ProxyAndTargetServers() {
  28003. proxy_mock_.stop();
  28004. target_.stop();
  28005. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  28006. if (target_thread_.joinable()) { target_thread_.join(); }
  28007. }
  28008. Server &proxy_mock() { return proxy_mock_; }
  28009. Server &target() { return target_; }
  28010. int proxy_port() const { return proxy_port_; }
  28011. int target_port() const { return target_port_; }
  28012. int proxy_hits() const { return proxy_hits_.load(); }
  28013. int target_hits() const { return target_hits_.load(); }
  28014. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  28015. void reset_counters() {
  28016. proxy_hits_ = 0;
  28017. target_hits_ = 0;
  28018. last_had_proxy_authz_ = false;
  28019. }
  28020. private:
  28021. Server proxy_mock_;
  28022. Server target_;
  28023. std::thread proxy_thread_;
  28024. std::thread target_thread_;
  28025. int proxy_port_ = 0;
  28026. int target_port_ = 0;
  28027. std::atomic<int> proxy_hits_{0};
  28028. std::atomic<int> target_hits_{0};
  28029. std::atomic<bool> last_had_proxy_authz_{false};
  28030. };
  28031. inline std::unique_ptr<Client> make_client(const std::string &host,
  28032. ProxyAndTargetServers &s) {
  28033. auto cli = detail::make_unique<Client>(host, s.target_port());
  28034. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  28035. cli->set_proxy("127.0.0.1", s.proxy_port());
  28036. return cli;
  28037. }
  28038. } // namespace no_proxy_test
  28039. using no_proxy_test::make_client;
  28040. using no_proxy_test::ProxyAndTargetServers;
  28041. // A stream request carries the credentials a buffered request does
  28042. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  28043. no_proxy_test::ScopedServer origin;
  28044. origin.svr().Get("/x", [](const Request &req, Response &res) {
  28045. res.set_content(req.get_header_value("Authorization"), "text/plain");
  28046. });
  28047. origin.listen();
  28048. Client cli("127.0.0.1", origin.port());
  28049. cli.set_basic_auth("user", "pass");
  28050. auto handle = cli.open_stream("GET", "/x");
  28051. ASSERT_TRUE(handle.is_valid());
  28052. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  28053. Client bearer("127.0.0.1", origin.port());
  28054. bearer.set_bearer_token_auth("tok");
  28055. auto handle2 = bearer.open_stream("GET", "/x");
  28056. ASSERT_TRUE(handle2.is_valid());
  28057. EXPECT_EQ("Bearer tok", read_all(handle2));
  28058. }
  28059. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  28060. // takes its own credentials, as for a buffered request
  28061. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  28062. std::string target, authz, proxy_authz;
  28063. no_proxy_test::ScopedServer proxy;
  28064. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  28065. target = req.target;
  28066. authz = req.get_header_value("Authorization");
  28067. proxy_authz = req.get_header_value("Proxy-Authorization");
  28068. res.set_content("ok", "text/plain");
  28069. });
  28070. proxy.listen();
  28071. Client cli("origin.example", 8080);
  28072. cli.set_proxy("127.0.0.1", proxy.port());
  28073. cli.set_proxy_basic_auth("puser", "ppass");
  28074. cli.set_basic_auth("user", "pass");
  28075. auto handle = cli.open_stream("GET", "/x");
  28076. ASSERT_TRUE(handle.is_valid());
  28077. EXPECT_EQ("ok", read_all(handle));
  28078. EXPECT_EQ("http://origin.example:8080/x", target);
  28079. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  28080. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  28081. }
  28082. // In absolute-form the path follows the authority, so a path that does not
  28083. // begin with '/' would make the proxy connect to another host
  28084. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  28085. std::vector<std::string> targets;
  28086. no_proxy_test::ScopedServer proxy;
  28087. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  28088. targets.push_back(req.target);
  28089. res.set_content("ok", "text/plain");
  28090. });
  28091. proxy.listen();
  28092. Client cli("origin.example", 8080);
  28093. cli.set_proxy("127.0.0.1", proxy.port());
  28094. cli.set_basic_auth("user", "pass");
  28095. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  28096. auto res = cli.Get(path);
  28097. EXPECT_FALSE(res) << path;
  28098. auto handle = cli.open_stream("GET", path);
  28099. EXPECT_FALSE(handle.is_valid()) << path;
  28100. }
  28101. EXPECT_TRUE(targets.empty());
  28102. auto res = cli.Get("/x");
  28103. ASSERT_TRUE(res);
  28104. ASSERT_EQ(1u, targets.size());
  28105. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  28106. }
  28107. TEST(NoProxyTest, ExactHostnameBypasses) {
  28108. ProxyAndTargetServers s;
  28109. auto cli = make_client("example.com", s);
  28110. cli->set_no_proxy({"example.com"});
  28111. auto res = cli->Get("/");
  28112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28113. EXPECT_EQ(0, s.proxy_hits());
  28114. EXPECT_EQ(1, s.target_hits());
  28115. }
  28116. TEST(NoProxyTest, SubdomainBypasses) {
  28117. ProxyAndTargetServers s;
  28118. auto cli = make_client("foo.example.com", s);
  28119. cli->set_no_proxy({"example.com"});
  28120. auto res = cli->Get("/");
  28121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28122. EXPECT_EQ(0, s.proxy_hits());
  28123. EXPECT_EQ(1, s.target_hits());
  28124. }
  28125. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  28126. // Regression guard: "evilexample.com" must not be considered a subdomain
  28127. // of "example.com". Without the dot-boundary rule, a naive endsWith
  28128. // check would let traffic bypass the proxy and leak credentials direct
  28129. // to the attacker host.
  28130. ProxyAndTargetServers s;
  28131. auto cli = make_client("evilexample.com", s);
  28132. cli->set_no_proxy({"example.com"});
  28133. auto res = cli->Get("/");
  28134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28135. EXPECT_GE(s.proxy_hits(), 1);
  28136. EXPECT_EQ(0, s.target_hits());
  28137. }
  28138. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  28139. ProxyAndTargetServers s;
  28140. auto cli = make_client("example.com.evil.com", s);
  28141. cli->set_no_proxy({"example.com"});
  28142. auto res = cli->Get("/");
  28143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28144. EXPECT_GE(s.proxy_hits(), 1);
  28145. EXPECT_EQ(0, s.target_hits());
  28146. }
  28147. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  28148. ProxyAndTargetServers s;
  28149. auto cli = make_client("example.com", s);
  28150. cli->set_no_proxy({".example.com"});
  28151. auto res = cli->Get("/");
  28152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28153. EXPECT_EQ(0, s.proxy_hits());
  28154. EXPECT_EQ(1, s.target_hits());
  28155. }
  28156. TEST(NoProxyTest, CaseInsensitiveHostname) {
  28157. ProxyAndTargetServers s;
  28158. auto cli = make_client("Example.COM", s);
  28159. cli->set_no_proxy({"EXAMPLE.com"});
  28160. auto res = cli->Get("/");
  28161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28162. EXPECT_EQ(0, s.proxy_hits());
  28163. EXPECT_EQ(1, s.target_hits());
  28164. }
  28165. TEST(NoProxyTest, TrailingDotIsNormalized) {
  28166. ProxyAndTargetServers s;
  28167. auto cli = make_client("example.com.", s);
  28168. cli->set_no_proxy({"example.com"});
  28169. auto res = cli->Get("/");
  28170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28171. EXPECT_EQ(0, s.proxy_hits());
  28172. EXPECT_EQ(1, s.target_hits());
  28173. }
  28174. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  28175. // Trailing dots must be normalized on BOTH sides — host and entry.
  28176. // An implementation that only strips the host-side trailing dot would
  28177. // fail to match host "example.com" against entry "example.com." because
  28178. // a literal substring search would compare 11 chars against 12.
  28179. ProxyAndTargetServers s;
  28180. auto cli = make_client("example.com", s);
  28181. cli->set_no_proxy({"example.com."});
  28182. auto res = cli->Get("/");
  28183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28184. EXPECT_EQ(0, s.proxy_hits());
  28185. EXPECT_EQ(1, s.target_hits());
  28186. }
  28187. TEST(NoProxyTest, WildcardBypassesEverything) {
  28188. ProxyAndTargetServers s;
  28189. auto cli = make_client("anything.invalid.test", s);
  28190. cli->set_no_proxy({"*"});
  28191. auto res = cli->Get("/");
  28192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28193. EXPECT_EQ(0, s.proxy_hits());
  28194. EXPECT_EQ(1, s.target_hits());
  28195. }
  28196. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  28197. ProxyAndTargetServers s;
  28198. Client cli("127.0.0.1", s.target_port());
  28199. cli.set_proxy("127.0.0.1", s.proxy_port());
  28200. cli.set_no_proxy({"127.0.0.1"});
  28201. auto res = cli.Get("/");
  28202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28203. EXPECT_EQ(0, s.proxy_hits());
  28204. EXPECT_EQ(1, s.target_hits());
  28205. }
  28206. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  28207. ProxyAndTargetServers s;
  28208. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  28209. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  28210. cli.set_proxy("127.0.0.1", s.proxy_port());
  28211. cli.set_no_proxy({"::1"});
  28212. auto res = cli.Get("/");
  28213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28214. EXPECT_EQ(0, s.proxy_hits());
  28215. EXPECT_EQ(1, s.target_hits());
  28216. }
  28217. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  28218. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  28219. // must still be recognized as IPv6 for CIDR matching. Implementations
  28220. // that detect IPv6 only when the host begins with '[' would parse the
  28221. // host as a hostname and miss the match.
  28222. ProxyAndTargetServers s;
  28223. Client cli("fe80::1", s.target_port());
  28224. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  28225. cli.set_proxy("127.0.0.1", s.proxy_port());
  28226. cli.set_no_proxy({"fe80::/10"});
  28227. auto res = cli.Get("/");
  28228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28229. EXPECT_EQ(0, s.proxy_hits());
  28230. EXPECT_EQ(1, s.target_hits());
  28231. }
  28232. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  28233. ProxyAndTargetServers s;
  28234. Client cli("::1", s.target_port());
  28235. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  28236. cli.set_proxy("127.0.0.1", s.proxy_port());
  28237. cli.set_no_proxy({"[::1]"});
  28238. auto res = cli.Get("/");
  28239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28240. EXPECT_EQ(0, s.proxy_hits());
  28241. EXPECT_EQ(1, s.target_hits());
  28242. }
  28243. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  28244. ProxyAndTargetServers s;
  28245. Client cli("fe80::1", s.target_port());
  28246. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  28247. cli.set_proxy("127.0.0.1", s.proxy_port());
  28248. cli.set_no_proxy({"[fe80::]/10"});
  28249. auto res = cli.Get("/");
  28250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28251. EXPECT_EQ(0, s.proxy_hits());
  28252. EXPECT_EQ(1, s.target_hits());
  28253. }
  28254. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  28255. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  28256. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  28257. // tricks via address-family conversion.
  28258. ProxyAndTargetServers s;
  28259. Client cli("::ffff:127.0.0.1", s.target_port());
  28260. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  28261. cli.set_proxy("127.0.0.1", s.proxy_port());
  28262. cli.set_no_proxy({"127.0.0.1"});
  28263. auto res = cli.Get("/");
  28264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28265. EXPECT_GE(s.proxy_hits(), 1);
  28266. EXPECT_EQ(0, s.target_hits());
  28267. }
  28268. TEST(NoProxyTest, IPv4CidrMatch) {
  28269. ProxyAndTargetServers s;
  28270. Client cli("127.0.0.1", s.target_port());
  28271. cli.set_proxy("127.0.0.1", s.proxy_port());
  28272. cli.set_no_proxy({"127.0.0.0/8"});
  28273. auto res = cli.Get("/");
  28274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28275. EXPECT_EQ(0, s.proxy_hits());
  28276. EXPECT_EQ(1, s.target_hits());
  28277. }
  28278. TEST(NoProxyTest, IPv4CidrNonMatch) {
  28279. ProxyAndTargetServers s;
  28280. Client cli("127.0.0.1", s.target_port());
  28281. cli.set_proxy("127.0.0.1", s.proxy_port());
  28282. cli.set_no_proxy({"10.0.0.0/8"});
  28283. auto res = cli.Get("/");
  28284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28285. EXPECT_GE(s.proxy_hits(), 1);
  28286. EXPECT_EQ(0, s.target_hits());
  28287. }
  28288. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  28289. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  28290. // IPv4 target matches.
  28291. ProxyAndTargetServers s;
  28292. Client cli("127.0.0.1", s.target_port());
  28293. cli.set_proxy("127.0.0.1", s.proxy_port());
  28294. cli.set_no_proxy({"0.0.0.0/0"});
  28295. auto res = cli.Get("/");
  28296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28297. EXPECT_EQ(0, s.proxy_hits());
  28298. EXPECT_EQ(1, s.target_hits());
  28299. }
  28300. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  28301. ProxyAndTargetServers s;
  28302. Client cli("127.0.0.1", s.target_port());
  28303. cli.set_proxy("127.0.0.1", s.proxy_port());
  28304. cli.set_no_proxy({"127.0.0.1"});
  28305. auto res = cli.Get("/");
  28306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28307. EXPECT_EQ(0, s.proxy_hits());
  28308. EXPECT_EQ(1, s.target_hits());
  28309. }
  28310. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  28311. ProxyAndTargetServers s;
  28312. Client cli("127.0.0.1", s.target_port());
  28313. cli.set_proxy("127.0.0.1", s.proxy_port());
  28314. cli.set_no_proxy({"127.0.0.0/33"});
  28315. auto res = cli.Get("/");
  28316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28317. EXPECT_GE(s.proxy_hits(), 1);
  28318. EXPECT_EQ(0, s.target_hits());
  28319. }
  28320. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  28321. // Empty prefix after the slash must be rejected, not silently treated as /32.
  28322. ProxyAndTargetServers s;
  28323. Client cli("127.0.0.1", s.target_port());
  28324. cli.set_proxy("127.0.0.1", s.proxy_port());
  28325. cli.set_no_proxy({"127.0.0.1/"});
  28326. auto res = cli.Get("/");
  28327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28328. EXPECT_GE(s.proxy_hits(), 1);
  28329. EXPECT_EQ(0, s.target_hits());
  28330. }
  28331. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  28332. ProxyAndTargetServers s;
  28333. auto cli = make_client("internal.corp", s);
  28334. cli->set_proxy_basic_auth("u", "p");
  28335. cli->set_no_proxy({"internal.corp"});
  28336. auto res = cli->Get("/");
  28337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28338. EXPECT_EQ(1, s.target_hits());
  28339. EXPECT_EQ(0, s.proxy_hits());
  28340. EXPECT_FALSE(s.last_had_proxy_authz())
  28341. << "Proxy-Authorization must not be sent direct to the target";
  28342. }
  28343. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  28344. ProxyAndTargetServers s;
  28345. auto cli = make_client("public.example", s);
  28346. cli->set_proxy_basic_auth("u", "p");
  28347. cli->set_no_proxy({"internal.corp"}); // does not match
  28348. auto res = cli->Get("/");
  28349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28350. EXPECT_GE(s.proxy_hits(), 1);
  28351. EXPECT_TRUE(s.last_had_proxy_authz());
  28352. }
  28353. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  28354. std::atomic<int> hits{0};
  28355. std::atomic<int> hits_with_authz{0};
  28356. no_proxy_test::ScopedServer proxy_mock;
  28357. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28358. hits++;
  28359. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  28360. if (req.target.find("/redir") != std::string::npos) {
  28361. res.set_redirect("http://other.example/landed");
  28362. } else {
  28363. res.set_content("via-proxy", "text/plain");
  28364. }
  28365. });
  28366. proxy_mock.listen();
  28367. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  28368. hits = 0;
  28369. hits_with_authz = 0;
  28370. Client cli("public.example", 80);
  28371. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28372. cli.set_proxy_basic_auth(c.first, c.second);
  28373. cli.set_follow_location(true);
  28374. // The redirect to another host goes through the proxy as well
  28375. auto res = cli.Get("/redir");
  28376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28377. EXPECT_EQ(2, hits.load());
  28378. EXPECT_EQ(2, hits_with_authz.load());
  28379. }
  28380. }
  28381. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  28382. ProxyAndTargetServers s;
  28383. auto cli = make_client("anything.test", s);
  28384. auto res = cli->Get("/");
  28385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28386. EXPECT_GE(s.proxy_hits(), 1);
  28387. EXPECT_EQ(0, s.target_hits());
  28388. }
  28389. TEST(NoProxyTest, PortSpecificEntryRejected) {
  28390. ProxyAndTargetServers s;
  28391. auto cli = make_client("example.com", s);
  28392. cli->set_no_proxy({"example.com:8080"});
  28393. auto res = cli->Get("/");
  28394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28395. EXPECT_GE(s.proxy_hits(), 1);
  28396. EXPECT_EQ(0, s.target_hits());
  28397. }
  28398. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  28399. ProxyAndTargetServers s;
  28400. auto cli = make_client("anything.test", s);
  28401. cli->set_no_proxy({"", " ", "\t"});
  28402. auto res = cli->Get("/");
  28403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28404. EXPECT_GE(s.proxy_hits(), 1);
  28405. EXPECT_EQ(0, s.target_hits());
  28406. }
  28407. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  28408. // An entry with leading/trailing whitespace must still match — env-style
  28409. // values are commonly pasted with stray spaces and an implementation
  28410. // that feeds the raw token directly to inet_pton would fail to match
  28411. // valid CIDRs because of the spaces.
  28412. ProxyAndTargetServers s;
  28413. Client cli("127.0.0.1", s.target_port());
  28414. cli.set_proxy("127.0.0.1", s.proxy_port());
  28415. cli.set_no_proxy({" 127.0.0.0/8 "});
  28416. auto res = cli.Get("/");
  28417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28418. EXPECT_EQ(0, s.proxy_hits());
  28419. EXPECT_EQ(1, s.target_hits());
  28420. }
  28421. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  28422. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  28423. // go direct and must NOT carry Proxy-Authorization.
  28424. std::atomic<int> proxy_hits{0};
  28425. std::atomic<int> target_hits{0};
  28426. std::atomic<bool> target_saw_authz{false};
  28427. no_proxy_test::ScopedServer proxy_mock, target;
  28428. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28429. proxy_hits++;
  28430. res.status = 302;
  28431. res.set_header("Location", "http://127.0.0.1:" +
  28432. std::to_string(target.port()) + "/landed");
  28433. });
  28434. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28435. target_hits++;
  28436. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  28437. res.set_content("direct", "text/plain");
  28438. });
  28439. proxy_mock.listen();
  28440. target.listen();
  28441. Client cli("public.example", target.port());
  28442. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28443. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28444. cli.set_proxy_basic_auth("u", "p");
  28445. cli.set_no_proxy({"127.0.0.1"});
  28446. cli.set_follow_location(true);
  28447. auto res = cli.Get("/redir");
  28448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28449. EXPECT_GE(proxy_hits.load(), 1);
  28450. EXPECT_GE(target_hits.load(), 1);
  28451. EXPECT_FALSE(target_saw_authz.load());
  28452. }
  28453. #ifdef CPPHTTPLIB_SSL_ENABLED
  28454. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  28455. // Direct origin replying 407 must not trigger the digest retry; otherwise
  28456. // proxy creds would be sent to the (possibly hostile) origin.
  28457. std::atomic<int> target_hits{0};
  28458. std::atomic<bool> target_saw_proxy_authz{false};
  28459. no_proxy_test::ScopedServer target;
  28460. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28461. target_hits++;
  28462. if (req.has_header("Proxy-Authorization")) {
  28463. target_saw_proxy_authz = true;
  28464. }
  28465. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28466. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  28467. "nonce=\"abc\", algorithm=MD5");
  28468. });
  28469. target.listen();
  28470. // The proxy address is set to the target's port: the bypass MUST kick in;
  28471. // if it doesn't, the test still routes "via proxy" to the same server and
  28472. // the Proxy-Authorization assertion below catches the leak.
  28473. Client cli("evil.example", target.port());
  28474. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  28475. cli.set_proxy("127.0.0.1", target.port());
  28476. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28477. cli.set_no_proxy({"evil.example"});
  28478. auto res = cli.Get("/x");
  28479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28480. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28481. EXPECT_EQ(1, target_hits.load());
  28482. EXPECT_FALSE(target_saw_proxy_authz.load());
  28483. }
  28484. #endif
  28485. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  28486. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  28487. std::atomic<int> proxy_hits{0};
  28488. std::atomic<int> bypass_hits{0};
  28489. std::atomic<bool> proxy_saw_c_url{false};
  28490. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  28491. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28492. proxy_hits++;
  28493. if (req.path.find("/start") != std::string::npos) {
  28494. res.status = 302;
  28495. res.set_header("Location", "http://127.0.0.1:" +
  28496. std::to_string(bypass_server.port()) +
  28497. "/middle");
  28498. return;
  28499. }
  28500. if (req.path.find("/end") != std::string::npos) {
  28501. proxy_saw_c_url = true;
  28502. res.set_content("c-via-proxy", "text/plain");
  28503. return;
  28504. }
  28505. res.set_content("unexpected", "text/plain");
  28506. });
  28507. // public.example's "advertised" port is arbitrary (the request never lands
  28508. // there — it goes through the proxy), but use a dynamic value to stay
  28509. // friendly with sharded parallel runs.
  28510. int public_port = bypass_server.port();
  28511. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  28512. bypass_hits++;
  28513. res.status = 302;
  28514. res.set_header("Location", "http://public.example:" +
  28515. std::to_string(public_port) + "/end");
  28516. });
  28517. proxy_mock.listen();
  28518. bypass_server.listen();
  28519. Client cli("public.example", public_port);
  28520. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28521. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28522. cli.set_no_proxy({"127.0.0.1"});
  28523. cli.set_follow_location(true);
  28524. auto res = cli.Get("/start");
  28525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28526. EXPECT_EQ(StatusCode::OK_200, res->status);
  28527. EXPECT_EQ("c-via-proxy", res->body);
  28528. EXPECT_GE(proxy_hits.load(), 2);
  28529. EXPECT_GE(bypass_hits.load(), 1);
  28530. EXPECT_TRUE(proxy_saw_c_url.load());
  28531. }
  28532. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  28533. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  28534. // request reconnects to the correct endpoint.
  28535. std::atomic<int> proxy_hits{0};
  28536. std::atomic<int> target_hits{0};
  28537. no_proxy_test::ScopedServer proxy_mock, target;
  28538. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28539. proxy_hits++;
  28540. res.set_content("via-proxy", "text/plain");
  28541. });
  28542. target.svr().Get(".*", [&](const Request &, Response &res) {
  28543. target_hits++;
  28544. res.set_content("direct", "text/plain");
  28545. });
  28546. proxy_mock.listen();
  28547. target.listen();
  28548. Client cli("public.example", target.port());
  28549. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28550. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28551. cli.set_keep_alive(true);
  28552. auto res1 = cli.Get("/a");
  28553. ASSERT_TRUE(res1);
  28554. EXPECT_EQ("via-proxy", res1->body);
  28555. EXPECT_EQ(1, proxy_hits.load());
  28556. EXPECT_EQ(0, target_hits.load());
  28557. cli.set_no_proxy({"public.example"});
  28558. auto res2 = cli.Get("/b");
  28559. ASSERT_TRUE(res2);
  28560. EXPECT_EQ("direct", res2->body);
  28561. EXPECT_EQ(1, proxy_hits.load());
  28562. EXPECT_EQ(1, target_hits.load());
  28563. }
  28564. // Forward declarations (see the base64_encode note).
  28565. namespace httplib {
  28566. namespace detail {
  28567. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  28568. int shutdown_socket(socket_t sock) noexcept;
  28569. } // namespace detail
  28570. } // namespace httplib
  28571. namespace proxy_tunnel_test {
  28572. const char *const kTunnelEstablished =
  28573. "HTTP/1.1 200 Connection established\r\n\r\n";
  28574. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  28575. using ConnectReply = std::function<std::string(const std::string &head)>;
  28576. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  28577. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  28578. class ScopedConnectProxy {
  28579. public:
  28580. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  28581. : forward_port_(forward_port), reply_(std::move(reply)) {
  28582. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  28583. if (listen_sock_ == INVALID_SOCKET) { return; }
  28584. auto a = loopback(0);
  28585. auto addr = reinterpret_cast<sockaddr *>(&a);
  28586. socklen_t alen = sizeof(a);
  28587. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  28588. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  28589. ::listen(listen_sock_, 4) != 0) {
  28590. return;
  28591. }
  28592. port_ = ntohs(a.sin_port);
  28593. th_ = std::thread([this] { run(); });
  28594. }
  28595. ~ScopedConnectProxy() {
  28596. if (th_.joinable()) {
  28597. stop_ = true;
  28598. auto wake = connect_to(port_);
  28599. th_.join();
  28600. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28601. }
  28602. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28603. }
  28604. int port() const { return port_; }
  28605. int connect_hits() const { return connect_hits_.load(); }
  28606. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28607. std::string connect_request() const {
  28608. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28609. return connect_request_;
  28610. }
  28611. private:
  28612. static sockaddr_in loopback(int port) {
  28613. sockaddr_in a{};
  28614. a.sin_family = AF_INET;
  28615. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28616. a.sin_port = htons(static_cast<unsigned short>(port));
  28617. return a;
  28618. }
  28619. static socket_t connect_to(int port) {
  28620. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28621. if (sock == INVALID_SOCKET) { return sock; }
  28622. auto a = loopback(port);
  28623. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28624. detail::close_socket(sock);
  28625. return INVALID_SOCKET;
  28626. }
  28627. return sock;
  28628. }
  28629. static bool send_all(socket_t sock, const char *data, size_t size) {
  28630. while (size > 0) {
  28631. auto n = detail::send_socket(sock, data, size, 0);
  28632. if (n <= 0) { return false; }
  28633. data += n;
  28634. size -= static_cast<size_t>(n);
  28635. }
  28636. return true;
  28637. }
  28638. void run() {
  28639. for (;;) {
  28640. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28641. if (stop_) {
  28642. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28643. return;
  28644. }
  28645. if (client == INVALID_SOCKET) { continue; }
  28646. serve(client);
  28647. detail::close_socket(client);
  28648. }
  28649. }
  28650. void serve(socket_t client) {
  28651. std::string head;
  28652. char buf[2048];
  28653. while (head.find("\r\n\r\n") == std::string::npos) {
  28654. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28655. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28656. if (n <= 0) { return; }
  28657. head.append(buf, static_cast<size_t>(n));
  28658. }
  28659. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28660. connect_hits_++;
  28661. {
  28662. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28663. connect_request_ = head;
  28664. }
  28665. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28666. if (!send_all(client, res.data(), res.size()) ||
  28667. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28668. return;
  28669. }
  28670. auto origin = connect_to(forward_port_);
  28671. if (origin == INVALID_SOCKET) { return; }
  28672. // When either side stops, shut both down so the other pump returns too.
  28673. auto pump = [&](socket_t from, socket_t to) {
  28674. char b[8192];
  28675. for (;;) {
  28676. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28677. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28678. }
  28679. detail::shutdown_socket(client);
  28680. detail::shutdown_socket(origin);
  28681. };
  28682. std::thread up([&] { pump(client, origin); });
  28683. pump(origin, client);
  28684. up.join();
  28685. detail::close_socket(origin);
  28686. }
  28687. int forward_port_;
  28688. ConnectReply reply_;
  28689. socket_t listen_sock_ = INVALID_SOCKET;
  28690. int port_ = 0;
  28691. std::thread th_;
  28692. std::atomic<bool> stop_{false};
  28693. std::atomic<int> connect_hits_{0};
  28694. mutable std::mutex connect_request_mutex_;
  28695. std::string connect_request_;
  28696. };
  28697. } // namespace proxy_tunnel_test
  28698. #ifdef CPPHTTPLIB_SSL_ENABLED
  28699. namespace proxy_tunnel_test {
  28700. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28701. class ScopedSSLServer {
  28702. public:
  28703. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28704. port_ = svr_.bind_to_any_port("127.0.0.1");
  28705. }
  28706. ~ScopedSSLServer() {
  28707. svr_.stop();
  28708. if (th_.joinable()) { th_.join(); }
  28709. }
  28710. SSLServer &svr() { return svr_; }
  28711. int port() const { return port_; }
  28712. void listen() {
  28713. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28714. svr_.wait_until_ready();
  28715. }
  28716. private:
  28717. SSLServer svr_;
  28718. std::thread th_;
  28719. int port_ = 0;
  28720. };
  28721. // Sends one request through the CONNECT proxy to the TLS origin with a
  28722. // credential configured for each hop, and checks that each credential reaches
  28723. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28724. // origin's (every header in origin_headers) on the tunnelled request.
  28725. void CredentialsStayWithTheirHop(
  28726. const std::function<void(SSLClient &)> &set_credentials,
  28727. const std::string &scheme,
  28728. const std::vector<std::string> &origin_headers = {"Authorization"},
  28729. bool stream = false) {
  28730. std::atomic<int> origin_hits{0};
  28731. std::atomic<bool> origin_saw_proxy_authz{false};
  28732. std::atomic<bool> origin_saw_headers{false};
  28733. ScopedSSLServer origin;
  28734. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28735. origin_hits++;
  28736. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28737. origin_saw_headers =
  28738. std::all_of(origin_headers.begin(), origin_headers.end(),
  28739. [&](const std::string &h) { return req.has_header(h); });
  28740. res.set_content("ok", "text/plain");
  28741. });
  28742. origin.listen();
  28743. ScopedConnectProxy proxy(origin.port());
  28744. ASSERT_NE(0, proxy.port());
  28745. // Pinned to 127.0.0.1 for the same reason as the test below.
  28746. SSLClient cli("127.0.0.1", origin.port());
  28747. cli.enable_server_certificate_verification(false);
  28748. cli.set_proxy("127.0.0.1", proxy.port());
  28749. set_credentials(cli);
  28750. if (stream) {
  28751. auto handle = cli.open_stream("GET", "/x");
  28752. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28753. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28754. } else {
  28755. auto res = cli.Get("/x");
  28756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28757. EXPECT_EQ(StatusCode::OK_200, res->status);
  28758. }
  28759. EXPECT_EQ(1, origin_hits.load());
  28760. EXPECT_EQ(1, proxy.connect_hits());
  28761. EXPECT_TRUE(origin_saw_headers.load());
  28762. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28763. << "Proxy-Authorization must not be sent inside the tunnel";
  28764. auto connect_req = proxy.connect_request();
  28765. EXPECT_NE(std::string::npos,
  28766. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28767. for (const auto &h : origin_headers) {
  28768. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28769. << h << " must not be sent to the proxy on CONNECT";
  28770. }
  28771. }
  28772. } // namespace proxy_tunnel_test
  28773. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28774. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28775. [](SSLClient &cli) {
  28776. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28777. cli.set_basic_auth("origin-user", "origin-pass");
  28778. },
  28779. "Basic");
  28780. }
  28781. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28782. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28783. [](SSLClient &cli) {
  28784. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28785. cli.set_basic_auth("origin-user", "origin-pass");
  28786. },
  28787. "Basic", {"Authorization"}, true);
  28788. }
  28789. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28790. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28791. [](SSLClient &cli) {
  28792. cli.set_proxy_bearer_token_auth("proxy-token");
  28793. cli.set_bearer_token_auth("origin-token");
  28794. },
  28795. "Bearer");
  28796. }
  28797. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28798. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28799. [](SSLClient &cli) {
  28800. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28801. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28802. {"Cookie", "sid=origin-session"},
  28803. {"X-Api-Key", "origin-key"}});
  28804. },
  28805. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28806. }
  28807. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28808. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28809. // retry; otherwise proxy creds would be sent to the origin.
  28810. std::atomic<int> origin_hits{0};
  28811. std::atomic<bool> origin_saw_proxy_authz{false};
  28812. proxy_tunnel_test::ScopedSSLServer origin;
  28813. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28814. origin_hits++;
  28815. if (req.has_header("Proxy-Authorization")) {
  28816. origin_saw_proxy_authz = true;
  28817. }
  28818. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28819. res.set_header("Proxy-Authenticate",
  28820. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28821. "algorithm=MD5");
  28822. });
  28823. origin.listen();
  28824. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28825. ASSERT_NE(0, proxy.port());
  28826. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28827. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28828. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28829. // and answer with its own status, making this test flaky.
  28830. SSLClient cli("127.0.0.1", origin.port());
  28831. cli.enable_server_certificate_verification(false);
  28832. cli.set_proxy("127.0.0.1", proxy.port());
  28833. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28834. auto res = cli.Get("/x");
  28835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28836. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28837. EXPECT_EQ(1, origin_hits.load());
  28838. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28839. EXPECT_EQ(1, proxy.connect_hits());
  28840. }
  28841. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28842. std::string origin_sni;
  28843. std::string origin_host;
  28844. proxy_tunnel_test::ScopedSSLServer origin;
  28845. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28846. origin_sni = req.sni();
  28847. origin_host = req.get_header_value("Host");
  28848. res.set_content("ok", "text/plain");
  28849. });
  28850. origin.listen();
  28851. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28852. ASSERT_NE(0, proxy.port());
  28853. SSLClient cli("origin.example", origin.port());
  28854. cli.enable_server_certificate_verification(false);
  28855. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28856. cli.set_proxy("127.0.0.1", proxy.port());
  28857. auto res = cli.Get("/x");
  28858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28859. EXPECT_EQ(StatusCode::OK_200, res->status);
  28860. auto port = std::to_string(origin.port());
  28861. auto target = "127.0.0.1:" + port;
  28862. auto connect_req = proxy.connect_request();
  28863. EXPECT_EQ(1, proxy.connect_hits());
  28864. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28865. EXPECT_NE(std::string::npos,
  28866. connect_req.find("\r\nHost: " + target + "\r\n"));
  28867. EXPECT_EQ("origin.example", origin_sni);
  28868. EXPECT_EQ("origin.example:" + port, origin_host);
  28869. }
  28870. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28871. proxy_tunnel_test::ScopedSSLServer origin;
  28872. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28873. res.set_content("ok", "text/plain");
  28874. });
  28875. origin.listen();
  28876. proxy_tunnel_test::ScopedConnectProxy proxy(
  28877. origin.port(), [](const std::string &head) -> std::string {
  28878. if (head.find(
  28879. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28880. std::string::npos) {
  28881. return proxy_tunnel_test::kTunnelEstablished;
  28882. }
  28883. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28884. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28885. "nonce=\"abc\", algorithm=MD5\r\n"
  28886. "Content-Length: 0\r\n\r\n";
  28887. });
  28888. ASSERT_NE(0, proxy.port());
  28889. SSLClient cli("origin.example", origin.port());
  28890. cli.enable_server_certificate_verification(false);
  28891. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28892. cli.set_proxy("127.0.0.1", proxy.port());
  28893. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28894. auto res = cli.Get("/x");
  28895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28896. EXPECT_EQ(StatusCode::OK_200, res->status);
  28897. // The retried CONNECT is the one the proxy saw last.
  28898. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28899. auto connect_req = proxy.connect_request();
  28900. EXPECT_EQ(2, proxy.connect_hits());
  28901. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28902. EXPECT_NE(std::string::npos,
  28903. connect_req.find("\r\nHost: " + target + "\r\n"));
  28904. }
  28905. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28906. proxy_tunnel_test::ScopedSSLServer origin;
  28907. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28908. res.set_content("ok", "text/plain");
  28909. });
  28910. origin.listen();
  28911. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28912. ASSERT_NE(0, proxy.port());
  28913. SSLClient cli("origin.example", origin.port());
  28914. cli.enable_server_certificate_verification(false);
  28915. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28916. cli.set_proxy("127.0.0.1", proxy.port());
  28917. auto res = cli.Get("/x");
  28918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28919. EXPECT_EQ(StatusCode::OK_200, res->status);
  28920. auto target = "origin.example:" + std::to_string(origin.port());
  28921. auto connect_req = proxy.connect_request();
  28922. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28923. EXPECT_NE(std::string::npos,
  28924. connect_req.find("\r\nHost: " + target + "\r\n"));
  28925. }
  28926. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28927. proxy_tunnel_test::ScopedSSLServer origin;
  28928. auto port = std::to_string(origin.port());
  28929. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28930. res.set_redirect("https://next.example:" + port + "/y");
  28931. });
  28932. origin.svr().Get("/y", [](const Request &, Response &res) {
  28933. res.set_content("ok", "text/plain");
  28934. });
  28935. origin.listen();
  28936. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28937. ASSERT_NE(0, proxy.port());
  28938. SSLClient cli("origin.example", origin.port());
  28939. cli.enable_server_certificate_verification(false);
  28940. cli.set_tunnel_hostname_addr_map(
  28941. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28942. cli.set_proxy("127.0.0.1", proxy.port());
  28943. cli.set_follow_location(true);
  28944. auto res = cli.Get("/x");
  28945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28946. EXPECT_EQ("ok", res->body);
  28947. // The last CONNECT is the redirect client's.
  28948. ASSERT_EQ(2, proxy.connect_hits());
  28949. auto target = "127.0.0.1:" + port;
  28950. auto connect_req = proxy.connect_request();
  28951. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28952. EXPECT_NE(std::string::npos,
  28953. connect_req.find("\r\nHost: " + target + "\r\n"));
  28954. }
  28955. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28956. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28957. std::atomic<int> origin_hits{0};
  28958. proxy_tunnel_test::ScopedSSLServer origin;
  28959. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28960. origin_hits++;
  28961. res.set_content("ok", "text/plain");
  28962. });
  28963. origin.listen();
  28964. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28965. ASSERT_NE(0, proxy.port());
  28966. SSLClient cli("127.0.0.1", origin.port());
  28967. cli.enable_server_certificate_verification(false);
  28968. cli.set_proxy("127.0.0.1", proxy.port());
  28969. cli.set_keep_alive(true);
  28970. cli.set_session_verifier(
  28971. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28972. auto res = cli.Get("/x");
  28973. EXPECT_FALSE(res);
  28974. ASSERT_FALSE(cli.is_socket_open());
  28975. res = cli.Get("/x");
  28976. EXPECT_FALSE(res);
  28977. EXPECT_EQ(2, proxy.connect_hits());
  28978. auto handle = cli.open_stream("GET", "/x");
  28979. EXPECT_FALSE(handle.is_valid());
  28980. EXPECT_EQ(3, proxy.connect_hits());
  28981. EXPECT_EQ(0, origin_hits.load());
  28982. }
  28983. #endif
  28984. namespace proxy_tunnel_test {
  28985. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28986. // anything else gets a 407 with `challenge`.
  28987. ConnectReply require_proxy_auth(const std::string &expected,
  28988. const std::string &challenge) {
  28989. return [=](const std::string &head) -> std::string {
  28990. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28991. std::string::npos) {
  28992. return kTunnelEstablished;
  28993. }
  28994. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28995. "Proxy-Authenticate: " +
  28996. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28997. };
  28998. }
  28999. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  29000. // request, then echoes.
  29001. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  29002. ws.send(
  29003. "authorization:" + req.get_header_value("Authorization") +
  29004. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  29005. std::string msg;
  29006. while (ws.read(msg)) {
  29007. ws.send(msg);
  29008. }
  29009. }
  29010. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  29011. class ScopedWebSocketOrigin {
  29012. public:
  29013. ScopedWebSocketOrigin() {
  29014. server_.svr().WebSocket("/ws", report_auth_then_echo);
  29015. server_.listen();
  29016. }
  29017. int port() const { return server_.port(); }
  29018. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  29019. std::string url() const {
  29020. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  29021. }
  29022. private:
  29023. no_proxy_test::ScopedServer server_;
  29024. };
  29025. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  29026. // passed as a constructor header, and checks that each reaches only its hop.
  29027. void WebSocketCredentialsStayWithTheirHop(
  29028. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  29029. const std::string &proxy_authz, const std::string &origin_authz) {
  29030. ScopedWebSocketOrigin origin;
  29031. ScopedConnectProxy proxy(
  29032. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  29033. ASSERT_NE(0, proxy.port());
  29034. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  29035. client.set_proxy("127.0.0.1", proxy.port());
  29036. set_proxy_credentials(client);
  29037. auto res = client.connect();
  29038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29039. std::string msg;
  29040. ASSERT_TRUE(client.read(msg));
  29041. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  29042. client.close();
  29043. EXPECT_EQ(1, proxy.connect_hits());
  29044. EXPECT_EQ(std::string::npos,
  29045. proxy.connect_request().find("\r\nAuthorization: "))
  29046. << "origin credentials must not be sent to the proxy";
  29047. }
  29048. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  29049. void WebSocketSetterCredentialsStayWithTheirHop(
  29050. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  29051. const std::string &proxy_authz, const std::string &origin_authz) {
  29052. ScopedWebSocketOrigin origin;
  29053. ScopedConnectProxy proxy(
  29054. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  29055. ASSERT_NE(0, proxy.port());
  29056. ws::WebSocketClient client(origin.url());
  29057. client.set_proxy("127.0.0.1", proxy.port());
  29058. set_credentials(client);
  29059. auto res = client.connect();
  29060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29061. std::string msg;
  29062. ASSERT_TRUE(client.read(msg));
  29063. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  29064. client.close();
  29065. EXPECT_EQ(1, proxy.connect_hits());
  29066. EXPECT_EQ(std::string::npos,
  29067. proxy.connect_request().find("\r\nAuthorization: "))
  29068. << "origin credentials must not be sent to the proxy";
  29069. }
  29070. } // namespace proxy_tunnel_test
  29071. namespace {
  29072. // Connects `client` and returns the Authorization header its upgrade
  29073. // request carried, or "<failed>" when the connection could not be opened.
  29074. std::string websocket_authorization(ws::WebSocketClient &client) {
  29075. if (!client.connect()) { return "<failed>"; }
  29076. std::string msg;
  29077. if (!client.read(msg)) { return "<failed>"; }
  29078. client.close();
  29079. auto prefix = std::string("authorization:");
  29080. auto end = msg.find("|proxy-authorization:");
  29081. return msg.substr(prefix.size(), end - prefix.size());
  29082. }
  29083. } // namespace
  29084. TEST(WebSocketClientAuthTest, BasicAuth) {
  29085. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29086. ws::WebSocketClient client(origin.url());
  29087. client.set_basic_auth("user", "pass");
  29088. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  29089. websocket_authorization(client));
  29090. }
  29091. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  29092. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29093. ws::WebSocketClient client(origin.url());
  29094. client.set_basic_auth("user", "");
  29095. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  29096. websocket_authorization(client));
  29097. }
  29098. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  29099. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29100. ws::WebSocketClient client(origin.url());
  29101. client.set_bearer_token_auth("token123");
  29102. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  29103. }
  29104. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  29105. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29106. ws::WebSocketClient client(origin.url());
  29107. client.set_bearer_token_auth("token123");
  29108. client.set_basic_auth("user", "pass");
  29109. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  29110. websocket_authorization(client));
  29111. }
  29112. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  29113. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29114. ws::WebSocketClient client(origin.url(),
  29115. {{"Authorization", "Bearer from-header"}});
  29116. client.set_bearer_token_auth("from-setter");
  29117. client.set_basic_auth("user", "pass");
  29118. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  29119. }
  29120. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  29121. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29122. ws::WebSocketClient client(origin.url());
  29123. EXPECT_EQ("", websocket_authorization(client));
  29124. client.set_bearer_token_auth("first");
  29125. EXPECT_EQ("Bearer first", websocket_authorization(client));
  29126. client.set_bearer_token_auth("second");
  29127. EXPECT_EQ("Bearer second", websocket_authorization(client));
  29128. client.set_bearer_token_auth("");
  29129. EXPECT_EQ("", websocket_authorization(client));
  29130. }
  29131. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  29132. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29133. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29134. ASSERT_NE(0, proxy.port());
  29135. ws::WebSocketClient client(origin.url());
  29136. client.set_proxy("127.0.0.1", proxy.port());
  29137. auto res = client.connect();
  29138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29139. std::string msg;
  29140. ASSERT_TRUE(client.read(msg));
  29141. ASSERT_TRUE(client.send("hello"));
  29142. ASSERT_TRUE(client.read(msg));
  29143. EXPECT_EQ("hello", msg);
  29144. client.close();
  29145. EXPECT_EQ(1, proxy.connect_hits());
  29146. auto target = "127.0.0.1:" + std::to_string(origin.port());
  29147. auto connect_req = proxy.connect_request();
  29148. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29149. EXPECT_NE(std::string::npos,
  29150. connect_req.find("\r\nHost: " + target + "\r\n"));
  29151. }
  29152. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  29153. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  29154. [](ws::WebSocketClient &cli) {
  29155. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  29156. },
  29157. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  29158. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  29159. }
  29160. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  29161. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  29162. [](ws::WebSocketClient &cli) {
  29163. cli.set_proxy_bearer_token_auth("proxy-token");
  29164. },
  29165. "Bearer proxy-token", "Bearer origin-token");
  29166. }
  29167. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  29168. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  29169. [](ws::WebSocketClient &cli) {
  29170. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  29171. cli.set_basic_auth("origin-user", "origin-pass");
  29172. },
  29173. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  29174. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  29175. }
  29176. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  29177. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  29178. [](ws::WebSocketClient &cli) {
  29179. cli.set_proxy_bearer_token_auth("proxy-token");
  29180. cli.set_bearer_token_auth("origin-token");
  29181. },
  29182. "Bearer proxy-token", "Bearer origin-token");
  29183. }
  29184. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  29185. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29186. proxy_tunnel_test::ScopedConnectProxy proxy(
  29187. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29188. "Basic " + detail::base64_encode("proxy-user:"),
  29189. "Basic realm=\"proxy\""));
  29190. ASSERT_NE(0, proxy.port());
  29191. ws::WebSocketClient client(origin.url());
  29192. client.set_proxy("127.0.0.1", proxy.port());
  29193. client.set_proxy_basic_auth("proxy-user", "");
  29194. auto res = client.connect();
  29195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29196. client.close();
  29197. EXPECT_EQ(1, proxy.connect_hits());
  29198. }
  29199. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  29200. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29201. proxy_tunnel_test::ScopedConnectProxy proxy(
  29202. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29203. "Bearer proxy-token", "Basic realm=\"proxy\""));
  29204. ASSERT_NE(0, proxy.port());
  29205. ws::WebSocketClient client(origin.url());
  29206. client.set_proxy("127.0.0.1", proxy.port());
  29207. auto res = client.connect();
  29208. EXPECT_FALSE(res);
  29209. EXPECT_EQ(Error::ProxyConnection, res.error());
  29210. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  29211. EXPECT_EQ("Basic realm=\"proxy\"",
  29212. res.get_header_value("Proxy-Authenticate"));
  29213. EXPECT_FALSE(client.is_open());
  29214. }
  29215. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  29216. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29217. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29218. ASSERT_NE(0, proxy.port());
  29219. ws::WebSocketClient client(origin.url());
  29220. client.set_proxy("127.0.0.1", proxy.port());
  29221. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  29222. client.set_no_proxy({"127.0.0.1"});
  29223. auto res = client.connect();
  29224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29225. std::string msg;
  29226. ASSERT_TRUE(client.read(msg));
  29227. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  29228. << "proxy credentials must not reach a bypassed origin";
  29229. client.close();
  29230. EXPECT_EQ(0, proxy.connect_hits());
  29231. }
  29232. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  29233. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29234. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29235. ASSERT_NE(0, proxy.port());
  29236. ws::WebSocketClient client(origin.url());
  29237. client.set_proxy("127.0.0.1", proxy.port());
  29238. ASSERT_TRUE(client.connect());
  29239. ASSERT_TRUE(client.connect());
  29240. client.close();
  29241. EXPECT_EQ(2, proxy.connect_hits());
  29242. }
  29243. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  29244. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29245. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29246. ASSERT_NE(0, proxy.port());
  29247. auto port = std::to_string(origin.port());
  29248. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  29249. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  29250. client.set_proxy("127.0.0.1", proxy.port());
  29251. auto res = client.connect();
  29252. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29253. std::string msg;
  29254. ASSERT_TRUE(client.read(msg));
  29255. client.close();
  29256. EXPECT_EQ(1, proxy.connect_hits());
  29257. auto target = "127.0.0.1:" + port;
  29258. auto connect_req = proxy.connect_request();
  29259. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29260. EXPECT_NE(std::string::npos,
  29261. connect_req.find("\r\nHost: " + target + "\r\n"));
  29262. }
  29263. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  29264. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29265. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29266. ASSERT_NE(0, proxy.port());
  29267. auto port = std::to_string(origin.port());
  29268. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  29269. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  29270. client.set_proxy("127.0.0.1", proxy.port());
  29271. auto res = client.connect();
  29272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29273. client.close();
  29274. auto target = "origin.example:" + port;
  29275. auto connect_req = proxy.connect_request();
  29276. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29277. EXPECT_NE(std::string::npos,
  29278. connect_req.find("\r\nHost: " + target + "\r\n"));
  29279. }
  29280. #ifdef CPPHTTPLIB_SSL_ENABLED
  29281. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  29282. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29283. proxy_tunnel_test::ScopedConnectProxy proxy(
  29284. origin.port(), [](const std::string &head) -> std::string {
  29285. if (head.find(
  29286. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  29287. std::string::npos) {
  29288. return proxy_tunnel_test::kTunnelEstablished;
  29289. }
  29290. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  29291. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  29292. "nonce=\"abc\", algorithm=MD5\r\n"
  29293. "Content-Length: 0\r\n\r\n";
  29294. });
  29295. ASSERT_NE(0, proxy.port());
  29296. ws::WebSocketClient client(origin.url());
  29297. client.set_proxy("127.0.0.1", proxy.port());
  29298. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  29299. auto res = client.connect();
  29300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29301. std::string msg;
  29302. ASSERT_TRUE(client.read(msg));
  29303. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  29304. client.close();
  29305. EXPECT_EQ(2, proxy.connect_hits());
  29306. }
  29307. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  29308. proxy_tunnel_test::ScopedSSLServer origin;
  29309. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  29310. origin.listen();
  29311. proxy_tunnel_test::ScopedConnectProxy proxy(
  29312. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29313. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  29314. ASSERT_NE(0, proxy.port());
  29315. ws::WebSocketClient client(
  29316. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  29317. client.enable_server_certificate_verification(false);
  29318. client.set_proxy("127.0.0.1", proxy.port());
  29319. client.set_proxy_bearer_token_auth("proxy-token");
  29320. auto res = client.connect();
  29321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29322. std::string msg;
  29323. ASSERT_TRUE(client.read(msg));
  29324. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  29325. << "Proxy-Authorization must not be sent inside the tunnel";
  29326. client.close();
  29327. EXPECT_EQ(1, proxy.connect_hits());
  29328. }
  29329. #endif
  29330. // ---------------------------------------------------------------------------
  29331. // Poller
  29332. // ---------------------------------------------------------------------------
  29333. namespace poller_test {
  29334. struct PollerBackend {
  29335. const char *name;
  29336. std::unique_ptr<detail::Poller> (*create)();
  29337. };
  29338. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  29339. *os << backend.name;
  29340. }
  29341. // Every backend runs the same contract tests. A new one is added here only.
  29342. std::vector<PollerBackend> poller_backends() {
  29343. return {
  29344. {"poll", &detail::PollPoller::create},
  29345. #ifdef __linux__
  29346. {"epoll", &detail::EpollPoller::create},
  29347. #endif
  29348. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  29349. {"kqueue", &detail::KqueuePoller::create},
  29350. #endif
  29351. };
  29352. }
  29353. // A descriptor whose readability the test controls.
  29354. struct TestSocketPair {
  29355. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  29356. TestSocketPair() { detail::create_socket_pair(fd); }
  29357. ~TestSocketPair() {
  29358. for (auto s : fd) {
  29359. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  29360. }
  29361. }
  29362. bool ok() const { return fd[0] != INVALID_SOCKET; }
  29363. socket_t reader() const { return fd[0]; }
  29364. void make_readable() {
  29365. const char c = 1;
  29366. detail::send_socket(fd[1], &c, 1, 0);
  29367. }
  29368. void close_writer() {
  29369. detail::close_socket(fd[1]);
  29370. fd[1] = INVALID_SOCKET;
  29371. }
  29372. };
  29373. using Tokens = std::vector<detail::Poller::Token>;
  29374. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  29375. protected:
  29376. void SetUp() override {
  29377. poller_ = GetParam().create();
  29378. ASSERT_TRUE(poller_ != nullptr);
  29379. }
  29380. Tokens wait_for(int timeout_ms) {
  29381. Tokens ready;
  29382. poller_->wait(timeout_ms, ready);
  29383. std::sort(ready.begin(), ready.end());
  29384. return ready;
  29385. }
  29386. std::unique_ptr<detail::Poller> poller_;
  29387. };
  29388. } // namespace poller_test
  29389. using poller_test::PollerTest;
  29390. using poller_test::TestSocketPair;
  29391. using poller_test::Tokens;
  29392. INSTANTIATE_TEST_SUITE_P(
  29393. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  29394. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  29395. return std::string(p.param.name);
  29396. });
  29397. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  29398. TestSocketPair sp;
  29399. ASSERT_TRUE(sp.ok());
  29400. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  29401. EXPECT_EQ(Tokens{}, wait_for(0));
  29402. sp.make_readable();
  29403. EXPECT_EQ(Tokens{7}, wait_for(1000));
  29404. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  29405. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  29406. EXPECT_EQ(Tokens{8}, wait_for(1000));
  29407. }
  29408. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  29409. TestSocketPair sp;
  29410. ASSERT_TRUE(sp.ok());
  29411. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29412. poller_->disarm(sp.reader());
  29413. poller_->disarm(sp.reader()); // disarming twice is harmless
  29414. sp.make_readable();
  29415. EXPECT_EQ(Tokens{}, wait_for(0));
  29416. }
  29417. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  29418. TestSocketPair sp;
  29419. ASSERT_TRUE(sp.ok());
  29420. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29421. auto start = std::chrono::steady_clock::now();
  29422. EXPECT_EQ(Tokens{}, wait_for(30));
  29423. auto elapsed = std::chrono::steady_clock::now() - start;
  29424. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  29425. EXPECT_LT(elapsed, std::chrono::seconds(1));
  29426. }
  29427. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  29428. std::vector<std::unique_ptr<TestSocketPair>> sps;
  29429. for (detail::Poller::Token i = 0; i < 8; i++) {
  29430. sps.emplace_back(new TestSocketPair());
  29431. ASSERT_TRUE(sps.back()->ok());
  29432. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  29433. }
  29434. sps[0]->make_readable();
  29435. sps[3]->make_readable();
  29436. sps[7]->make_readable();
  29437. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  29438. // The others are still armed, the delivered ones are not.
  29439. sps[1]->make_readable();
  29440. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29441. EXPECT_EQ(Tokens{}, wait_for(0));
  29442. }
  29443. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  29444. TestSocketPair s0, s1, s2;
  29445. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  29446. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  29447. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  29448. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  29449. // A delivery may move another entry inside the poller.
  29450. s0.make_readable();
  29451. EXPECT_EQ(Tokens{0}, wait_for(1000));
  29452. // The entries left must still be found by descriptor.
  29453. poller_->disarm(s2.reader());
  29454. s1.make_readable();
  29455. s2.make_readable();
  29456. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29457. }
  29458. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  29459. TestSocketPair sp;
  29460. ASSERT_TRUE(sp.ok());
  29461. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  29462. sp.close_writer();
  29463. EXPECT_EQ(Tokens{5}, wait_for(1000));
  29464. char c;
  29465. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  29466. }
  29467. TEST_P(PollerTest, WakeEndsABlockedWait) {
  29468. std::thread waker([&] {
  29469. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  29470. poller_->wake();
  29471. });
  29472. Tokens ready;
  29473. auto start = std::chrono::steady_clock::now();
  29474. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  29475. waker.join();
  29476. EXPECT_TRUE(ready.empty());
  29477. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  29478. }
  29479. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  29480. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  29481. Tokens ready;
  29482. EXPECT_TRUE(poller_->wait(1000, ready));
  29483. }
  29484. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  29485. for (int i = 0; i < 1000; i++) {
  29486. poller_->wake();
  29487. }
  29488. Tokens ready;
  29489. EXPECT_TRUE(poller_->wait(0, ready));
  29490. EXPECT_FALSE(poller_->wait(0, ready));
  29491. poller_->wake();
  29492. EXPECT_TRUE(poller_->wait(0, ready));
  29493. }
  29494. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  29495. // Two threads publish changes and wake() after each, as a reactor's workers
  29496. // do. Every change must be seen without a wait() timing out. A lost wake()
  29497. // needs an unlucky interleaving, hence the rounds.
  29498. for (int round = 0; round < 5; round++) {
  29499. SCOPED_TRACE(round);
  29500. const int per_thread = 20000;
  29501. std::atomic<int> posted{0};
  29502. auto post = [&] {
  29503. for (int i = 0; i < per_thread; i++) {
  29504. posted++;
  29505. poller_->wake();
  29506. }
  29507. };
  29508. std::thread t1(post), t2(post);
  29509. auto lost = false;
  29510. Tokens ready;
  29511. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  29512. if (!poller_->wait(1000, ready)) {
  29513. lost = true;
  29514. break;
  29515. }
  29516. }
  29517. t1.join();
  29518. t2.join();
  29519. ASSERT_FALSE(lost);
  29520. }
  29521. }
  29522. TEST(PollerFactoryTest, MakePollerWorks) {
  29523. auto poller = detail::make_poller();
  29524. ASSERT_TRUE(poller != nullptr);
  29525. poller->wake();
  29526. std::vector<detail::Poller::Token> ready;
  29527. EXPECT_TRUE(poller->wait(1000, ready));
  29528. }
  29529. // ---------------------------------------------------------------------------
  29530. // Keep-alive parking
  29531. // ---------------------------------------------------------------------------
  29532. namespace parking_test {
  29533. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  29534. // runs once the port is bound and listening, before the server accepts.
  29535. struct RunningServer {
  29536. explicit RunningServer(
  29537. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  29538. : svr_(svr) {
  29539. port = svr_.bind_to_any_port("127.0.0.1");
  29540. if (before_listen) { before_listen(port); }
  29541. thread = std::thread([this] { svr_.listen_after_bind(); });
  29542. svr_.wait_until_ready();
  29543. }
  29544. ~RunningServer() {
  29545. svr_.stop();
  29546. if (thread.joinable()) { thread.join(); }
  29547. }
  29548. Server &svr_;
  29549. int port = 0;
  29550. std::thread thread;
  29551. };
  29552. struct Sockets {
  29553. std::vector<socket_t> socks;
  29554. ~Sockets() {
  29555. for (auto s : socks) {
  29556. detail::close_socket(s);
  29557. }
  29558. }
  29559. socket_t connect(int port) {
  29560. auto error = Error::Success;
  29561. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  29562. false, false, nullptr, 2, 0, 2, 0, 2,
  29563. 0, std::string(), error);
  29564. if (s != INVALID_SOCKET) { socks.push_back(s); }
  29565. return s;
  29566. }
  29567. };
  29568. std::chrono::steady_clock::time_point in_ms(int ms) {
  29569. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  29570. }
  29571. bool readable_by(socket_t sock,
  29572. std::chrono::steady_clock::time_point deadline) {
  29573. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  29574. deadline - std::chrono::steady_clock::now())
  29575. .count();
  29576. return left > 0 && detail::select_read(sock, 0, left) > 0;
  29577. }
  29578. bool send_get(socket_t sock, const std::string &path = "/") {
  29579. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  29580. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  29581. static_cast<ssize_t>(req.size());
  29582. }
  29583. // Reads one response whose body is "ok".
  29584. bool receives_ok(socket_t sock, int timeout_ms) {
  29585. auto deadline = in_ms(timeout_ms);
  29586. std::string buf;
  29587. while (readable_by(sock, deadline)) {
  29588. char tmp[1024];
  29589. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  29590. if (n <= 0) { return false; }
  29591. buf.append(tmp, static_cast<size_t>(n));
  29592. auto end = buf.find("\r\n\r\n");
  29593. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  29594. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  29595. buf.compare(end + 4, 2, "ok") == 0;
  29596. }
  29597. }
  29598. return false;
  29599. }
  29600. bool get_ok(socket_t sock, int timeout_ms) {
  29601. return send_get(sock) && receives_ok(sock, timeout_ms);
  29602. }
  29603. // Whether the server closes `sock` by `deadline`.
  29604. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29605. char c;
  29606. return readable_by(sock, deadline) &&
  29607. detail::read_socket(sock, &c, 1, 0) <= 0;
  29608. }
  29609. // Whether the server closes `sock` without answering a request.
  29610. bool get_refused(socket_t sock, int timeout_ms) {
  29611. return send_get(sock) && sees_eof(sock, in_ms(timeout_ms));
  29612. }
  29613. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29614. auto deadline = in_ms(timeout_ms);
  29615. while (!cond()) {
  29616. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29617. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29618. }
  29619. return true;
  29620. }
  29621. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29622. svr.new_task_queue = std::move(new_task_queue);
  29623. svr.set_keep_alive_parking(true);
  29624. svr.Get("/", [](const Request &, Response &res) {
  29625. res.set_content("ok", "text/plain");
  29626. });
  29627. }
  29628. std::function<TaskQueue *(void)> threads(size_t n) {
  29629. return [n] { return new ThreadPool(n); };
  29630. }
  29631. // Counts what the event loop managed to queue, so that a test can wait for it.
  29632. class CountingTaskQueue final : public TaskQueue {
  29633. public:
  29634. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29635. std::atomic<int> &full)
  29636. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29637. bool enqueue(std::function<void()> fn) override {
  29638. auto queued = pool_.enqueue([this, fn]() {
  29639. fn();
  29640. // Holds the worker back from taking the next job.
  29641. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29642. });
  29643. (queued ? ok_ : full_)++;
  29644. return queued;
  29645. }
  29646. void shutdown() override { pool_.shutdown(); }
  29647. std::atomic<int> pause_after_ms{0};
  29648. private:
  29649. ThreadPool pool_;
  29650. std::atomic<int> &ok_;
  29651. std::atomic<int> &full_;
  29652. };
  29653. // Holds handlers until it opens, or for 3 seconds at most.
  29654. class Gate {
  29655. public:
  29656. void wait() {
  29657. std::unique_lock<std::mutex> lock(m_);
  29658. entered_++;
  29659. cv_.notify_all();
  29660. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29661. }
  29662. void open() {
  29663. std::lock_guard<std::mutex> guard(m_);
  29664. open_ = true;
  29665. cv_.notify_all();
  29666. }
  29667. int entered() {
  29668. std::lock_guard<std::mutex> guard(m_);
  29669. return entered_;
  29670. }
  29671. private:
  29672. std::mutex m_;
  29673. std::condition_variable cv_;
  29674. bool open_ = false;
  29675. int entered_ = 0;
  29676. };
  29677. } // namespace parking_test
  29678. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29679. using namespace parking_test;
  29680. Server svr;
  29681. serve_ok(svr, threads(1));
  29682. RunningServer running(svr);
  29683. Sockets socks;
  29684. // One kept-alive connection that has been served, and many that have not
  29685. // sent anything yet. None of them may keep the only worker.
  29686. auto served = socks.connect(running.port);
  29687. ASSERT_TRUE(get_ok(served, 2000));
  29688. for (int i = 0; i < 49; i++) {
  29689. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29690. }
  29691. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29692. EXPECT_TRUE(get_ok(served, 1000));
  29693. }
  29694. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29695. using namespace parking_test;
  29696. Server svr;
  29697. serve_ok(svr, threads(1));
  29698. svr.set_keep_alive_timeout(1);
  29699. RunningServer running(svr);
  29700. Sockets socks;
  29701. for (int i = 0; i < 3; i++) {
  29702. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29703. }
  29704. // One worker waiting on each in turn would take about 3 seconds.
  29705. auto deadline = in_ms(2000);
  29706. for (auto s : socks.socks) {
  29707. EXPECT_TRUE(sees_eof(s, deadline));
  29708. }
  29709. }
  29710. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29711. using namespace parking_test;
  29712. std::atomic<int> queued{0}, full{0};
  29713. Server svr;
  29714. // One worker and room for one queued task.
  29715. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29716. Gate gate;
  29717. svr.Get("/block", [&](const Request &, Response &res) {
  29718. gate.wait();
  29719. res.set_content("ok", "text/plain");
  29720. });
  29721. RunningServer running(svr);
  29722. // Before the server stops, so that a failed run does not wait for the
  29723. // handler's timeout.
  29724. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29725. Sockets socks;
  29726. auto a = socks.connect(running.port);
  29727. ASSERT_TRUE(get_ok(a, 2000));
  29728. // B keeps the only worker busy.
  29729. auto b = socks.connect(running.port);
  29730. ASSERT_TRUE(send_get(b, "/block"));
  29731. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29732. // A new connection C fills the queue.
  29733. auto c = socks.connect(running.port);
  29734. ASSERT_TRUE(send_get(c));
  29735. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29736. // A's next request finds the queue full, but A has been served before, so it
  29737. // waits instead of being cut off.
  29738. ASSERT_TRUE(send_get(a));
  29739. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29740. gate.open();
  29741. EXPECT_TRUE(receives_ok(b, 2000));
  29742. EXPECT_TRUE(receives_ok(c, 2000));
  29743. EXPECT_TRUE(receives_ok(a, 2000));
  29744. }
  29745. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29746. using namespace parking_test;
  29747. std::atomic<int> queued{0}, full{0};
  29748. CountingTaskQueue *queue = nullptr;
  29749. Server svr;
  29750. // Two workers and room for one queued task.
  29751. serve_ok(svr,
  29752. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29753. Gate first, second;
  29754. svr.Get("/first", [&](const Request &, Response &res) {
  29755. first.wait();
  29756. res.set_content("ok", "text/plain");
  29757. });
  29758. svr.Get("/second", [&](const Request &, Response &res) {
  29759. second.wait();
  29760. res.set_content("ok", "text/plain");
  29761. });
  29762. RunningServer running(svr);
  29763. auto open_gates = detail::scope_exit([&] {
  29764. first.open();
  29765. second.open();
  29766. });
  29767. Sockets socks;
  29768. auto a = socks.connect(running.port);
  29769. ASSERT_TRUE(get_ok(a, 2000));
  29770. // B and D take both workers, and C fills the queue. One at a time: the
  29771. // queue has room for one job only until a worker takes it.
  29772. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29773. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29774. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29775. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29776. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29777. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29778. // A's next request waits in the backlog.
  29779. ASSERT_TRUE(send_get(a));
  29780. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29781. // B's worker finishes, then takes C off the queue only later, which makes
  29782. // room for A.
  29783. queue->pause_after_ms = 200;
  29784. first.open();
  29785. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29786. queue->pause_after_ms = 0;
  29787. second.open();
  29788. EXPECT_TRUE(receives_ok(a, 2000));
  29789. }
  29790. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29791. using namespace parking_test;
  29792. Server svr;
  29793. serve_ok(svr, threads(1));
  29794. svr.set_keep_alive_timeout(0);
  29795. // The request is on the socket before the server accepts the connection,
  29796. // so it does not race the 10 ms floor. Without the floor the connection is
  29797. // closed unread.
  29798. Sockets socks;
  29799. auto sock = INVALID_SOCKET;
  29800. RunningServer running(svr, [&](int port) {
  29801. sock = socks.connect(port);
  29802. send_get(sock);
  29803. });
  29804. EXPECT_TRUE(receives_ok(sock, 1000));
  29805. }
  29806. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29807. using namespace parking_test;
  29808. for (int round = 0; round < 5; round++) {
  29809. SCOPED_TRACE(round);
  29810. Server svr;
  29811. serve_ok(svr, threads(2));
  29812. RunningServer running(svr);
  29813. Sockets socks;
  29814. for (int i = 0; i < 20; i++) {
  29815. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29816. }
  29817. auto start = std::chrono::steady_clock::now();
  29818. svr.stop();
  29819. running.thread.join();
  29820. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29821. std::chrono::milliseconds(500));
  29822. auto deadline = in_ms(1000);
  29823. for (auto s : socks.socks) {
  29824. EXPECT_TRUE(sees_eof(s, deadline));
  29825. }
  29826. }
  29827. }
  29828. #ifdef CPPHTTPLIB_SSL_ENABLED
  29829. namespace parking_test {
  29830. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29831. // that has opened a connection ahead of time. Freeing the session sends no
  29832. // close_notify, so the connection stays quiet.
  29833. bool handshake_only(socket_t sock) {
  29834. auto ctx = tls::create_client_context();
  29835. tls::set_verify_client(ctx, false);
  29836. auto session = tls::create_session(ctx, sock);
  29837. auto se = detail::scope_exit([&] {
  29838. tls::free_session(session);
  29839. tls::free_context(ctx);
  29840. });
  29841. tls::TlsError err;
  29842. return session &&
  29843. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29844. }
  29845. Client tls_client(int port) {
  29846. Client cli("https://127.0.0.1:" + std::to_string(port));
  29847. cli.enable_server_certificate_verification(false);
  29848. cli.set_keep_alive(true);
  29849. cli.set_connection_timeout(1);
  29850. cli.set_read_timeout(1);
  29851. return cli;
  29852. }
  29853. bool tls_get_ok(Client &cli) {
  29854. auto res = cli.Get("/");
  29855. return res && res->body == "ok";
  29856. }
  29857. } // namespace parking_test
  29858. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29859. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29860. struct {
  29861. unsigned long version;
  29862. bool safe;
  29863. } cases[] = {
  29864. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29865. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29866. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29867. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29868. };
  29869. for (const auto &c : cases) {
  29870. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29871. << std::hex << c.version;
  29872. }
  29873. }
  29874. #endif
  29875. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29876. using namespace parking_test;
  29877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29878. ASSERT_TRUE(svr.is_valid());
  29879. serve_ok(svr, threads(1));
  29880. svr.set_read_timeout(1); // so that a failing run does not take long
  29881. RunningServer running(svr);
  29882. Sockets socks;
  29883. // One served connection, some that have not started their handshake, and
  29884. // one that has finished it and gone quiet. None may keep the only worker.
  29885. auto served = tls_client(running.port);
  29886. ASSERT_TRUE(tls_get_ok(served));
  29887. for (int i = 0; i < 10; i++) {
  29888. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29889. }
  29890. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29891. auto other = tls_client(running.port);
  29892. EXPECT_TRUE(tls_get_ok(other));
  29893. EXPECT_TRUE(tls_get_ok(served));
  29894. }
  29895. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29896. using namespace parking_test;
  29897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29898. ASSERT_TRUE(svr.is_valid());
  29899. serve_ok(svr, threads(1));
  29900. RunningServer running(svr);
  29901. Sockets socks;
  29902. auto plain = socks.connect(running.port);
  29903. ASSERT_TRUE(send_get(plain));
  29904. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29905. EXPECT_NE(0, svr.ssl_last_error());
  29906. }
  29907. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29908. using namespace parking_test;
  29909. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29910. ASSERT_TRUE(svr.is_valid());
  29911. serve_ok(svr, threads(2));
  29912. RunningServer running(svr);
  29913. std::vector<Client> clients;
  29914. for (int i = 0; i < 5; i++) {
  29915. clients.push_back(tls_client(running.port));
  29916. ASSERT_TRUE(tls_get_ok(clients.back()));
  29917. }
  29918. auto start = std::chrono::steady_clock::now();
  29919. svr.stop();
  29920. running.thread.join();
  29921. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29922. std::chrono::milliseconds(500));
  29923. }
  29924. #endif
  29925. TEST(AcceptHandlerTest, RefusedConnectionIsClosedUnread) {
  29926. using namespace parking_test;
  29927. for (auto parking : {false, true}) {
  29928. SCOPED_TRACE(parking);
  29929. Server svr;
  29930. serve_ok(svr, threads(2));
  29931. svr.set_keep_alive_parking(parking);
  29932. std::atomic<int> served{0};
  29933. svr.set_pre_routing_handler([&](const Request &, Response &) {
  29934. served++;
  29935. return Server::HandlerResponse::Unhandled;
  29936. });
  29937. std::atomic<bool> allow{false};
  29938. std::atomic<bool> peer_seen{false};
  29939. svr.set_accept_handler([&](socket_t sock) {
  29940. sockaddr_in addr{};
  29941. socklen_t len = sizeof(addr);
  29942. peer_seen =
  29943. getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) == 0 &&
  29944. addr.sin_family == AF_INET &&
  29945. ntohl(addr.sin_addr.s_addr) == INADDR_LOOPBACK;
  29946. return allow.load();
  29947. });
  29948. RunningServer running(svr);
  29949. Sockets socks;
  29950. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  29951. EXPECT_TRUE(peer_seen);
  29952. EXPECT_EQ(0, served);
  29953. allow = true;
  29954. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29955. EXPECT_EQ(1, served);
  29956. }
  29957. }
  29958. TEST(AcceptHandlerTest, HandlerSeesTheReadTimeout) {
  29959. using namespace parking_test;
  29960. Server svr;
  29961. serve_ok(svr, threads(1));
  29962. svr.set_read_timeout(std::chrono::milliseconds(50));
  29963. std::atomic<bool> timed_out{false};
  29964. svr.set_accept_handler([&](socket_t sock) {
  29965. char c;
  29966. timed_out = detail::read_socket(sock, &c, 1, 0) < 0;
  29967. return true;
  29968. });
  29969. RunningServer running(svr);
  29970. Sockets socks;
  29971. auto sock = socks.connect(running.port);
  29972. EXPECT_TRUE(wait_until([&] { return timed_out.load(); }, 1000));
  29973. EXPECT_TRUE(get_ok(sock, 1000));
  29974. }
  29975. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  29976. TEST(AcceptHandlerTest, ThrowingHandlerRefusesTheConnection) {
  29977. using namespace parking_test;
  29978. Server svr;
  29979. serve_ok(svr, threads(1));
  29980. std::atomic<bool> throws{true};
  29981. svr.set_accept_handler([&](socket_t) -> bool {
  29982. if (throws) { throw std::runtime_error("refused"); }
  29983. return true;
  29984. });
  29985. std::atomic<int> logged{0};
  29986. svr.set_error_logger([&](const Error &err, const Request *) {
  29987. if (err == Error::UserCallbackException) { logged++; }
  29988. });
  29989. RunningServer running(svr);
  29990. Sockets socks;
  29991. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  29992. EXPECT_EQ(1, logged);
  29993. throws = false;
  29994. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29995. }
  29996. #endif
  29997. #ifdef CPPHTTPLIB_SSL_ENABLED
  29998. TEST(AcceptHandlerTest, RefusedTlsConnectionSkipsTheHandshake) {
  29999. using namespace parking_test;
  30000. for (auto parking : {false, true}) {
  30001. SCOPED_TRACE(parking);
  30002. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  30003. ASSERT_TRUE(svr.is_valid());
  30004. serve_ok(svr, threads(1));
  30005. svr.set_keep_alive_parking(parking);
  30006. svr.set_accept_handler([](socket_t) { return false; });
  30007. RunningServer running(svr);
  30008. Sockets socks;
  30009. // A handshake on a plain request would fail and set ssl_last_error().
  30010. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  30011. EXPECT_EQ(0, svr.ssl_last_error());
  30012. }
  30013. }
  30014. #endif