test.cc 1.1 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. ctx_t create_client_context();
  75. void set_verify_client(ctx_t ctx, bool require);
  76. session_t create_session(ctx_t ctx, socket_t sock);
  77. void free_session(session_t session);
  78. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  79. time_t timeout_usec, TlsError *err,
  80. const std::function<bool()> &interrupted);
  81. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  82. time_t timeout_usec, TlsError *err);
  83. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  84. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  85. void shutdown(session_t session, bool graceful);
  86. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  87. namespace impl {
  88. SecTrustSettingsResult
  89. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  90. } // namespace impl
  91. #endif
  92. } // namespace tls
  93. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  94. namespace detail {
  95. bool ssl_free_buffers_is_safe(unsigned long version);
  96. } // namespace detail
  97. #endif
  98. } // namespace httplib
  99. #endif
  100. using namespace std;
  101. using namespace httplib;
  102. const char *HOST = "localhost";
  103. static int get_base_port() {
  104. const char *shard = getenv("GTEST_SHARD_INDEX");
  105. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  106. }
  107. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  108. // New standalone tests MUST use svr.bind_to_any_port() instead.
  109. const int PORT = get_base_port();
  110. const string LONG_QUERY_VALUE = string(25000, '@');
  111. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  112. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  113. const string TOO_LONG_QUERY_URL =
  114. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  115. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  116. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  117. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  118. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  119. return file.name == key;
  120. });
  121. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  122. return *it;
  123. #else
  124. if (it != items.end()) { return *it; }
  125. throw std::runtime_error("invalid multipart form data name error");
  126. #endif
  127. }
  128. static void read_file(const std::string &path, std::string &out) {
  129. std::ifstream fs(path, std::ios_base::binary);
  130. if (!fs) {
  131. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  132. return;
  133. #else
  134. throw std::runtime_error("File not found: " + path);
  135. #endif
  136. }
  137. fs.seekg(0, std::ios_base::end);
  138. auto size = fs.tellg();
  139. fs.seekg(0);
  140. out.resize(static_cast<size_t>(size));
  141. fs.read(&out[0], static_cast<std::streamsize>(size));
  142. }
  143. // httpbingo.org intermittently answers with gateway errors unrelated to the
  144. // client under test.
  145. static bool is_gateway_error(const Result &res) {
  146. return res && (res->status == StatusCode::BadGateway_502 ||
  147. res->status == StatusCode::ServiceUnavailable_503 ||
  148. res->status == StatusCode::GatewayTimeout_504);
  149. }
  150. template <typename F> static Result retry_gateway_errors(F &&send) {
  151. auto res = send();
  152. for (auto wait : {1, 2}) {
  153. if (!is_gateway_error(res)) { break; }
  154. std::this_thread::sleep_for(std::chrono::seconds(wait));
  155. res = send();
  156. }
  157. return res;
  158. }
  159. #define SKIP_ON_GATEWAY_ERROR(res) \
  160. do { \
  161. if (is_gateway_error(res)) { \
  162. GTEST_SKIP() << "gateway error " << (res)->status; \
  163. } \
  164. } while (0)
  165. class UnixSocketTest : public ::testing::Test {
  166. protected:
  167. void TearDown() override { std::remove(pathname_.c_str()); }
  168. void client_GET(const std::string &addr) {
  169. httplib::Client cli{addr};
  170. cli.set_address_family(AF_UNIX);
  171. ASSERT_TRUE(cli.is_valid());
  172. const auto &result = cli.Get(pattern_);
  173. ASSERT_TRUE(result) << "error: " << result.error();
  174. const auto &resp = result.value();
  175. EXPECT_EQ(resp.status, StatusCode::OK_200);
  176. EXPECT_EQ(resp.body, content_);
  177. }
  178. static std::string make_sock_path() {
  179. const char *shard = getenv("GTEST_SHARD_INDEX");
  180. return shard ? std::string("./httplib-server-") + shard + ".sock"
  181. : "./httplib-server.sock";
  182. }
  183. const std::string pathname_{make_sock_path()};
  184. const std::string pattern_{"/hi"};
  185. const std::string content_{"Hello World!"};
  186. };
  187. TEST_F(UnixSocketTest, pathname) {
  188. httplib::Server svr;
  189. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  190. res.set_content(content_, "text/plain");
  191. });
  192. std::thread t{[&] {
  193. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  194. }};
  195. auto se = detail::scope_exit([&] {
  196. svr.stop();
  197. t.join();
  198. ASSERT_FALSE(svr.is_running());
  199. });
  200. svr.wait_until_ready();
  201. ASSERT_TRUE(svr.is_running());
  202. client_GET(pathname_);
  203. // ".//x.sock", which is not taken for a URL
  204. client_GET("./" + pathname_.substr(1));
  205. }
  206. #if defined(__linux__) || \
  207. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  208. TEST_F(UnixSocketTest, PeerPid) {
  209. httplib::Server svr;
  210. std::string remote_port_val;
  211. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  212. res.set_content(content_, "text/plain");
  213. remote_port_val = std::to_string(req.remote_port);
  214. });
  215. std::thread t{[&] {
  216. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  217. }};
  218. auto se = detail::scope_exit([&] {
  219. svr.stop();
  220. t.join();
  221. ASSERT_FALSE(svr.is_running());
  222. });
  223. svr.wait_until_ready();
  224. ASSERT_TRUE(svr.is_running());
  225. client_GET(pathname_);
  226. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  227. }
  228. #endif
  229. #ifdef __linux__
  230. TEST_F(UnixSocketTest, abstract) {
  231. constexpr char svr_path[]{"\x00httplib-server.sock"};
  232. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  233. httplib::Server svr;
  234. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  235. res.set_content(content_, "text/plain");
  236. });
  237. std::thread t{[&] {
  238. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  239. }};
  240. auto se = detail::scope_exit([&] {
  241. svr.stop();
  242. t.join();
  243. ASSERT_FALSE(svr.is_running());
  244. });
  245. svr.wait_until_ready();
  246. ASSERT_TRUE(svr.is_running());
  247. client_GET(abstract_addr);
  248. }
  249. #endif
  250. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  251. httplib::Server svr;
  252. std::string received_host_header;
  253. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  254. // Capture the Host header sent by the client
  255. auto host_iter = req.headers.find("Host");
  256. if (host_iter != req.headers.end()) {
  257. received_host_header = host_iter->second;
  258. }
  259. res.set_content(content_, "text/plain");
  260. });
  261. std::thread t{[&] {
  262. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  263. }};
  264. auto se = detail::scope_exit([&] {
  265. svr.stop();
  266. t.join();
  267. ASSERT_FALSE(svr.is_running());
  268. });
  269. svr.wait_until_ready();
  270. ASSERT_TRUE(svr.is_running());
  271. // Test that Host header is automatically set to "localhost" for Unix socket
  272. // connections
  273. httplib::Client cli{pathname_};
  274. cli.set_address_family(AF_UNIX);
  275. ASSERT_TRUE(cli.is_valid());
  276. const auto &result = cli.Get(pattern_);
  277. ASSERT_TRUE(result) << "error: " << result.error();
  278. const auto &resp = result.value();
  279. EXPECT_EQ(resp.status, StatusCode::OK_200);
  280. EXPECT_EQ(resp.body, content_);
  281. // Verify that Host header was automatically set to "localhost"
  282. EXPECT_EQ(received_host_header, "localhost");
  283. }
  284. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  285. // Another socket in the working directory, which a Location can name as
  286. // its host
  287. const auto other_path = "other-" + pathname_.substr(2);
  288. httplib::Server svr;
  289. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  290. // An absolute Location naming the Host this client sends
  291. res.set_redirect("http://localhost" + pattern_);
  292. });
  293. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  294. res.set_redirect("http://" + other_path + pattern_);
  295. });
  296. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  297. res.set_redirect("http://mapped.test" + pattern_);
  298. });
  299. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  300. res.set_header("X-Auth", req.get_header_value("Authorization"));
  301. res.set_content(content_, "text/plain");
  302. });
  303. httplib::Server other;
  304. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  305. res.set_content("other", "text/plain");
  306. });
  307. std::thread t{[&] {
  308. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  309. }};
  310. std::thread t2{[&] {
  311. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  312. }};
  313. auto se = detail::scope_exit([&] {
  314. svr.stop();
  315. other.stop();
  316. t.join();
  317. t2.join();
  318. std::remove(other_path.c_str());
  319. });
  320. svr.wait_until_ready();
  321. other.wait_until_ready();
  322. httplib::Client cli{pathname_};
  323. cli.set_address_family(AF_UNIX);
  324. cli.set_follow_location(true);
  325. cli.set_bearer_token_auth("token");
  326. // Another host: the same socket, without the credentials
  327. auto res = cli.Get("/cross");
  328. ASSERT_TRUE(res) << "error: " << res.error();
  329. EXPECT_EQ(StatusCode::OK_200, res->status);
  330. EXPECT_EQ(content_, res->body);
  331. EXPECT_EQ("", res->get_header_value("X-Auth"));
  332. // localhost is this client's own host
  333. res = cli.Get("/redirect");
  334. ASSERT_TRUE(res) << "error: " << res.error();
  335. EXPECT_EQ(StatusCode::OK_200, res->status);
  336. EXPECT_EQ(content_, res->body);
  337. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  338. // A host the caller mapped to a socket goes there
  339. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  340. res = cli.Get("/mapped");
  341. ASSERT_TRUE(res) << "error: " << res.error();
  342. EXPECT_EQ(StatusCode::OK_200, res->status);
  343. EXPECT_EQ("other", res->body);
  344. }
  345. #ifndef _WIN32
  346. TEST(SocketStream, wait_writable_UNIX) {
  347. int fds[2];
  348. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  349. const auto asSocketStream = [&](socket_t fd,
  350. std::function<bool(Stream &)> func) {
  351. return detail::process_client_socket(
  352. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  353. };
  354. asSocketStream(fds[0], [&](Stream &s0) {
  355. EXPECT_EQ(s0.socket(), fds[0]);
  356. EXPECT_TRUE(s0.wait_writable());
  357. EXPECT_TRUE(s0.is_peer_alive());
  358. EXPECT_EQ(0, close(fds[1]));
  359. EXPECT_FALSE(s0.is_peer_alive());
  360. return true;
  361. });
  362. EXPECT_EQ(0, close(fds[0]));
  363. }
  364. TEST(SocketStream, wait_writable_INET) {
  365. sockaddr_in addr;
  366. memset(&addr, 0, sizeof(addr));
  367. addr.sin_family = AF_INET;
  368. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  369. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  370. int disconnected_svr_sock = -1;
  371. std::thread svr{[&] {
  372. const int s = socket(AF_INET, SOCK_STREAM, 0);
  373. ASSERT_LE(0, s);
  374. // PORT + 1 is shared with the SSL redirect tests and with
  375. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  376. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  377. // because that happens on a worker thread the ASSERT does not stop the
  378. // test: it runs on and fails at the disconnected_svr_sock check instead.
  379. default_socket_options(s);
  380. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  381. ASSERT_EQ(0, listen(s, 1));
  382. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  383. ASSERT_EQ(0, close(s));
  384. }};
  385. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  386. std::thread cli{[&] {
  387. const int s = socket(AF_INET, SOCK_STREAM, 0);
  388. ASSERT_LE(0, s);
  389. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  390. ASSERT_EQ(0, close(s));
  391. }};
  392. cli.join();
  393. svr.join();
  394. ASSERT_NE(disconnected_svr_sock, -1);
  395. const auto asSocketStream = [&](socket_t fd,
  396. std::function<bool(Stream &)> func) {
  397. return detail::process_client_socket(
  398. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  399. };
  400. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  401. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  402. // wait_writable() returns true because select_write() only checks if the
  403. // send buffer has space. Peer disconnection is detected later by send().
  404. EXPECT_TRUE(ss.wait_writable());
  405. return true;
  406. });
  407. ASSERT_EQ(0, close(disconnected_svr_sock));
  408. }
  409. #endif // #ifndef _WIN32
  410. TEST(SetSocketOptTest, TcpNoDelay) {
  411. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  412. ASSERT_NE(sock, INVALID_SOCKET);
  413. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  414. int val = 0;
  415. socklen_t len = sizeof(val);
  416. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  417. reinterpret_cast<char *>(&val), &len));
  418. EXPECT_NE(val, 0);
  419. detail::close_socket(sock);
  420. }
  421. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  422. // accept() reports failures through WSAGetLastError() on Windows and through
  423. // errno everywhere else. Asking the wrong one is what made the accept loop
  424. // treat every recoverable failure as fatal on Windows.
  425. struct Classification {
  426. bool resource;
  427. bool transient;
  428. };
  429. auto classify = [](int err) {
  430. #ifdef _WIN32
  431. WSASetLastError(err);
  432. #else
  433. errno = err;
  434. #endif
  435. // Read both before asserting: an assertion may clobber the error slot.
  436. Classification c;
  437. c.resource = detail::is_accept_resource_error();
  438. c.transient = detail::is_accept_transient_error();
  439. return c;
  440. };
  441. #ifdef _WIN32
  442. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  443. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  444. WSAECONNRESET, WSAECONNABORTED};
  445. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  446. #else
  447. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  448. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  449. ECONNABORTED};
  450. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  451. #endif
  452. for (auto err : resource_errors) {
  453. const auto c = classify(err);
  454. EXPECT_TRUE(c.resource) << "error " << err;
  455. EXPECT_FALSE(c.transient) << "error " << err;
  456. }
  457. for (auto err : transient_errors) {
  458. const auto c = classify(err);
  459. EXPECT_TRUE(c.transient) << "error " << err;
  460. EXPECT_FALSE(c.resource) << "error " << err;
  461. }
  462. for (auto err : fatal_errors) {
  463. const auto c = classify(err);
  464. EXPECT_FALSE(c.resource) << "error " << err;
  465. EXPECT_FALSE(c.transient) << "error " << err;
  466. }
  467. #ifdef _WIN32
  468. WSASetLastError(0);
  469. #else
  470. errno = 0;
  471. #endif
  472. }
  473. TEST(ClientTest, MoveConstructible) {
  474. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  475. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  476. }
  477. TEST(ClientTest, MoveAssignable) {
  478. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  479. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  480. }
  481. #ifdef _WIN32
  482. TEST(StartupTest, WSAStartup) {
  483. WSADATA wsaData;
  484. int ret = WSAStartup(0x0002, &wsaData);
  485. ASSERT_EQ(0, ret);
  486. }
  487. #endif
  488. TEST(DecodePathTest, PercentCharacter) {
  489. EXPECT_EQ(
  490. decode_path_component(
  491. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  492. U8("descrip=Gastos áéíóúñÑ 6"));
  493. }
  494. TEST(DecodePathTest, PercentCharacterNUL) {
  495. string expected;
  496. expected.push_back('x');
  497. expected.push_back('\0');
  498. expected.push_back('x');
  499. EXPECT_EQ(decode_path_component("x%00x"), expected);
  500. }
  501. TEST(DecodePathTest, UnicodeEncoding) {
  502. // %u0041 = 'A' (1-byte UTF-8)
  503. EXPECT_EQ("A", decode_path_component("%u0041"));
  504. // %u00E9 = 'é' (2-byte UTF-8)
  505. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  506. // %u3042 = 'あ' (3-byte UTF-8)
  507. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  508. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  509. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  510. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  511. // neighbours)
  512. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  513. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  514. }
  515. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  516. // A sign or whitespace inside the two-character escape window must not be
  517. // accepted as a valid percent-encoding; the sequence is passed through
  518. // literally, matching decode_uri_component / decode_path_component.
  519. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  520. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  521. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  522. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  523. // Well-formed escapes still decode.
  524. EXPECT_EQ("-", decode_query_component("%2D", false));
  525. EXPECT_EQ("A", decode_query_component("%41", false));
  526. }
  527. TEST(SanitizeFilenameTest, VariousPatterns) {
  528. // Path traversal
  529. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  530. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  531. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  532. // Normal and edge cases
  533. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  534. EXPECT_EQ("filename.txt",
  535. httplib::sanitize_filename("/path/to/filename.txt"));
  536. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  537. EXPECT_EQ("", httplib::sanitize_filename(".."));
  538. EXPECT_EQ("", httplib::sanitize_filename(""));
  539. // Null bytes stripped
  540. EXPECT_EQ("safe.txt",
  541. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  542. // Whitespace-only rejected
  543. EXPECT_EQ("", httplib::sanitize_filename(" "));
  544. }
  545. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  546. // before it is dropped; anywhere else it is an ordinary file name character.
  547. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  548. #ifdef _WIN32
  549. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  550. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  551. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  552. #else
  553. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  554. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  555. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  556. #endif
  557. }
  558. // Forward declaration (see the base64_encode note below): split builds move the
  559. // definition into httplib.cc, so re-declaring it here lets the test link.
  560. namespace httplib {
  561. namespace detail {
  562. bool is_chunked_transfer_encoding(const Headers &headers);
  563. } // namespace detail
  564. } // namespace httplib
  565. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  566. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  567. auto make = [](std::initializer_list<const char *> lines) {
  568. Headers h;
  569. for (auto te : lines) {
  570. if (te) { h.emplace("Transfer-Encoding", te); }
  571. }
  572. return h;
  573. };
  574. // Sole coding, matched case-insensitively.
  575. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  576. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  577. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  578. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  579. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  580. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  581. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  582. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  583. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  584. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  585. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  586. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  587. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  588. // were received, into one list. Headers preserves that order, so the answer
  589. // is decided by the last coding of the last line and the order the lines
  590. // arrived in is significant.
  591. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  592. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  593. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  594. // The split can fall anywhere in the list.
  595. EXPECT_TRUE(
  596. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  597. EXPECT_FALSE(
  598. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  599. // A trailing line naming no coding leaves the list ending in nothing, so it
  600. // must not inherit the chunked from the line before it.
  601. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  602. }
  603. // Forward declarations (see the base64_encode note below).
  604. namespace httplib {
  605. namespace detail {
  606. bool parse_status_line(const char *line, std::string &version, int &status,
  607. std::string &reason);
  608. std::string file_extension(const std::string &path);
  609. std::string
  610. find_content_type(const std::string &path,
  611. const std::map<std::string, std::string> &user_data,
  612. const std::string &default_content_type);
  613. bool can_compress_content_type(const std::string &content_type);
  614. bool is_prohibited_header_name(const std::string &name);
  615. bool is_valid_path(const std::string &path);
  616. #ifdef CPPHTTPLIB_SSL_ENABLED
  617. bool match_hostname(const std::string &pattern, const std::string &hostname);
  618. #endif
  619. } // namespace detail
  620. } // namespace httplib
  621. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  622. struct {
  623. const char *line;
  624. const char *version;
  625. int status;
  626. const char *reason;
  627. } cases[] = {
  628. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  629. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  630. // The reason phrase may be empty, or left out along with its space.
  631. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  632. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  633. };
  634. for (const auto &c : cases) {
  635. std::string version;
  636. int status = 0;
  637. std::string reason = "unset";
  638. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  639. << c.line;
  640. EXPECT_EQ(c.version, version);
  641. EXPECT_EQ(c.status, status);
  642. EXPECT_EQ(c.reason, reason);
  643. }
  644. }
  645. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  646. const char *lines[] = {
  647. "HTTP/2 200 OK\r\n",
  648. "HTTP/1.2 200 OK\r\n",
  649. "HTTP/1.1 20 OK\r\n",
  650. "HTTP/1.1 2000 OK\r\n",
  651. "HTTP/1.1 2x0 OK\r\n",
  652. "HTTP/1.1 200 OK\r\n",
  653. "HTTP/1.1 200OK\r\n",
  654. "HTTP/1.1 200 O\rK\r\n",
  655. "HTTP/1.1 200 OK",
  656. "HTTP/1.1 200 OK\r\nX",
  657. "",
  658. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  659. "HTTP/1.1 200 OK\n",
  660. #endif
  661. };
  662. for (auto line : lines) {
  663. std::string version;
  664. int status = 0;
  665. std::string reason;
  666. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  667. << line;
  668. }
  669. }
  670. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  671. // Long enough to overflow the stack when matched with std::regex.
  672. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  673. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  674. std::string version;
  675. int status = 0;
  676. std::string reason;
  677. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  678. EXPECT_EQ(200, status);
  679. EXPECT_EQ(long_reason, reason);
  680. }
  681. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  682. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  683. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  684. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  685. EXPECT_EQ("", detail::file_extension("noext"));
  686. EXPECT_EQ("", detail::file_extension("a."));
  687. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  688. EXPECT_EQ("", detail::file_extension("a.b-c"));
  689. // Long enough to overflow the stack when matched with std::regex.
  690. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  691. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  692. }
  693. #ifdef CPPHTTPLIB_SSL_ENABLED
  694. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  695. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  696. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  697. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  698. // A wildcard needs two labels after it, in the leftmost label only
  699. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  700. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  701. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  702. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  703. EXPECT_FALSE(
  704. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  705. // No name may have an empty label
  706. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  707. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  708. }
  709. #endif
  710. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  711. detail::case_ignore::hash hash;
  712. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  713. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  714. // Long enough to overflow the stack if hashed one call per character.
  715. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  716. }
  717. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  718. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  719. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  720. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  721. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  722. // Same 26-bit hash as html, svg and js.
  723. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  724. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  725. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  726. }
  727. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  728. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  729. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  730. }
  731. }
  732. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  733. // name anywhere else.
  734. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  735. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  736. #ifdef _WIN32
  737. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  738. #else
  739. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  740. #endif
  741. }
  742. }
  743. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  744. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  745. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  746. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  747. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  748. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  749. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  750. // Same 26-bit hash as application/json.
  751. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  752. }
  753. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  754. Request req;
  755. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  756. EXPECT_TRUE(req.is_multipart_form_data());
  757. std::string boundary;
  758. EXPECT_TRUE(detail::parse_multipart_boundary(
  759. req.get_header_value("Content-Type"), boundary));
  760. EXPECT_EQ("x", boundary);
  761. }
  762. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  763. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  764. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  765. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  766. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  767. // Same 26-bit hash as REMOTE_ADDR.
  768. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  769. }
  770. // Forward declaration: in split builds split.py strips `inline` and moves the
  771. // definition into httplib.cc, so detail::base64_encode is not visible from the
  772. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  773. // in both header-only and split builds.
  774. namespace httplib {
  775. namespace detail {
  776. std::string base64_encode(const std::string &in);
  777. } // namespace detail
  778. } // namespace httplib
  779. TEST(Base64EncodeTest, KnownAnswers) {
  780. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  781. // where the accumulator's top bit is already set before the next shift.
  782. EXPECT_EQ("", detail::base64_encode(""));
  783. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  784. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  785. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  786. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  787. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  788. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  789. // High bytes keep the top bit set across several rounds.
  790. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  791. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  792. }
  793. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  794. string unescapedCharacters = "-_.!~*'()";
  795. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  796. }
  797. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  798. string reservedCharacters = ";,/?:@&=+$";
  799. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  800. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  801. }
  802. TEST(ClientQueryOrder, PreserveOrder) {
  803. // This test reproduces Issue #2259: client may reorder query parameters
  804. // when sending a GET request. The expected behavior is that the client
  805. // preserves the original query string order when the caller supplied it
  806. // as part of the path.
  807. Server svr;
  808. svr.Get("/", [&](const Request &req, Response &res) {
  809. // Echo back the raw target so the test can assert ordering
  810. res.set_content(req.target, "text/plain");
  811. });
  812. std::thread t{[&] { svr.listen(HOST, PORT); }};
  813. auto se = detail::scope_exit([&] {
  814. svr.stop();
  815. t.join();
  816. ASSERT_FALSE(svr.is_running());
  817. });
  818. svr.wait_until_ready();
  819. Client cli(HOST, PORT);
  820. ASSERT_TRUE(cli.is_valid());
  821. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  822. auto res = cli.Get(original);
  823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  824. // Expect the echoed target to exactly match the original path (order
  825. // preserved)
  826. EXPECT_EQ(res->body, original);
  827. }
  828. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  829. string chineseCharacters = U8("中国語");
  830. string russianCharacters = U8("дом");
  831. string brazilianCharacters = U8("óculos");
  832. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  833. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  834. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  835. "%D0%B4%D0%BE%D0%BC");
  836. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  837. }
  838. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  839. string unescapedCharacters = "-_.!~*'()";
  840. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  841. }
  842. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  843. string reservedCharacters = ";,/?:@&=+$";
  844. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  845. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  846. }
  847. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  848. string chineseCharacters = U8("中国語");
  849. string russianCharacters = U8("дом");
  850. string brazilianCharacters = U8("óculos");
  851. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  852. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  853. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  854. "%D0%B4%D0%BE%D0%BC");
  855. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  856. }
  857. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  858. // Issue #2082 use case: encoding path component with ampersand
  859. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  860. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  861. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  862. }
  863. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  864. string unescapedCharacters = "-_.!~*'()";
  865. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  866. }
  867. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  868. string reservedCharacters = ";,/?:@&=+$#";
  869. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  870. }
  871. TEST(EncodeUriTest, TestUTF8Characters) {
  872. string chineseCharacters = U8("中国語");
  873. string russianCharacters = U8("дом");
  874. string brazilianCharacters = U8("óculos");
  875. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  876. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  877. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  878. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  879. }
  880. TEST(EncodeUriTest, TestCompleteUri) {
  881. string uri =
  882. "https://example.com/path/to/resource?query=value&param=test#fragment";
  883. EXPECT_EQ(
  884. httplib::encode_uri(uri),
  885. "https://example.com/path/to/resource?query=value&param=test#fragment");
  886. }
  887. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  888. string uri =
  889. "https://example.com/path with spaces/file name.html?q=hello world";
  890. EXPECT_EQ(httplib::encode_uri(uri),
  891. "https://example.com/path%20with%20spaces/"
  892. "file%20name.html?q=hello%20world");
  893. }
  894. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  895. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  896. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  897. }
  898. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  899. string unescapedCharacters = "-_.!~*'()";
  900. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  901. }
  902. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  903. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  904. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  905. string encodedBrazilian = "%C3%B3culos";
  906. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  907. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  908. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  909. }
  910. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  911. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  912. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  913. "Piri Tommy Villiers - on & on");
  914. }
  915. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  916. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  917. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  918. }
  919. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  920. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  921. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  922. }
  923. TEST(DecodeUriTest, TestUTF8Characters) {
  924. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  925. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  926. string encodedBrazilian = "%C3%B3culos";
  927. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  928. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  929. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  930. }
  931. TEST(DecodeUriTest, TestCompleteUri) {
  932. string encodedUri = "https://example.com/path%20with%20spaces/"
  933. "file%20name.html?q=hello%20world";
  934. EXPECT_EQ(
  935. httplib::decode_uri(encodedUri),
  936. "https://example.com/path with spaces/file name.html?q=hello world");
  937. }
  938. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  939. string original =
  940. "https://example.com/path with spaces/file name.html?q=hello world";
  941. string encoded = httplib::encode_uri(original);
  942. string decoded = httplib::decode_uri(encoded);
  943. EXPECT_EQ(decoded, original);
  944. }
  945. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  946. // decode_uri is the inverse of encode_uri: an escaped reserved character
  947. // stays encoded so it is not promoted into a real delimiter, while
  948. // non-reserved escapes still decode (like JS decodeURI).
  949. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  950. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  951. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  952. "%3F%3A%40%26%3D%2B%24%2C%3B");
  953. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  954. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  955. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  956. "http://example.com/a%2Fb");
  957. // decode_uri_component still decodes the reserved character.
  958. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  959. }
  960. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  961. string original = "Piri Tommy Villiers - on & on";
  962. string encoded = httplib::encode_uri_component(original);
  963. string decoded = httplib::decode_uri_component(encoded);
  964. EXPECT_EQ(decoded, original);
  965. }
  966. TEST(TrimTests, TrimStringTests) {
  967. EXPECT_EQ("abc", detail::trim_copy("abc"));
  968. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  969. EXPECT_TRUE(detail::trim_copy("").empty());
  970. }
  971. TEST(AsciiTest, LocaleIndependentClassification) {
  972. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  973. // which consult the global C locale: std::isalnum(0xC5) can return true
  974. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  975. // helpers must classify every byte by the ASCII grammar alone.
  976. for (int i = 0; i < 256; i++) {
  977. auto c = static_cast<char>(i);
  978. auto is_digit = i >= '0' && i <= '9';
  979. auto is_upper = i >= 'A' && i <= 'Z';
  980. auto is_lower = i >= 'a' && i <= 'z';
  981. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  982. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  983. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  984. << "byte " << i;
  985. }
  986. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  987. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  988. // Non-ASCII bytes must be percent-encoded, never passed through as
  989. // alphanumeric.
  990. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  991. }
  992. TEST(FromCharsTest, Double) {
  993. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  994. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  995. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  996. auto parse = [](const std::string &s, double &v) {
  997. return detail::from_chars(s.data(), s.data() + s.size(), v);
  998. };
  999. double v = -1.0;
  1000. // Representative quality values.
  1001. EXPECT_EQ(parse("0", v).ec, std::errc{});
  1002. EXPECT_DOUBLE_EQ(v, 0.0);
  1003. EXPECT_EQ(parse("1", v).ec, std::errc{});
  1004. EXPECT_DOUBLE_EQ(v, 1.0);
  1005. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  1006. EXPECT_DOUBLE_EQ(v, 0.8);
  1007. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  1008. EXPECT_DOUBLE_EQ(v, 0.001);
  1009. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  1010. EXPECT_DOUBLE_EQ(v, 1.0);
  1011. // A missing integer or fractional part is tolerated.
  1012. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  1013. EXPECT_DOUBLE_EQ(v, 0.5);
  1014. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  1015. EXPECT_DOUBLE_EQ(v, 5.0);
  1016. // Values outside [0, 1] still parse; the caller range-checks them.
  1017. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  1018. EXPECT_DOUBLE_EQ(v, 123.456);
  1019. // Stops at the first byte that is not part of the number and reports where.
  1020. std::string trailing = "0.9, text/html";
  1021. auto r = parse(trailing, v);
  1022. EXPECT_EQ(r.ec, std::errc{});
  1023. EXPECT_DOUBLE_EQ(v, 0.9);
  1024. EXPECT_EQ(*r.ptr, ',');
  1025. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  1026. // outright, and an 'e'/'E' simply ends the number.
  1027. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  1028. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  1029. std::string exp_input = "1.5e3";
  1030. r = parse(exp_input, v);
  1031. EXPECT_EQ(r.ec, std::errc{});
  1032. EXPECT_DOUBLE_EQ(v, 1.5);
  1033. EXPECT_EQ(*r.ptr, 'e');
  1034. // Invalid inputs.
  1035. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1036. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1037. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1038. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1039. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1040. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1041. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1042. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1043. std::errc{});
  1044. EXPECT_DOUBLE_EQ(v, 0.0);
  1045. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1046. std::errc{});
  1047. EXPECT_GE(v, 0.0);
  1048. EXPECT_LE(v, 1.0);
  1049. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1050. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1051. }
  1052. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1053. // Simple case without quality values
  1054. std::vector<std::string> result1;
  1055. EXPECT_TRUE(detail::parse_accept_header(
  1056. "text/html,application/json,text/plain", result1));
  1057. EXPECT_EQ(result1.size(), 3U);
  1058. EXPECT_EQ(result1[0], "text/html");
  1059. EXPECT_EQ(result1[1], "application/json");
  1060. EXPECT_EQ(result1[2], "text/plain");
  1061. // With quality values
  1062. std::vector<std::string> result2;
  1063. EXPECT_TRUE(detail::parse_accept_header(
  1064. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1065. EXPECT_EQ(result2.size(), 3U);
  1066. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1067. EXPECT_EQ(result2[1], "text/html");
  1068. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1069. }
  1070. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1071. // Mixed with and without quality values
  1072. std::vector<std::string> result;
  1073. EXPECT_TRUE(detail::parse_accept_header(
  1074. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1075. EXPECT_EQ(result.size(), 3U);
  1076. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1077. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1078. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1079. }
  1080. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1081. // Empty header
  1082. std::vector<std::string> empty_result;
  1083. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1084. EXPECT_TRUE(empty_result.empty());
  1085. // Single type
  1086. std::vector<std::string> single_result;
  1087. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1088. EXPECT_EQ(single_result.size(), 1U);
  1089. EXPECT_EQ(single_result[0], "application/json");
  1090. // Wildcard types
  1091. std::vector<std::string> wildcard_result;
  1092. EXPECT_TRUE(detail::parse_accept_header(
  1093. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1094. EXPECT_EQ(wildcard_result.size(), 3U);
  1095. EXPECT_EQ(wildcard_result[0], "application/json");
  1096. EXPECT_EQ(wildcard_result[1], "text/*");
  1097. EXPECT_EQ(wildcard_result[2], "*/*");
  1098. }
  1099. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1100. // Common browser Accept header
  1101. std::vector<std::string> browser_result;
  1102. EXPECT_TRUE(
  1103. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1104. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1105. browser_result));
  1106. EXPECT_EQ(browser_result.size(), 6U);
  1107. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1108. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1109. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1110. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1111. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1112. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1113. // API client header
  1114. std::vector<std::string> api_result;
  1115. EXPECT_TRUE(detail::parse_accept_header(
  1116. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1117. api_result));
  1118. EXPECT_EQ(api_result.size(), 3U);
  1119. EXPECT_EQ(api_result[0], "application/json");
  1120. EXPECT_EQ(api_result[1], "application/xml");
  1121. EXPECT_EQ(api_result[2], "text/plain");
  1122. }
  1123. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1124. // Quality value with 3 decimal places
  1125. std::vector<std::string> decimal_result;
  1126. EXPECT_TRUE(detail::parse_accept_header(
  1127. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1128. EXPECT_EQ(decimal_result.size(), 2U);
  1129. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1130. EXPECT_EQ(decimal_result[1], "text/html");
  1131. // Zero quality (should still be included but with lowest priority)
  1132. std::vector<std::string> zero_q_result;
  1133. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1134. zero_q_result));
  1135. EXPECT_EQ(zero_q_result.size(), 2U);
  1136. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1137. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1138. // No spaces around commas
  1139. std::vector<std::string> no_space_result;
  1140. EXPECT_TRUE(detail::parse_accept_header(
  1141. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1142. no_space_result));
  1143. EXPECT_EQ(no_space_result.size(), 3U);
  1144. EXPECT_EQ(no_space_result[0], "text/html");
  1145. EXPECT_EQ(no_space_result[1], "application/json");
  1146. EXPECT_EQ(no_space_result[2], "text/plain");
  1147. }
  1148. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1149. // Quality values always use '.' as the decimal separator, so parsing must
  1150. // not depend on the process locale. An embedding application may have
  1151. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1152. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1153. std::string saved = cur ? cur : "C";
  1154. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1155. "fr_FR.UTF-8"};
  1156. bool switched = false;
  1157. for (const auto loc : comma_locales) {
  1158. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1159. std::localeconv()->decimal_point[0] == ',') {
  1160. switched = true;
  1161. break;
  1162. }
  1163. }
  1164. if (!switched) {
  1165. std::setlocale(LC_NUMERIC, saved.c_str());
  1166. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1167. }
  1168. // The higher-weighted type appears later in the list, so a correct parse
  1169. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1170. // sensitive parse reads both weights as 0 and leaves the original order.
  1171. std::vector<std::string> result;
  1172. EXPECT_TRUE(detail::parse_accept_header(
  1173. "application/json;q=0.1,text/html;q=0.9", result));
  1174. ASSERT_EQ(result.size(), 2U);
  1175. EXPECT_EQ(result[0], "text/html");
  1176. EXPECT_EQ(result[1], "application/json");
  1177. std::setlocale(LC_NUMERIC, saved.c_str());
  1178. }
  1179. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1180. std::vector<std::string> result;
  1181. // Invalid quality value (> 1.0)
  1182. EXPECT_FALSE(
  1183. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1184. // Invalid quality value (< 0.0)
  1185. EXPECT_FALSE(
  1186. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1187. // Invalid quality value (not a number)
  1188. EXPECT_FALSE(detail::parse_accept_header(
  1189. "text/html;q=invalid,application/json", result));
  1190. // A valid numeric prefix does not make the entire quality value valid.
  1191. EXPECT_FALSE(detail::parse_accept_header(
  1192. "text/html;q=0.5junk,application/json", result));
  1193. // Empty quality value
  1194. EXPECT_FALSE(
  1195. detail::parse_accept_header("text/html;q=,application/json", result));
  1196. // Invalid media type format (no slash and not wildcard)
  1197. EXPECT_FALSE(
  1198. detail::parse_accept_header("invalidtype,application/json", result));
  1199. // Valid cases should still work
  1200. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1201. EXPECT_EQ(result.size(), 1U);
  1202. EXPECT_EQ(result[0], "*/*");
  1203. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1204. EXPECT_EQ(result.size(), 1U);
  1205. EXPECT_EQ(result[0], "*");
  1206. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1207. EXPECT_EQ(result.size(), 1U);
  1208. EXPECT_EQ(result[0], "text/*");
  1209. }
  1210. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1211. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1212. // and must not be answered with 400 Bad Request.
  1213. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1214. struct {
  1215. const char *value;
  1216. std::vector<std::string> expected;
  1217. } cases[] = {
  1218. {",application/json", {"application/json"}},
  1219. {"text/html,", {"text/html"}},
  1220. {"text/html,,*/*", {"text/html", "*/*"}},
  1221. // An empty element may be spelled with whitespace in it
  1222. {"text/html, , application/json", {"text/html", "application/json"}},
  1223. // Nothing but empty elements is an empty list, which means the same
  1224. // thing as no Accept header at all
  1225. {",,,", {}},
  1226. // Quality values still apply across ignored empty elements
  1227. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1228. };
  1229. for (const auto &c : cases) {
  1230. std::vector<std::string> result;
  1231. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1232. << "value: " << c.value;
  1233. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1234. }
  1235. // An invalid entry is still rejected when empty elements surround it
  1236. std::vector<std::string> result;
  1237. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1238. }
  1239. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1240. // or ';' inside one does not end the list element or the parameter. Section
  1241. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1242. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1243. struct {
  1244. const char *value;
  1245. std::vector<std::string> expected;
  1246. } cases[] = {
  1247. {"text/html;profile=\"a,b\",application/json",
  1248. {"text/html", "application/json"}},
  1249. // A "q=" inside a quoted value is not the weight
  1250. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1251. {"text/html", "application/json"}},
  1252. // The weight after a quoted value still applies
  1253. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1254. {"application/json", "text/html"}},
  1255. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1256. {"application/json", "text/html"}},
  1257. {"text/html;profile=\"a\\\"b\",application/json",
  1258. {"text/html", "application/json"}},
  1259. // An escaped backslash does not escape the '"' after it
  1260. {"text/html;profile=\"a\\\\\",application/json",
  1261. {"text/html", "application/json"}},
  1262. };
  1263. for (const auto &c : cases) {
  1264. std::vector<std::string> result;
  1265. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1266. << "value: " << c.value;
  1267. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1268. }
  1269. }
  1270. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1271. Server svr;
  1272. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1273. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1274. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1275. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1276. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1277. res.set_content("ok", "text/plain");
  1278. });
  1279. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1280. EXPECT_TRUE(false);
  1281. res.set_content("bad request", "text/plain");
  1282. });
  1283. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1284. auto se = detail::scope_exit([&] {
  1285. svr.stop();
  1286. listen_thread.join();
  1287. ASSERT_FALSE(svr.is_running());
  1288. });
  1289. svr.wait_until_ready();
  1290. Client cli("localhost", PORT);
  1291. {
  1292. auto res = cli.Get(
  1293. "/accept_ok",
  1294. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1296. EXPECT_EQ(StatusCode::OK_200, res->status);
  1297. }
  1298. {
  1299. auto res = cli.Get("/accept_bad_request",
  1300. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1302. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1303. }
  1304. }
  1305. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1306. Server svr;
  1307. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1308. res.set_content("ok", "text/plain");
  1309. });
  1310. std::atomic<int> start_count{0};
  1311. std::atomic<bool> running_when_called{false};
  1312. svr.set_start_handler([&]() {
  1313. running_when_called = svr.is_running();
  1314. start_count++;
  1315. });
  1316. auto port = svr.bind_to_any_port(HOST);
  1317. std::thread t([&]() { svr.listen_after_bind(); });
  1318. auto se = detail::scope_exit([&] {
  1319. svr.stop();
  1320. t.join();
  1321. ASSERT_FALSE(svr.is_running());
  1322. });
  1323. svr.wait_until_ready();
  1324. // A successful request proves the accept loop is running, which the start
  1325. // handler precedes; so by now the handler must have run exactly once.
  1326. Client cli(HOST, port);
  1327. cli.set_connection_timeout(std::chrono::seconds(5));
  1328. auto res = cli.Get("/");
  1329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1330. EXPECT_EQ(StatusCode::OK_200, res->status);
  1331. EXPECT_EQ(1, start_count.load());
  1332. EXPECT_TRUE(running_when_called.load());
  1333. }
  1334. TEST(DivideTest, DivideStringTests) {
  1335. auto divide = [](const std::string &str, char d) {
  1336. std::string lhs;
  1337. std::string rhs;
  1338. detail::divide(str, d,
  1339. [&](const char *lhs_data, std::size_t lhs_size,
  1340. const char *rhs_data, std::size_t rhs_size) {
  1341. lhs.assign(lhs_data, lhs_size);
  1342. rhs.assign(rhs_data, rhs_size);
  1343. });
  1344. return std::make_pair(std::move(lhs), std::move(rhs));
  1345. };
  1346. {
  1347. const auto res = divide("", '=');
  1348. EXPECT_EQ(res.first, "");
  1349. EXPECT_EQ(res.second, "");
  1350. }
  1351. {
  1352. const auto res = divide("=", '=');
  1353. EXPECT_EQ(res.first, "");
  1354. EXPECT_EQ(res.second, "");
  1355. }
  1356. {
  1357. const auto res = divide(" ", '=');
  1358. EXPECT_EQ(res.first, " ");
  1359. EXPECT_EQ(res.second, "");
  1360. }
  1361. {
  1362. const auto res = divide("a", '=');
  1363. EXPECT_EQ(res.first, "a");
  1364. EXPECT_EQ(res.second, "");
  1365. }
  1366. {
  1367. const auto res = divide("a=", '=');
  1368. EXPECT_EQ(res.first, "a");
  1369. EXPECT_EQ(res.second, "");
  1370. }
  1371. {
  1372. const auto res = divide("=b", '=');
  1373. EXPECT_EQ(res.first, "");
  1374. EXPECT_EQ(res.second, "b");
  1375. }
  1376. {
  1377. const auto res = divide("a=b", '=');
  1378. EXPECT_EQ(res.first, "a");
  1379. EXPECT_EQ(res.second, "b");
  1380. }
  1381. {
  1382. const auto res = divide("a=b=", '=');
  1383. EXPECT_EQ(res.first, "a");
  1384. EXPECT_EQ(res.second, "b=");
  1385. }
  1386. {
  1387. const auto res = divide("a=b=c", '=');
  1388. EXPECT_EQ(res.first, "a");
  1389. EXPECT_EQ(res.second, "b=c");
  1390. }
  1391. }
  1392. TEST(SplitTest, ParseQueryString) {
  1393. string s = "key1=val1&key2=val2&key3=val3";
  1394. Params dic;
  1395. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1396. [&](const char *b, const char *e) {
  1397. string key, val;
  1398. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1399. if (key.empty()) {
  1400. key.assign(b2, e2);
  1401. } else {
  1402. val.assign(b2, e2);
  1403. }
  1404. });
  1405. dic.emplace(key, val);
  1406. });
  1407. EXPECT_EQ("val1", dic.find("key1")->second);
  1408. EXPECT_EQ("val2", dic.find("key2")->second);
  1409. EXPECT_EQ("val3", dic.find("key3")->second);
  1410. }
  1411. TEST(SplitTest, ParseInvalidQueryTests) {
  1412. {
  1413. string s = " ";
  1414. Params dict;
  1415. detail::parse_query_text(s, dict);
  1416. EXPECT_TRUE(dict.empty());
  1417. }
  1418. {
  1419. string s = " = =";
  1420. Params dict;
  1421. detail::parse_query_text(s, dict);
  1422. EXPECT_TRUE(dict.empty());
  1423. }
  1424. }
  1425. TEST(ParseQueryTest, ParseQueryString) {
  1426. {
  1427. std::string s = "key1=val1&key2=val2&key3=val3";
  1428. Params dic;
  1429. detail::parse_query_text(s, dic);
  1430. EXPECT_EQ("val1", dic.find("key1")->second);
  1431. EXPECT_EQ("val2", dic.find("key2")->second);
  1432. EXPECT_EQ("val3", dic.find("key3")->second);
  1433. }
  1434. {
  1435. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1436. Params dic;
  1437. detail::parse_query_text(s, dic);
  1438. EXPECT_EQ("", dic.find("key1")->second);
  1439. EXPECT_EQ("val1", dic.find("key2")->second);
  1440. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1441. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1442. }
  1443. }
  1444. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1445. Params dic;
  1446. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1447. dic.emplace("key1", "val1");
  1448. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1449. dic.emplace("key2", "val2");
  1450. dic.emplace("key3", "val3");
  1451. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1452. }
  1453. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1454. Params params;
  1455. params.emplace("a", "1");
  1456. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1457. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1458. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1459. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1460. // Long enough to overflow the stack when matched with std::regex.
  1461. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1462. EXPECT_EQ("/p?" + long_query + "&a=1",
  1463. append_query_params("/p?" + long_query, params));
  1464. }
  1465. // Joins every entry of a Headers or Params into "key=value " so a whole
  1466. // traversal can be compared in one assertion. Both are instantiations of the
  1467. // same insertion-ordered container, so one helper serves both.
  1468. template <typename Map> static std::string entries_to_string(const Map &m) {
  1469. std::string s;
  1470. for (const auto &entry : m) {
  1471. s += entry.first + "=" + entry.second + " ";
  1472. }
  1473. return s;
  1474. }
  1475. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1476. // Params used to be a std::multimap, which sorted by name and handed the
  1477. // caller's query back alphabetised. A client signing its query string could
  1478. // not reproduce the order it asked for.
  1479. Params dic;
  1480. dic.emplace("zulu", "1");
  1481. dic.emplace("alpha", "2");
  1482. dic.emplace("mike", "3");
  1483. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1484. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1485. }
  1486. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1487. Params dic;
  1488. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1489. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1490. }
  1491. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1492. Request req;
  1493. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1494. req.params);
  1495. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1496. EXPECT_EQ("first", req.get_param_value("tag"));
  1497. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1498. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1499. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1500. EXPECT_EQ("", req.get_param_value("tag", 3));
  1501. }
  1502. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1503. // Params shares its container with Headers, which matches field names
  1504. // case-insensitively. Parameter names must not pick that up.
  1505. Params dic;
  1506. dic.emplace("Key", "upper");
  1507. dic.emplace("key", "lower");
  1508. EXPECT_EQ(2U, dic.size());
  1509. EXPECT_EQ(1U, dic.count("Key"));
  1510. EXPECT_EQ(1U, dic.count("key"));
  1511. EXPECT_EQ("upper", dic.find("Key")->second);
  1512. EXPECT_EQ("lower", dic.find("key")->second);
  1513. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1514. }
  1515. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1516. Server svr;
  1517. std::string order;
  1518. svr.Get("/order", [&](const Request &req, Response &res) {
  1519. order = entries_to_string(req.params);
  1520. res.set_content("ok", "text/plain");
  1521. });
  1522. auto port = svr.bind_to_any_port(HOST);
  1523. thread t = thread([&] { svr.listen_after_bind(); });
  1524. auto se = detail::scope_exit([&] {
  1525. svr.stop();
  1526. t.join();
  1527. ASSERT_FALSE(svr.is_running());
  1528. });
  1529. svr.wait_until_ready();
  1530. Client cli(HOST, port);
  1531. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1532. ASSERT_TRUE(res);
  1533. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1534. }
  1535. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1536. Server svr;
  1537. std::string field_order, file_order;
  1538. svr.Post("/order", [&](const Request &req, Response &res) {
  1539. for (const auto &field : req.form.fields) {
  1540. field_order += field.first + "=" + field.second.content + " ";
  1541. }
  1542. for (const auto &file : req.form.files) {
  1543. file_order += file.first + "=" + file.second.filename + " ";
  1544. }
  1545. res.set_content("ok", "text/plain");
  1546. });
  1547. auto port = svr.bind_to_any_port(HOST);
  1548. thread t = thread([&] { svr.listen_after_bind(); });
  1549. auto se = detail::scope_exit([&] {
  1550. svr.stop();
  1551. t.join();
  1552. ASSERT_FALSE(svr.is_running());
  1553. });
  1554. svr.wait_until_ready();
  1555. UploadFormDataItems items = {
  1556. {"zulu", "1", "", ""},
  1557. {"alpha", "2", "", ""},
  1558. {"mike", "3", "", ""},
  1559. {"zebra", "z", "z.txt", "text/plain"},
  1560. {"apple", "a", "a.txt", "text/plain"},
  1561. };
  1562. Client cli(HOST, port);
  1563. auto res = cli.Post("/order", items);
  1564. ASSERT_TRUE(res);
  1565. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1566. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1567. }
  1568. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1569. Server svr;
  1570. std::vector<std::string> values;
  1571. std::string first, second, out_of_range, order;
  1572. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1573. values = req.form.get_fields("tag");
  1574. first = req.form.get_field("tag", 0);
  1575. second = req.form.get_field("tag", 1);
  1576. out_of_range = req.form.get_field("tag", 2);
  1577. for (const auto &field : req.form.fields) {
  1578. order += field.first + "=" + field.second.content + " ";
  1579. }
  1580. res.set_content("ok", "text/plain");
  1581. });
  1582. auto port = svr.bind_to_any_port(HOST);
  1583. thread t = thread([&] { svr.listen_after_bind(); });
  1584. auto se = detail::scope_exit([&] {
  1585. svr.stop();
  1586. t.join();
  1587. ASSERT_FALSE(svr.is_running());
  1588. });
  1589. svr.wait_until_ready();
  1590. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1591. // not adjacent in the container.
  1592. UploadFormDataItems items = {
  1593. {"tag", "first", "", ""},
  1594. {"other", "x", "", ""},
  1595. {"tag", "second", "", ""},
  1596. };
  1597. Client cli(HOST, port);
  1598. auto res = cli.Post("/repeated", items);
  1599. ASSERT_TRUE(res);
  1600. ASSERT_EQ(2U, values.size());
  1601. EXPECT_EQ("first", values[0]);
  1602. EXPECT_EQ("second", values[1]);
  1603. EXPECT_EQ("first", first);
  1604. EXPECT_EQ("second", second);
  1605. // std::multimap already kept entries sharing a name in insertion order, so
  1606. // everything above passes without this change too. The whole traversal is
  1607. // what tells the two apart: sorting by name would hoist "other" to the front
  1608. // and the two "tag" parts would end up adjacent.
  1609. EXPECT_EQ("tag=first other=x tag=second ", order);
  1610. // Advancing past the last entry of a name used to run off the container;
  1611. // the container's saturating increment makes it return the default instead.
  1612. EXPECT_EQ("", out_of_range);
  1613. }
  1614. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1615. Server svr;
  1616. std::string file_names;
  1617. svr.Post("/upload", [&](const Request &req, Response &res) {
  1618. for (const auto &file : req.form.files) {
  1619. file_names += file.first + "|" + file.second.filename + " ";
  1620. }
  1621. res.set_content("ok", "text/plain");
  1622. });
  1623. auto port = svr.bind_to_any_port(HOST);
  1624. thread t = thread([&] { svr.listen_after_bind(); });
  1625. auto se = detail::scope_exit([&] {
  1626. svr.stop();
  1627. t.join();
  1628. ASSERT_FALSE(svr.is_running());
  1629. });
  1630. svr.wait_until_ready();
  1631. // A trailing backslash would otherwise escape the closing quote.
  1632. UploadFormDataItems items = {
  1633. {"dir\\", "x", "a.txt", "text/plain"},
  1634. {"b", "y", "a\\\\b.txt", "text/plain"},
  1635. };
  1636. Client cli(HOST, port);
  1637. auto res = cli.Post("/upload", items);
  1638. ASSERT_TRUE(res);
  1639. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1640. }
  1641. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1642. // Server::read_content() keeps a FormFields::iterator alive across the
  1643. // content callbacks that fill the part it points at. The container is
  1644. // vector-backed, so a later emplace can reallocate and invalidate an older
  1645. // iterator; 64 parts grow the vector through seven reallocations, which
  1646. // checks that every part's content still lands in its own entry.
  1647. const size_t part_count = 64;
  1648. // One formula for both the parts sent and the values expected back, so the
  1649. // two cannot drift apart.
  1650. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1651. auto content_of = [](size_t i) {
  1652. return std::string(64, static_cast<char>('a' + (i % 26)));
  1653. };
  1654. Server svr;
  1655. std::vector<std::pair<std::string, std::string>> received;
  1656. svr.Post("/many", [&](const Request &req, Response &res) {
  1657. for (const auto &field : req.form.fields) {
  1658. received.emplace_back(field.first, field.second.content);
  1659. }
  1660. res.set_content("ok", "text/plain");
  1661. });
  1662. auto port = svr.bind_to_any_port(HOST);
  1663. thread t = thread([&] { svr.listen_after_bind(); });
  1664. auto se = detail::scope_exit([&] {
  1665. svr.stop();
  1666. t.join();
  1667. ASSERT_FALSE(svr.is_running());
  1668. });
  1669. svr.wait_until_ready();
  1670. UploadFormDataItems items;
  1671. for (size_t i = 0; i < part_count; i++) {
  1672. items.push_back({name_of(i), content_of(i), "", ""});
  1673. }
  1674. Client cli(HOST, port);
  1675. auto res = cli.Post("/many", items);
  1676. ASSERT_TRUE(res);
  1677. ASSERT_EQ(part_count, received.size());
  1678. for (size_t i = 0; i < part_count; i++) {
  1679. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1680. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1681. }
  1682. }
  1683. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1684. string content_type = "multipart/form-data; boundary=something";
  1685. string boundary;
  1686. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1687. EXPECT_TRUE(ret);
  1688. EXPECT_EQ(boundary, "something");
  1689. }
  1690. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1691. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1692. string boundary;
  1693. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1694. EXPECT_TRUE(ret);
  1695. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1696. }
  1697. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1698. string content_type =
  1699. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1700. string boundary;
  1701. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1702. EXPECT_TRUE(ret);
  1703. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1704. }
  1705. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1706. string content_type =
  1707. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1708. string boundary;
  1709. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1710. EXPECT_TRUE(ret);
  1711. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1712. }
  1713. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1714. const string boundary(70, 'a');
  1715. string content_type = "multipart/form-data; boundary=" + boundary;
  1716. string parsed;
  1717. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1718. EXPECT_TRUE(ret);
  1719. EXPECT_EQ(parsed, boundary);
  1720. }
  1721. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1722. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1723. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1724. string parsed;
  1725. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1726. EXPECT_FALSE(ret);
  1727. }
  1728. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1729. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1730. // is 72 characters on the wire and still valid.
  1731. const string boundary(70, 'a');
  1732. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1733. string parsed;
  1734. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1735. EXPECT_EQ(parsed, boundary);
  1736. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1737. parsed.clear();
  1738. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1739. }
  1740. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1741. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1742. // The parameter parser must not treat that '=' as the key/value separator.
  1743. string content_type =
  1744. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1745. "charset=UTF-8";
  1746. string parsed;
  1747. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1748. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1749. }
  1750. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1751. // A ';' inside the quoted-string is part of the value, not a parameter
  1752. // separator, so it must not truncate the boundary.
  1753. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1754. string parsed;
  1755. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1756. EXPECT_EQ(parsed, "a;b");
  1757. }
  1758. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1759. string parsed;
  1760. EXPECT_TRUE(detail::parse_multipart_boundary(
  1761. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1762. EXPECT_EQ("a\\b", parsed);
  1763. EXPECT_TRUE(detail::parse_multipart_boundary(
  1764. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1765. EXPECT_EQ("a\"b", parsed);
  1766. }
  1767. TEST(ParseDispositionParamsTest, QuotedValues) {
  1768. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1769. // ';' and '=' are ordinary characters inside one.
  1770. struct {
  1771. const char *value;
  1772. std::vector<std::pair<const char *, const char *>> expected;
  1773. } cases[] = {
  1774. {"name=\"file1\"; filename=\"a.txt\"",
  1775. {{"name", "file1"}, {"filename", "a.txt"}}},
  1776. // Whitespace around '=' and ';' is still trimmed
  1777. {"name=\"file2\" ;filename = \"a.html\"",
  1778. {{"name", "file2"}, {"filename", "a.html"}}},
  1779. // '=' inside the value used to leave only the text after the last one
  1780. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1781. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1782. {"name=\"x=y\"", {{"name", "x=y"}}},
  1783. // ';' inside the value used to truncate the pair and leave a bogus one
  1784. {"name=\"file3\"; filename=\"a;b.txt\"",
  1785. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1786. // An unquoted value keeps working, and so does filename*
  1787. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1788. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1789. // A parameter with no key is dropped rather than turned into one whose
  1790. // key is the value
  1791. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1792. // An escaped quote does not end the value
  1793. {"name=\"a\\\"; filename=evil.php\"",
  1794. {{"name", "a\"; filename=evil.php"}}},
  1795. // Other backslashes, as in a Windows path, are kept
  1796. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1797. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1798. };
  1799. for (const auto &c : cases) {
  1800. Params params;
  1801. detail::parse_disposition_params(c.value, params);
  1802. for (const auto &kv : c.expected) {
  1803. auto it = params.find(kv.first);
  1804. ASSERT_NE(it, params.end())
  1805. << "value: " << c.value << ", key: " << kv.first;
  1806. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1807. }
  1808. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1809. }
  1810. }
  1811. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1812. Server svr;
  1813. std::string filename;
  1814. std::string content;
  1815. svr.Post("/upload", [&](const Request &req, Response &) {
  1816. const auto &file = req.form.get_file("file");
  1817. filename = file.filename;
  1818. content = file.content;
  1819. });
  1820. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1821. auto se = detail::scope_exit([&] {
  1822. svr.stop();
  1823. thread.join();
  1824. ASSERT_FALSE(svr.is_running());
  1825. });
  1826. svr.wait_until_ready();
  1827. std::string body = "--B\r\n"
  1828. "Content-Disposition: form-data; name=\"file\"; "
  1829. "filename=\"a.txt\"\r\n"
  1830. "Content-Type: text/plain\r\n"
  1831. "\r\n"
  1832. "hello\r\n"
  1833. "--B--\r\n";
  1834. Client cli(HOST, PORT);
  1835. auto res = cli.Post(
  1836. "/upload",
  1837. [&](size_t offset, DataSink &sink) {
  1838. if (offset < body.size()) {
  1839. sink.write(&body[offset], 1);
  1840. } else {
  1841. sink.done();
  1842. }
  1843. return true;
  1844. },
  1845. "multipart/form-data; boundary=B");
  1846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1847. EXPECT_EQ(StatusCode::OK_200, res->status);
  1848. EXPECT_EQ("a.txt", filename);
  1849. EXPECT_EQ("hello", content);
  1850. }
  1851. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1852. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1853. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1854. Server svr;
  1855. std::string field_value, file_name, file_filename;
  1856. bool has_field = false, has_file = false;
  1857. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1858. has_field = req.form.has_field("x=y");
  1859. field_value = req.form.get_field("x=y");
  1860. has_file = req.form.has_file("file1");
  1861. const auto &file = req.form.get_file("file1");
  1862. file_name = file.name;
  1863. file_filename = file.filename;
  1864. res.set_content("ok", "text/plain");
  1865. });
  1866. auto port = svr.bind_to_any_port(HOST);
  1867. thread t = thread([&] { svr.listen_after_bind(); });
  1868. auto se = detail::scope_exit([&] {
  1869. svr.stop();
  1870. t.join();
  1871. ASSERT_FALSE(svr.is_running());
  1872. });
  1873. svr.wait_until_ready();
  1874. UploadFormDataItems items = {
  1875. {"x=y", "field-value", "", ""},
  1876. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1877. };
  1878. Client cli(HOST, port);
  1879. auto res = cli.Post("/quoted", items);
  1880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1881. ASSERT_EQ(StatusCode::OK_200, res->status);
  1882. EXPECT_TRUE(has_field);
  1883. EXPECT_EQ("field-value", field_value);
  1884. EXPECT_TRUE(has_file);
  1885. EXPECT_EQ("file1", file_name);
  1886. EXPECT_EQ("a;b=report.pdf", file_filename);
  1887. }
  1888. TEST(GetHeaderValueTest, DefaultValue) {
  1889. Headers headers = {{"Dummy", "Dummy"}};
  1890. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1891. EXPECT_STREQ("text/plain", val);
  1892. }
  1893. TEST(GetHeaderValueTest, DefaultValueInt) {
  1894. Headers headers = {{"Dummy", "Dummy"}};
  1895. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1896. EXPECT_EQ(100ull, val);
  1897. }
  1898. TEST(GetHeaderValueTest, RegularValue) {
  1899. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1900. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1901. EXPECT_STREQ("text/html", val);
  1902. }
  1903. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1904. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1905. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1906. EXPECT_STREQ("text/html", val);
  1907. }
  1908. TEST(GetHeaderValueTest, SetContent) {
  1909. Response res;
  1910. res.set_content("html", "text/html");
  1911. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1912. res.set_content("text", "text/plain");
  1913. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1914. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1915. }
  1916. TEST(GetHeaderValueTest, RegularValueInt) {
  1917. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1918. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1919. EXPECT_EQ(100ull, val);
  1920. }
  1921. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1922. Headers headers = {{"Content-Length", "x"}};
  1923. auto is_invalid_value = false;
  1924. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1925. is_invalid_value);
  1926. EXPECT_EQ(0ull, val);
  1927. EXPECT_TRUE(is_invalid_value);
  1928. }
  1929. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1930. // An all-digit value that overflows size_t must be reported as invalid, not
  1931. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1932. // a large length to a small one on 32-bit builds, leaving the framing length
  1933. // wrong while is_invalid_value stayed false.
  1934. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1935. auto is_invalid_value = false;
  1936. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1937. is_invalid_value);
  1938. EXPECT_TRUE(is_invalid_value);
  1939. // A well-formed length is unaffected.
  1940. Headers ok = {{"Content-Length", "1234"}};
  1941. is_invalid_value = false;
  1942. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1943. is_invalid_value);
  1944. EXPECT_EQ(1234ull, val);
  1945. EXPECT_FALSE(is_invalid_value);
  1946. }
  1947. TEST(GetHeaderValueTest, Range) {
  1948. {
  1949. Headers headers = {make_range_header({{1, -1}})};
  1950. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1951. EXPECT_STREQ("bytes=1-", val);
  1952. }
  1953. {
  1954. Headers headers = {make_range_header({{-1, 1}})};
  1955. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1956. EXPECT_STREQ("bytes=-1", val);
  1957. }
  1958. {
  1959. Headers headers = {make_range_header({{1, 10}})};
  1960. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1961. EXPECT_STREQ("bytes=1-10", val);
  1962. }
  1963. {
  1964. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1965. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1966. EXPECT_STREQ("bytes=1-10, 100-", val);
  1967. }
  1968. {
  1969. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1970. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1971. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1972. }
  1973. {
  1974. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1975. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1976. EXPECT_STREQ("bytes=0-0, -1", val);
  1977. }
  1978. }
  1979. TEST(BearerTokenAuthTest, SchemeValidation) {
  1980. // A value shorter than "Bearer " must not throw from the fixed-length
  1981. // substr, and a non-Bearer scheme must not be reported as a token.
  1982. struct {
  1983. const char *value;
  1984. const char *expected;
  1985. } cases[] = {
  1986. {"x", ""},
  1987. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1988. {"Bearer abc123", "abc123"},
  1989. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1990. };
  1991. for (const auto &c : cases) {
  1992. Request req;
  1993. req.set_header("Authorization", c.value);
  1994. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1995. }
  1996. }
  1997. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1998. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1999. // to depend on the standard library (libstdc++ handed back duplicates in
  2000. // reverse insertion order, libc++ in insertion order).
  2001. Request req;
  2002. req.set_header("Accept-Encoding", "gzip");
  2003. req.set_header("Accept-Encoding", "deflate");
  2004. req.set_header("Accept-Encoding", "br");
  2005. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  2006. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  2007. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  2008. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  2009. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  2010. }
  2011. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  2012. Request req;
  2013. req.set_header("X-Test", "only");
  2014. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  2015. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  2016. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  2017. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  2018. }
  2019. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  2020. Request req;
  2021. req.set_header("X-First", "1");
  2022. req.set_header("X-Test", "2");
  2023. req.params.emplace("first", "1");
  2024. req.params.emplace("test", "2");
  2025. req.form.fields.emplace("first", FormField{"first", "1", {}});
  2026. req.form.fields.emplace("test", FormField{"test", "2", {}});
  2027. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  2028. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  2029. // The second one is negative when read as a signed value
  2030. const auto max_id = (std::numeric_limits<size_t>::max)();
  2031. for (auto id : {max_id / 2, max_id}) {
  2032. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2033. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2034. EXPECT_EQ("", req.get_param_value("test", id));
  2035. EXPECT_EQ("", req.form.get_field("test", id));
  2036. EXPECT_EQ("", req.form.get_file("test", id).content);
  2037. }
  2038. }
  2039. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2040. Headers headers;
  2041. headers.emplace("Host", "example.com");
  2042. headers.emplace("Accept-Encoding", "gzip");
  2043. headers.emplace("User-Agent", "test");
  2044. headers.emplace("Accept-Encoding", "deflate");
  2045. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2046. "Accept-Encoding=deflate ",
  2047. entries_to_string(headers));
  2048. }
  2049. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2050. Headers headers = {{"Content-Type", "text/html"},
  2051. {"CONTENT-TYPE", "text/xml"}};
  2052. EXPECT_EQ(2U, headers.count("content-type"));
  2053. auto it = headers.find("content-type");
  2054. ASSERT_TRUE(it != headers.end());
  2055. EXPECT_EQ("text/html", it->second);
  2056. }
  2057. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2058. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2059. // drop only those fields and leave everything positioned between them.
  2060. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2061. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2062. auto rng = headers.equal_range("a");
  2063. headers.erase(rng.first, rng.second);
  2064. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2065. }
  2066. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2067. Headers headers = {
  2068. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2069. EXPECT_EQ(3U, headers.erase("A"));
  2070. EXPECT_EQ(0U, headers.count("A"));
  2071. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2072. }
  2073. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2074. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2075. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2076. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2077. }
  2078. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2079. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2080. headers.emplace_front("Host", "example.com");
  2081. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2082. entries_to_string(headers));
  2083. }
  2084. TEST(ParseHeaderValueTest, Range) {
  2085. {
  2086. Ranges ranges;
  2087. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2088. EXPECT_TRUE(ret);
  2089. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2090. }
  2091. {
  2092. Ranges ranges;
  2093. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2094. EXPECT_TRUE(ret);
  2095. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2096. }
  2097. {
  2098. Ranges ranges;
  2099. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2100. EXPECT_TRUE(ret);
  2101. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2102. }
  2103. {
  2104. Ranges ranges;
  2105. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2106. EXPECT_FALSE(ret);
  2107. }
  2108. {
  2109. Ranges ranges;
  2110. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2111. EXPECT_TRUE(ret);
  2112. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2113. }
  2114. {
  2115. Ranges ranges;
  2116. auto ret =
  2117. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2118. EXPECT_TRUE(ret);
  2119. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2120. }
  2121. {
  2122. Ranges ranges;
  2123. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2124. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2125. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2126. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2127. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2128. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2129. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2130. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2131. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2132. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2133. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2134. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2135. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2136. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2137. EXPECT_FALSE(
  2138. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2139. EXPECT_TRUE(ranges.empty());
  2140. }
  2141. {
  2142. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2143. // remainder of the representation, so it stays accepted.
  2144. Ranges ranges;
  2145. auto ret =
  2146. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2147. EXPECT_TRUE(ret);
  2148. ASSERT_EQ(1u, ranges.size());
  2149. EXPECT_EQ(0, ranges[0].first);
  2150. EXPECT_EQ(-1, ranges[0].second);
  2151. }
  2152. // RFC 9110 14.1: range unit names are case-insensitive.
  2153. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2154. Ranges ranges;
  2155. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2156. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2157. }
  2158. }
  2159. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2160. Request req;
  2161. req.set_header("Accept-Encoding", "gzip");
  2162. Response res;
  2163. res.set_header("Content-Type", "text/plain");
  2164. auto ret = detail::encoding_type(req, res);
  2165. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2166. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2167. #else
  2168. EXPECT_TRUE(ret == detail::EncodingType::None);
  2169. #endif
  2170. }
  2171. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2172. Request req;
  2173. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2174. Response res;
  2175. res.set_header("Content-Type", "text/plain");
  2176. auto ret = detail::encoding_type(req, res);
  2177. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2178. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2179. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2180. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2181. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2182. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2183. #else
  2184. EXPECT_TRUE(ret == detail::EncodingType::None);
  2185. #endif
  2186. }
  2187. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2188. Request req;
  2189. req.set_header("Accept-Encoding",
  2190. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2191. Response res;
  2192. res.set_header("Content-Type", "text/plain");
  2193. auto ret = detail::encoding_type(req, res);
  2194. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2195. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2196. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2197. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2198. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2199. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2200. #else
  2201. EXPECT_TRUE(ret == detail::EncodingType::None);
  2202. #endif
  2203. }
  2204. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2205. // All supported encodings rejected with q=0 should return None
  2206. Request req;
  2207. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2208. Response res;
  2209. res.set_header("Content-Type", "text/plain");
  2210. auto ret = detail::encoding_type(req, res);
  2211. EXPECT_TRUE(ret == detail::EncodingType::None);
  2212. }
  2213. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2214. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2215. Request req;
  2216. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2217. Response res;
  2218. res.set_header("Content-Type", "text/plain");
  2219. auto ret = detail::encoding_type(req, res);
  2220. EXPECT_TRUE(ret == detail::EncodingType::None);
  2221. }
  2222. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2223. Request req;
  2224. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2225. Response res;
  2226. res.set_header("Content-Type", "text/plain");
  2227. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2228. }
  2229. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2230. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2231. Request req;
  2232. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2233. Response res;
  2234. res.set_header("Content-Type", "text/plain");
  2235. auto ret = detail::encoding_type(req, res);
  2236. EXPECT_TRUE(ret == detail::EncodingType::None);
  2237. }
  2238. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2239. // RFC 7231: Accept-Encoding values are case-insensitive
  2240. Request req;
  2241. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2242. Response res;
  2243. res.set_header("Content-Type", "text/plain");
  2244. auto ret = detail::encoding_type(req, res);
  2245. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2246. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2247. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2248. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2249. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2250. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2251. #else
  2252. EXPECT_TRUE(ret == detail::EncodingType::None);
  2253. #endif
  2254. }
  2255. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2256. // q value should determine priority, not hardcoded order
  2257. Request req;
  2258. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2259. Response res;
  2260. res.set_header("Content-Type", "text/plain");
  2261. auto ret = detail::encoding_type(req, res);
  2262. // gzip has highest q=1.0, so it should be selected even though
  2263. // br and zstd are also supported
  2264. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2265. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2266. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2267. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2268. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2269. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2270. #else
  2271. EXPECT_TRUE(ret == detail::EncodingType::None);
  2272. #endif
  2273. }
  2274. TEST(BufferStreamTest, read) {
  2275. detail::BufferStream strm1;
  2276. Stream &strm = strm1;
  2277. EXPECT_EQ(5, strm.write("hello"));
  2278. char buf[512];
  2279. EXPECT_EQ(2, strm.read(buf, 2));
  2280. EXPECT_EQ('h', buf[0]);
  2281. EXPECT_EQ('e', buf[1]);
  2282. EXPECT_EQ(2, strm.read(buf, 2));
  2283. EXPECT_EQ('l', buf[0]);
  2284. EXPECT_EQ('l', buf[1]);
  2285. EXPECT_EQ(1, strm.read(buf, 1));
  2286. EXPECT_EQ('o', buf[0]);
  2287. EXPECT_EQ(0, strm.read(buf, 1));
  2288. }
  2289. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2290. auto host = "www.httpwatch.com";
  2291. auto ip = hosted_at(host);
  2292. EXPECT_EQ("23.96.13.243", ip);
  2293. std::vector<std::string> addrs;
  2294. hosted_at(host, addrs);
  2295. EXPECT_EQ(1u, addrs.size());
  2296. }
  2297. #if 0 // It depends on each test environment...
  2298. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2299. auto host = "www.youtube.com";
  2300. std::vector<std::string> addrs;
  2301. hosted_at(host, addrs);
  2302. EXPECT_EQ(20u, addrs.size());
  2303. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2304. EXPECT_TRUE(it != addrs.end());
  2305. }
  2306. #endif
  2307. class ChunkedEncodingTest : public ::testing::Test {
  2308. protected:
  2309. ChunkedEncodingTest()
  2310. : cli_(HOST, PORT)
  2311. #ifdef CPPHTTPLIB_SSL_ENABLED
  2312. ,
  2313. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2314. #endif
  2315. {
  2316. cli_.set_connection_timeout(2);
  2317. #ifdef CPPHTTPLIB_SSL_ENABLED
  2318. cli_.enable_server_certificate_verification(false);
  2319. #endif
  2320. }
  2321. virtual void SetUp() {
  2322. read_file("./image.jpg", image_data_);
  2323. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2324. res.set_content("Hello World!", "text/plain");
  2325. });
  2326. svr_.Get(
  2327. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2328. res.set_chunked_content_provider(
  2329. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2330. size_t remaining = image_data_.size() - offset;
  2331. if (remaining == 0) {
  2332. sink.done();
  2333. } else {
  2334. constexpr size_t CHUNK_SIZE = 1024;
  2335. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2336. sink.write(&image_data_[offset], send_size);
  2337. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2338. }
  2339. return true;
  2340. });
  2341. });
  2342. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2343. svr_.wait_until_ready();
  2344. }
  2345. virtual void TearDown() {
  2346. svr_.stop();
  2347. if (!request_threads_.empty()) {
  2348. std::this_thread::sleep_for(std::chrono::seconds(1));
  2349. for (auto &t : request_threads_) {
  2350. t.join();
  2351. }
  2352. }
  2353. t_.join();
  2354. }
  2355. #ifdef CPPHTTPLIB_SSL_ENABLED
  2356. SSLClient cli_;
  2357. SSLServer svr_;
  2358. #else
  2359. Client cli_;
  2360. Server svr_;
  2361. #endif
  2362. thread t_;
  2363. std::vector<thread> request_threads_;
  2364. std::string image_data_;
  2365. };
  2366. TEST_F(ChunkedEncodingTest, NormalGet) {
  2367. auto res = cli_.Get("/chunked");
  2368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2369. std::string out;
  2370. read_file("./image.jpg", out);
  2371. EXPECT_EQ(StatusCode::OK_200, res->status);
  2372. EXPECT_EQ(out, res->body);
  2373. }
  2374. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2375. std::string body;
  2376. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2377. body.append(data, data_length);
  2378. return true;
  2379. });
  2380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2381. std::string out;
  2382. read_file("./image.jpg", out);
  2383. EXPECT_EQ(StatusCode::OK_200, res->status);
  2384. EXPECT_EQ(out, body);
  2385. }
  2386. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2387. std::string body;
  2388. auto res = cli_.Get(
  2389. "/chunked",
  2390. [&](const Response &response) {
  2391. EXPECT_EQ(StatusCode::OK_200, response.status);
  2392. return true;
  2393. },
  2394. [&](const char *data, size_t data_length) {
  2395. body.append(data, data_length);
  2396. return true;
  2397. });
  2398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2399. std::string out;
  2400. read_file("./image.jpg", out);
  2401. EXPECT_EQ(StatusCode::OK_200, res->status);
  2402. EXPECT_EQ(out, body);
  2403. }
  2404. TEST(RangeTest, FromHTTPBin_Online) {
  2405. auto host = "httpbingo.org";
  2406. auto path = std::string{"/range/32"};
  2407. #ifdef CPPHTTPLIB_SSL_ENABLED
  2408. auto port = 443;
  2409. SSLClient cli(host, port);
  2410. #else
  2411. auto port = 80;
  2412. Client cli(host, port);
  2413. #endif
  2414. cli.set_connection_timeout(5);
  2415. {
  2416. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  2417. SKIP_ON_GATEWAY_ERROR(res);
  2418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2419. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2420. EXPECT_EQ(StatusCode::OK_200, res->status);
  2421. }
  2422. {
  2423. Headers headers = {make_range_header({{1, -1}})};
  2424. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2425. SKIP_ON_GATEWAY_ERROR(res);
  2426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2427. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2428. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2429. }
  2430. {
  2431. Headers headers = {make_range_header({{1, 10}})};
  2432. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2433. SKIP_ON_GATEWAY_ERROR(res);
  2434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2435. EXPECT_EQ("bcdefghijk", res->body);
  2436. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2437. }
  2438. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2439. // entire resource, while the original httpbin returned 200. Both are
  2440. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2441. {
  2442. Headers headers = {make_range_header({{0, 31}})};
  2443. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2444. SKIP_ON_GATEWAY_ERROR(res);
  2445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2446. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2447. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2448. res->status == StatusCode::PartialContent_206);
  2449. }
  2450. {
  2451. Headers headers = {make_range_header({{0, -1}})};
  2452. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2453. SKIP_ON_GATEWAY_ERROR(res);
  2454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2455. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2456. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2457. res->status == StatusCode::PartialContent_206);
  2458. }
  2459. // go-httpbin returns 206 with clamped range for over-range requests,
  2460. // while the original httpbin returned 416. Both behaviors are observed
  2461. // in real servers, so we only verify the request succeeds.
  2462. {
  2463. Headers headers = {make_range_header({{0, 32}})};
  2464. auto res = retry_gateway_errors([&] { return cli.Get(path, headers); });
  2465. SKIP_ON_GATEWAY_ERROR(res);
  2466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2467. }
  2468. }
  2469. TEST(RangeTest, IgnoredForPost) {
  2470. Server svr;
  2471. svr.Post("/", [](const Request &, Response &res) {
  2472. res.set_content("abcdefg", "text/plain");
  2473. });
  2474. auto port = svr.bind_to_any_port(HOST);
  2475. ASSERT_GT(port, 0);
  2476. thread t = thread([&] { svr.listen_after_bind(); });
  2477. auto se = detail::scope_exit([&] {
  2478. svr.stop();
  2479. t.join();
  2480. ASSERT_FALSE(svr.is_running());
  2481. });
  2482. svr.wait_until_ready();
  2483. Client cli(HOST, port);
  2484. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2485. auto res = cli.Post("/", Headers{{"Range", range}});
  2486. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2487. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2488. EXPECT_EQ("abcdefg", res->body) << range;
  2489. }
  2490. }
  2491. TEST(RangeTest, IgnoredForUnknownUnit) {
  2492. Server svr;
  2493. svr.Get("/", [](const Request &, Response &res) {
  2494. res.set_content("abcdefg", "text/plain");
  2495. });
  2496. auto port = svr.bind_to_any_port(HOST);
  2497. ASSERT_GT(port, 0);
  2498. thread t = thread([&] { svr.listen_after_bind(); });
  2499. auto se = detail::scope_exit([&] {
  2500. svr.stop();
  2501. t.join();
  2502. ASSERT_FALSE(svr.is_running());
  2503. });
  2504. svr.wait_until_ready();
  2505. Client cli(HOST, port);
  2506. for (auto range : {"items=1-2", "none=x"}) {
  2507. auto res = cli.Get("/", Headers{{"Range", range}});
  2508. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2509. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2510. EXPECT_EQ("abcdefg", res->body) << range;
  2511. }
  2512. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2513. ASSERT_TRUE(res) << to_string(res.error());
  2514. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2515. }
  2516. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2517. auto host = "unresolvableaddress.local";
  2518. auto path = std::string{"/"};
  2519. #ifdef CPPHTTPLIB_SSL_ENABLED
  2520. auto port = 443;
  2521. SSLClient cli(host, port);
  2522. #else
  2523. auto port = 80;
  2524. Client cli(host, port);
  2525. #endif
  2526. cli.set_connection_timeout(1);
  2527. {
  2528. auto res = cli.Get(path);
  2529. ASSERT_FALSE(res);
  2530. }
  2531. std::this_thread::sleep_for(std::chrono::seconds(8));
  2532. }
  2533. #if defined(__linux__) && defined(__GLIBC__) && \
  2534. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2535. // Forward declaration: in split builds split.py strips `inline` and moves the
  2536. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2537. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2538. // against the symbol in both header-only and split builds.
  2539. namespace httplib {
  2540. namespace detail {
  2541. int getaddrinfo_with_timeout(const char *node, const char *service,
  2542. const struct addrinfo *hints,
  2543. struct addrinfo **res, time_t timeout_sec);
  2544. } // namespace detail
  2545. } // namespace httplib
  2546. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2547. //
  2548. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2549. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2550. // gai_suspend() call hits the connection timeout the function calls
  2551. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2552. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2553. // still alive and still references the now-destroyed stack frame.
  2554. //
  2555. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2556. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2557. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2558. // and runs them in a container.
  2559. namespace {
  2560. bool should_run_issue_2431_tests() {
  2561. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2562. return v && *v && std::string(v) != "0";
  2563. }
  2564. std::string unique_unresolvable_host(int n) {
  2565. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2566. // glibc still asks the configured nameserver — which is exactly the path
  2567. // we want to exercise. A unique label per call avoids the resolver cache.
  2568. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2569. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2570. std::to_string(n) + ".invalid";
  2571. }
  2572. } // namespace
  2573. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2574. if (!should_run_issue_2431_tests()) {
  2575. GTEST_SKIP()
  2576. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2577. }
  2578. for (int i = 0; i < 8; ++i) {
  2579. struct addrinfo hints;
  2580. memset(&hints, 0, sizeof(hints));
  2581. hints.ai_family = AF_UNSPEC;
  2582. hints.ai_socktype = SOCK_STREAM;
  2583. auto host = unique_unresolvable_host(i);
  2584. struct addrinfo *result = nullptr;
  2585. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2586. &result, /*timeout_sec=*/1);
  2587. if (rc == 0 && result) { freeaddrinfo(result); }
  2588. }
  2589. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2590. // stack region they still believe holds their gaicb.
  2591. std::this_thread::sleep_for(std::chrono::seconds(3));
  2592. }
  2593. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2594. if (!should_run_issue_2431_tests()) {
  2595. GTEST_SKIP()
  2596. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2597. }
  2598. std::atomic<bool> stop{false};
  2599. std::vector<std::thread> threads;
  2600. for (int t = 0; t < 8; ++t) {
  2601. threads.emplace_back([t, &stop] {
  2602. int i = 0;
  2603. while (!stop.load(std::memory_order_relaxed)) {
  2604. struct addrinfo hints;
  2605. memset(&hints, 0, sizeof(hints));
  2606. hints.ai_family = AF_UNSPEC;
  2607. hints.ai_socktype = SOCK_STREAM;
  2608. auto host = unique_unresolvable_host(t * 100000 + i++);
  2609. struct addrinfo *result = nullptr;
  2610. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2611. &result, /*timeout_sec=*/1);
  2612. if (rc == 0 && result) { freeaddrinfo(result); }
  2613. }
  2614. });
  2615. }
  2616. std::this_thread::sleep_for(std::chrono::seconds(8));
  2617. stop.store(true, std::memory_order_relaxed);
  2618. for (auto &th : threads) {
  2619. th.join();
  2620. }
  2621. std::this_thread::sleep_for(std::chrono::seconds(3));
  2622. }
  2623. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2624. if (!should_run_issue_2431_tests()) {
  2625. GTEST_SKIP()
  2626. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2627. }
  2628. std::atomic<bool> stop{false};
  2629. std::vector<std::thread> threads;
  2630. for (int t = 0; t < 8; ++t) {
  2631. threads.emplace_back([t, &stop] {
  2632. int i = 0;
  2633. while (!stop.load(std::memory_order_relaxed)) {
  2634. auto host = unique_unresolvable_host(t * 100000 + i++);
  2635. Client cli(host, 80);
  2636. cli.set_connection_timeout(1, 0);
  2637. cli.set_read_timeout(1, 0);
  2638. cli.set_write_timeout(1, 0);
  2639. (void)cli.Get("/");
  2640. }
  2641. });
  2642. }
  2643. std::this_thread::sleep_for(std::chrono::seconds(8));
  2644. stop.store(true, std::memory_order_relaxed);
  2645. for (auto &th : threads) {
  2646. th.join();
  2647. }
  2648. std::this_thread::sleep_for(std::chrono::seconds(3));
  2649. }
  2650. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2651. TEST(ConnectionErrorTest, InvalidHost) {
  2652. auto host = "-abcde.com";
  2653. #ifdef CPPHTTPLIB_SSL_ENABLED
  2654. auto port = 443;
  2655. SSLClient cli(host, port);
  2656. #else
  2657. auto port = 80;
  2658. Client cli(host, port);
  2659. #endif
  2660. cli.set_connection_timeout(std::chrono::seconds(2));
  2661. auto res = cli.Get("/");
  2662. ASSERT_TRUE(!res);
  2663. EXPECT_EQ(Error::Connection, res.error());
  2664. }
  2665. TEST(ConnectionErrorTest, InvalidHost2) {
  2666. auto host = "httpcan.org/";
  2667. #ifdef CPPHTTPLIB_SSL_ENABLED
  2668. SSLClient cli(host);
  2669. #else
  2670. Client cli(host);
  2671. #endif
  2672. cli.set_connection_timeout(std::chrono::seconds(2));
  2673. auto res = cli.Get("/");
  2674. ASSERT_TRUE(!res);
  2675. EXPECT_EQ(Error::Connection, res.error());
  2676. }
  2677. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2678. auto host = "httpcan.org/";
  2679. #ifdef CPPHTTPLIB_SSL_ENABLED
  2680. SSLClient cli(host);
  2681. #else
  2682. Client cli(host);
  2683. #endif
  2684. cli.set_connection_timeout(std::chrono::seconds(2));
  2685. auto res = cli.Get("/");
  2686. ASSERT_TRUE(!res);
  2687. stringstream s;
  2688. s << "error code: " << res.error();
  2689. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2690. }
  2691. TEST(ConnectionErrorTest, InvalidPort) {
  2692. auto host = "localhost";
  2693. auto port = 44380;
  2694. #ifdef CPPHTTPLIB_SSL_ENABLED
  2695. SSLClient cli(host, port);
  2696. #else
  2697. Client cli(host, port);
  2698. #endif
  2699. cli.set_connection_timeout(std::chrono::seconds(2));
  2700. auto res = cli.Get("/");
  2701. ASSERT_TRUE(!res);
  2702. EXPECT_TRUE(Error::Connection == res.error() ||
  2703. Error::ConnectionTimeout == res.error());
  2704. }
  2705. TEST(ConnectionErrorTest, Timeout_Online) {
  2706. auto host = "google.com";
  2707. #ifdef CPPHTTPLIB_SSL_ENABLED
  2708. auto port = 44380;
  2709. SSLClient cli(host, port);
  2710. #else
  2711. auto port = 8080;
  2712. Client cli(host, port);
  2713. #endif
  2714. cli.set_connection_timeout(std::chrono::seconds(2));
  2715. // only probe one address type so that the error reason
  2716. // correlates to the timed-out IPv4, not the unsupported
  2717. // IPv6 connection attempt
  2718. cli.set_address_family(AF_INET);
  2719. auto res = cli.Get("/");
  2720. ASSERT_TRUE(!res);
  2721. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2722. }
  2723. TEST(CancelTest, NoCancel_Online) {
  2724. auto host = "httpbingo.org";
  2725. auto path = std::string{"/range/32"};
  2726. #ifdef CPPHTTPLIB_SSL_ENABLED
  2727. auto port = 443;
  2728. SSLClient cli(host, port);
  2729. #else
  2730. auto port = 80;
  2731. Client cli(host, port);
  2732. #endif
  2733. cli.set_connection_timeout(std::chrono::seconds(5));
  2734. auto res = retry_gateway_errors(
  2735. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
  2736. SKIP_ON_GATEWAY_ERROR(res);
  2737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2738. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2739. EXPECT_EQ(StatusCode::OK_200, res->status);
  2740. }
  2741. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2742. // Use /bytes with a large payload so that the DownloadProgress callback
  2743. // (which only fires for Content-Length responses) is invoked before the
  2744. // entire body is received, giving cancellation a chance to fire.
  2745. auto host = "httpbingo.org";
  2746. auto path = std::string{"/bytes/524288"};
  2747. #ifdef CPPHTTPLIB_SSL_ENABLED
  2748. auto port = 443;
  2749. SSLClient cli(host, port);
  2750. #else
  2751. auto port = 80;
  2752. Client cli(host, port);
  2753. #endif
  2754. auto res = retry_gateway_errors(
  2755. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
  2756. SKIP_ON_GATEWAY_ERROR(res);
  2757. cli.set_connection_timeout(std::chrono::seconds(5));
  2758. ASSERT_TRUE(!res);
  2759. EXPECT_EQ(Error::Canceled, res.error());
  2760. }
  2761. TEST(CancelTest, WithCancelLargePayload_Online) {
  2762. auto host = "httpbingo.org";
  2763. auto path = std::string{"/bytes/524288"};
  2764. #ifdef CPPHTTPLIB_SSL_ENABLED
  2765. auto port = 443;
  2766. SSLClient cli(host, port);
  2767. #else
  2768. auto port = 80;
  2769. Client cli(host, port);
  2770. #endif
  2771. cli.set_connection_timeout(std::chrono::seconds(5));
  2772. auto res = retry_gateway_errors([&] {
  2773. auto count = 0;
  2774. return cli.Get(path,
  2775. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2776. });
  2777. SKIP_ON_GATEWAY_ERROR(res);
  2778. ASSERT_TRUE(!res);
  2779. EXPECT_EQ(Error::Canceled, res.error());
  2780. }
  2781. TEST(CancelTest, NoCancelPost) {
  2782. Server svr;
  2783. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2784. res.set_content("Hello World!", "text/plain");
  2785. });
  2786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2787. auto se = detail::scope_exit([&] {
  2788. svr.stop();
  2789. thread.join();
  2790. ASSERT_FALSE(svr.is_running());
  2791. });
  2792. svr.wait_until_ready();
  2793. Client cli(HOST, PORT);
  2794. cli.set_connection_timeout(std::chrono::seconds(5));
  2795. auto res =
  2796. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2797. "application/json", [](uint64_t, uint64_t) { return true; });
  2798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2799. EXPECT_EQ("Hello World!", res->body);
  2800. EXPECT_EQ(StatusCode::OK_200, res->status);
  2801. }
  2802. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2803. Server svr;
  2804. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2805. res.set_content("Hello World!", "text/plain");
  2806. });
  2807. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2808. auto se = detail::scope_exit([&] {
  2809. svr.stop();
  2810. thread.join();
  2811. ASSERT_FALSE(svr.is_running());
  2812. });
  2813. svr.wait_until_ready();
  2814. Client cli(HOST, PORT);
  2815. cli.set_connection_timeout(std::chrono::seconds(5));
  2816. auto res =
  2817. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2818. "application/json", [](uint64_t, uint64_t) { return false; });
  2819. ASSERT_TRUE(!res);
  2820. EXPECT_EQ(Error::Canceled, res.error());
  2821. }
  2822. TEST(CancelTest, WithCancelLargePayloadPost) {
  2823. Server svr;
  2824. svr.set_payload_max_length(200 * 1024 * 1024);
  2825. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2826. res.set_content(LARGE_DATA, "text/plain");
  2827. });
  2828. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2829. auto se = detail::scope_exit([&] {
  2830. svr.stop();
  2831. thread.join();
  2832. ASSERT_FALSE(svr.is_running());
  2833. });
  2834. svr.wait_until_ready();
  2835. Client cli(HOST, PORT);
  2836. cli.set_payload_max_length(200 * 1024 * 1024);
  2837. cli.set_connection_timeout(std::chrono::seconds(5));
  2838. auto res =
  2839. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2840. "application/json", [](uint64_t, uint64_t) { return false; });
  2841. ASSERT_TRUE(!res);
  2842. EXPECT_EQ(Error::Canceled, res.error());
  2843. }
  2844. TEST(CancelTest, NoCancelPut) {
  2845. Server svr;
  2846. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2847. res.set_content("Hello World!", "text/plain");
  2848. });
  2849. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2850. auto se = detail::scope_exit([&] {
  2851. svr.stop();
  2852. thread.join();
  2853. ASSERT_FALSE(svr.is_running());
  2854. });
  2855. svr.wait_until_ready();
  2856. Client cli(HOST, PORT);
  2857. cli.set_connection_timeout(std::chrono::seconds(5));
  2858. auto res =
  2859. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2860. "application/json", [](uint64_t, uint64_t) { return true; });
  2861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2862. EXPECT_EQ("Hello World!", res->body);
  2863. EXPECT_EQ(StatusCode::OK_200, res->status);
  2864. }
  2865. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2866. Server svr;
  2867. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2868. res.set_content("Hello World!", "text/plain");
  2869. });
  2870. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2871. auto se = detail::scope_exit([&] {
  2872. svr.stop();
  2873. thread.join();
  2874. ASSERT_FALSE(svr.is_running());
  2875. });
  2876. svr.wait_until_ready();
  2877. Client cli(HOST, PORT);
  2878. cli.set_connection_timeout(std::chrono::seconds(5));
  2879. auto res =
  2880. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2881. "application/json", [](uint64_t, uint64_t) { return false; });
  2882. ASSERT_TRUE(!res);
  2883. EXPECT_EQ(Error::Canceled, res.error());
  2884. }
  2885. TEST(CancelTest, WithCancelLargePayloadPut) {
  2886. Server svr;
  2887. svr.set_payload_max_length(200 * 1024 * 1024);
  2888. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2889. res.set_content(LARGE_DATA, "text/plain");
  2890. });
  2891. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2892. auto se = detail::scope_exit([&] {
  2893. svr.stop();
  2894. thread.join();
  2895. ASSERT_FALSE(svr.is_running());
  2896. });
  2897. svr.wait_until_ready();
  2898. Client cli(HOST, PORT);
  2899. cli.set_payload_max_length(200 * 1024 * 1024);
  2900. cli.set_connection_timeout(std::chrono::seconds(5));
  2901. auto res =
  2902. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2903. "application/json", [](uint64_t, uint64_t) { return false; });
  2904. ASSERT_TRUE(!res);
  2905. EXPECT_EQ(Error::Canceled, res.error());
  2906. }
  2907. TEST(CancelTest, NoCancelPatch) {
  2908. Server svr;
  2909. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2910. res.set_content("Hello World!", "text/plain");
  2911. });
  2912. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2913. auto se = detail::scope_exit([&] {
  2914. svr.stop();
  2915. thread.join();
  2916. ASSERT_FALSE(svr.is_running());
  2917. });
  2918. svr.wait_until_ready();
  2919. Client cli(HOST, PORT);
  2920. cli.set_connection_timeout(std::chrono::seconds(5));
  2921. auto res =
  2922. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2923. "application/json", [](uint64_t, uint64_t) { return true; });
  2924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2925. EXPECT_EQ("Hello World!", res->body);
  2926. EXPECT_EQ(StatusCode::OK_200, res->status);
  2927. }
  2928. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2929. Server svr;
  2930. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2931. res.set_content("Hello World!", "text/plain");
  2932. });
  2933. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2934. auto se = detail::scope_exit([&] {
  2935. svr.stop();
  2936. thread.join();
  2937. ASSERT_FALSE(svr.is_running());
  2938. });
  2939. svr.wait_until_ready();
  2940. Client cli(HOST, PORT);
  2941. cli.set_connection_timeout(std::chrono::seconds(5));
  2942. auto res =
  2943. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2944. "application/json", [](uint64_t, uint64_t) { return false; });
  2945. ASSERT_TRUE(!res);
  2946. EXPECT_EQ(Error::Canceled, res.error());
  2947. }
  2948. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2949. Server svr;
  2950. svr.set_payload_max_length(200 * 1024 * 1024);
  2951. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2952. res.set_content(LARGE_DATA, "text/plain");
  2953. });
  2954. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2955. auto se = detail::scope_exit([&] {
  2956. svr.stop();
  2957. thread.join();
  2958. ASSERT_FALSE(svr.is_running());
  2959. });
  2960. svr.wait_until_ready();
  2961. Client cli(HOST, PORT);
  2962. cli.set_payload_max_length(200 * 1024 * 1024);
  2963. cli.set_connection_timeout(std::chrono::seconds(5));
  2964. auto res =
  2965. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2966. "application/json", [](uint64_t, uint64_t) { return false; });
  2967. ASSERT_TRUE(!res);
  2968. EXPECT_EQ(Error::Canceled, res.error());
  2969. }
  2970. TEST(CancelTest, NoCancelDelete) {
  2971. Server svr;
  2972. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2973. res.set_content("Hello World!", "text/plain");
  2974. });
  2975. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2976. auto se = detail::scope_exit([&] {
  2977. svr.stop();
  2978. thread.join();
  2979. ASSERT_FALSE(svr.is_running());
  2980. });
  2981. svr.wait_until_ready();
  2982. Client cli(HOST, PORT);
  2983. cli.set_connection_timeout(std::chrono::seconds(5));
  2984. auto res =
  2985. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2986. "application/json", [](uint64_t, uint64_t) { return true; });
  2987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2988. EXPECT_EQ("Hello World!", res->body);
  2989. EXPECT_EQ(StatusCode::OK_200, res->status);
  2990. }
  2991. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2992. Server svr;
  2993. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2994. res.set_content("Hello World!", "text/plain");
  2995. });
  2996. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2997. auto se = detail::scope_exit([&] {
  2998. svr.stop();
  2999. thread.join();
  3000. ASSERT_FALSE(svr.is_running());
  3001. });
  3002. svr.wait_until_ready();
  3003. Client cli(HOST, PORT);
  3004. cli.set_connection_timeout(std::chrono::seconds(5));
  3005. auto res =
  3006. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3007. "application/json", [](uint64_t, uint64_t) { return false; });
  3008. ASSERT_TRUE(!res);
  3009. EXPECT_EQ(Error::Canceled, res.error());
  3010. }
  3011. TEST(CancelTest, WithCancelLargePayloadDelete) {
  3012. Server svr;
  3013. svr.set_payload_max_length(200 * 1024 * 1024);
  3014. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3015. res.set_content(LARGE_DATA, "text/plain");
  3016. });
  3017. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3018. auto se = detail::scope_exit([&] {
  3019. svr.stop();
  3020. thread.join();
  3021. ASSERT_FALSE(svr.is_running());
  3022. });
  3023. svr.wait_until_ready();
  3024. Client cli(HOST, PORT);
  3025. cli.set_payload_max_length(200 * 1024 * 1024);
  3026. cli.set_connection_timeout(std::chrono::seconds(5));
  3027. auto res =
  3028. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3029. "application/json", [](uint64_t, uint64_t) { return false; });
  3030. ASSERT_TRUE(!res);
  3031. EXPECT_EQ(Error::Canceled, res.error());
  3032. }
  3033. // One stop() from another thread ends a request that waits for the response
  3034. TEST(ClientStopTest, StopEndsWaitForResponse) {
  3035. Server svr;
  3036. std::atomic<bool> received{false};
  3037. std::atomic<bool> done{false};
  3038. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  3039. received.store(true);
  3040. while (!done.load()) {
  3041. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3042. }
  3043. res.set_content("Hello World!", "text/plain");
  3044. });
  3045. auto port = svr.bind_to_any_port(HOST);
  3046. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3047. Client cli(HOST, port);
  3048. cli.set_read_timeout(std::chrono::seconds(30));
  3049. std::future<Result> request;
  3050. auto se = detail::scope_exit([&] {
  3051. done.store(true);
  3052. svr.stop();
  3053. thread.join();
  3054. ASSERT_FALSE(svr.is_running());
  3055. });
  3056. svr.wait_until_ready();
  3057. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3058. for (int i = 0; i < 500 && !received.load(); ++i) {
  3059. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3060. }
  3061. ASSERT_TRUE(received.load());
  3062. // Let the client block in the wait for the response
  3063. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3064. auto start = std::chrono::steady_clock::now();
  3065. cli.stop();
  3066. ASSERT_EQ(std::future_status::ready,
  3067. request.wait_for(std::chrono::seconds(5)));
  3068. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3069. auto res = request.get();
  3070. ASSERT_TRUE(!res);
  3071. EXPECT_EQ(Error::Read, res.error());
  3072. }
  3073. // A listener whose backlog completes the TCP connections of clients, and that
  3074. // never answers them
  3075. struct SilentListener {
  3076. socket_t sock = INVALID_SOCKET;
  3077. sockaddr_in addr{};
  3078. int port = 0;
  3079. explicit SilentListener(int backlog = 1) {
  3080. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3081. addr.sin_family = AF_INET;
  3082. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3083. socklen_t len = sizeof(addr);
  3084. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3085. ::listen(sock, backlog) != 0 ||
  3086. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3087. detail::close_socket(sock);
  3088. sock = INVALID_SOCKET;
  3089. }
  3090. port = ntohs(addr.sin_port);
  3091. }
  3092. ~SilentListener() { detail::close_socket(sock); }
  3093. // The next connection, whose reads give up after 5 seconds
  3094. socket_t accept() const {
  3095. auto peer = ::accept(sock, nullptr, nullptr);
  3096. if (peer != INVALID_SOCKET) {
  3097. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3098. }
  3099. return peer;
  3100. }
  3101. };
  3102. static bool receives_a_byte(socket_t peer) {
  3103. char c = 0;
  3104. return detail::read_socket(peer, &c, 1, 0) == 1;
  3105. }
  3106. // Runs op, stops cli once the listener receives the first byte op sends, and
  3107. // expects op to end with error soon after
  3108. template <typename ClientType, typename Op>
  3109. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3110. Op op, Error error = Error::Canceled) {
  3111. auto ended = std::async(std::launch::async, op);
  3112. auto peer = listener.accept();
  3113. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3114. ASSERT_NE(INVALID_SOCKET, peer);
  3115. ASSERT_TRUE(receives_a_byte(peer));
  3116. cli.stop();
  3117. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3118. EXPECT_EQ(error, ended.get());
  3119. }
  3120. // Stops itself from another thread as the connection opens, the last moment a
  3121. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3122. // waits for the connection fails the test instead of hanging it.
  3123. class StoppedAsConnectedClient : public ClientImpl {
  3124. public:
  3125. using ClientImpl::ClientImpl;
  3126. protected:
  3127. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3128. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3129. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3130. stopper_.wait_for(std::chrono::seconds(1));
  3131. return true;
  3132. }
  3133. private:
  3134. std::future<void> stopper_;
  3135. };
  3136. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3137. SilentListener listener;
  3138. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3139. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3140. cli.set_read_timeout(std::chrono::seconds(3));
  3141. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3142. auto peer = listener.accept();
  3143. EXPECT_FALSE(receives_a_byte(peer));
  3144. detail::close_socket(peer);
  3145. auto handle = cli.open_stream("GET", "/");
  3146. EXPECT_FALSE(handle.is_valid());
  3147. EXPECT_EQ(Error::Canceled, handle.error);
  3148. peer = listener.accept();
  3149. EXPECT_FALSE(receives_a_byte(peer));
  3150. detail::close_socket(peer);
  3151. }
  3152. #ifdef __linux__
  3153. // A connect that a listener with a full backlog never completes
  3154. TEST(ClientStopTest, StopEndsAConnect) {
  3155. SilentListener listener(0);
  3156. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3157. std::vector<socket_t> backlog;
  3158. auto close_backlog = detail::scope_exit([&] {
  3159. for (auto sock : backlog) {
  3160. detail::close_socket(sock);
  3161. }
  3162. });
  3163. for (int i = 0; i < 8; i++) {
  3164. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3165. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3166. sizeof(listener.addr));
  3167. backlog.push_back(sock);
  3168. }
  3169. Client cli("127.0.0.1", listener.port);
  3170. cli.set_connection_timeout(std::chrono::seconds(3));
  3171. auto ended =
  3172. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3173. // A stop() before the request starts does not apply to it, so it repeats
  3174. auto status = std::future_status::timeout;
  3175. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3176. cli.stop();
  3177. status = ended.wait_for(std::chrono::milliseconds(10));
  3178. }
  3179. EXPECT_EQ(std::future_status::ready, status);
  3180. EXPECT_EQ(Error::Canceled, ended.get());
  3181. }
  3182. #endif
  3183. // The stream holds the socket while it waits for the head, out of the reach
  3184. // of shutdown()
  3185. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3186. SilentListener listener;
  3187. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3188. Client cli("127.0.0.1", listener.port);
  3189. cli.set_read_timeout(std::chrono::seconds(3));
  3190. expect_stop_ends(
  3191. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3192. Error::Read);
  3193. }
  3194. #ifdef CPPHTTPLIB_SSL_ENABLED
  3195. // A server that never answers the ClientHello
  3196. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3197. SilentListener listener;
  3198. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3199. SSLClient cli("127.0.0.1", listener.port);
  3200. cli.enable_server_certificate_verification(false);
  3201. cli.set_connection_timeout(std::chrono::seconds(3));
  3202. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3203. expect_stop_ends(cli, listener,
  3204. [&] { return cli.open_stream("GET", "/").error; });
  3205. }
  3206. // A proxy that takes the CONNECT and never answers it
  3207. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3208. SilentListener listener;
  3209. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3210. SSLClient cli("example.com", 443);
  3211. cli.set_proxy("127.0.0.1", listener.port);
  3212. cli.set_read_timeout(std::chrono::seconds(3));
  3213. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3214. }
  3215. #endif
  3216. // A read timeout past what the clock reaches waits for the response
  3217. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3218. SilentListener listener;
  3219. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3220. Client cli("127.0.0.1", listener.port);
  3221. cli.set_read_timeout(
  3222. static_cast<time_t>((std::min)(static_cast<long long>(
  3223. (std::numeric_limits<time_t>::max)()),
  3224. 10000000000LL)),
  3225. 0);
  3226. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3227. auto peer = listener.accept();
  3228. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3229. ASSERT_NE(INVALID_SOCKET, peer);
  3230. ASSERT_TRUE(receives_a_byte(peer));
  3231. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3232. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3233. "Connection: close\r\n\r\nok";
  3234. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3235. auto result = res.get();
  3236. ASSERT_TRUE(result);
  3237. EXPECT_EQ("ok", result->body);
  3238. }
  3239. static std::string remove_whitespace(const std::string &input) {
  3240. std::string output;
  3241. output.reserve(input.size());
  3242. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3243. [](unsigned char c) { return !std::isspace(c); });
  3244. return output;
  3245. }
  3246. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3247. auto host = "httpbingo.org";
  3248. auto path = std::string{"/basic-auth/hello/world"};
  3249. #ifdef CPPHTTPLIB_SSL_ENABLED
  3250. auto port = 443;
  3251. SSLClient cli(host, port);
  3252. #else
  3253. auto port = 80;
  3254. Client cli(host, port);
  3255. #endif
  3256. {
  3257. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3258. SKIP_ON_GATEWAY_ERROR(res);
  3259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3260. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3261. }
  3262. {
  3263. auto res = retry_gateway_errors([&] {
  3264. return cli.Get(
  3265. path, Headers{make_basic_authentication_header("hello", "world")});
  3266. });
  3267. SKIP_ON_GATEWAY_ERROR(res);
  3268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3269. auto body = remove_whitespace(res->body);
  3270. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3271. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3272. EXPECT_EQ(StatusCode::OK_200, res->status);
  3273. }
  3274. {
  3275. cli.set_basic_auth("hello", "world");
  3276. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3277. SKIP_ON_GATEWAY_ERROR(res);
  3278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3279. auto body = remove_whitespace(res->body);
  3280. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3281. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3282. EXPECT_EQ(StatusCode::OK_200, res->status);
  3283. }
  3284. {
  3285. cli.set_basic_auth("hello", "bad");
  3286. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3287. SKIP_ON_GATEWAY_ERROR(res);
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3290. }
  3291. {
  3292. cli.set_basic_auth("bad", "world");
  3293. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3294. SKIP_ON_GATEWAY_ERROR(res);
  3295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3296. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3297. }
  3298. }
  3299. #ifdef CPPHTTPLIB_SSL_ENABLED
  3300. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3301. auto host = "httpbingo.org";
  3302. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3303. auto paths = std::vector<std::string>{
  3304. "/digest-auth/auth/hello/world/MD5",
  3305. "/digest-auth/auth/hello/world/SHA-256",
  3306. };
  3307. auto port = 443;
  3308. SSLClient cli(host, port);
  3309. {
  3310. auto res = retry_gateway_errors([&] { return cli.Get(unauth_path); });
  3311. SKIP_ON_GATEWAY_ERROR(res);
  3312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3313. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3314. }
  3315. {
  3316. cli.set_digest_auth("hello", "world");
  3317. for (const auto &path : paths) {
  3318. auto res = retry_gateway_errors([&] { return cli.Get(path.c_str()); });
  3319. SKIP_ON_GATEWAY_ERROR(res);
  3320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3321. auto body = remove_whitespace(res->body);
  3322. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3323. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3324. EXPECT_EQ(StatusCode::OK_200, res->status);
  3325. }
  3326. cli.set_digest_auth("hello", "bad");
  3327. for (const auto &path : paths) {
  3328. auto res = retry_gateway_errors([&] { return cli.Get(path.c_str()); });
  3329. SKIP_ON_GATEWAY_ERROR(res);
  3330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3331. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3332. }
  3333. }
  3334. }
  3335. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3336. // comma-separated list of challenges, and each challenge may itself carry a
  3337. // comma-separated auth-param list, so a server can legally offer Basic
  3338. // before Digest, either as two field lines or packed into one. Runs one 401
  3339. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3340. // value() joins them in receipt order) and checks that the retry carries a
  3341. // well-formed Digest Authorization header naming expected_realm.
  3342. static void
  3343. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3344. const std::string &expected_realm) {
  3345. std::atomic<int> hits{0};
  3346. Server svr;
  3347. svr.Get("/x", [&](const Request &req, Response &res) {
  3348. if (++hits == 1) {
  3349. res.status = StatusCode::Unauthorized_401;
  3350. for (const auto &challenge : challenges) {
  3351. res.set_header("WWW-Authenticate", challenge);
  3352. }
  3353. } else {
  3354. auto authorization = req.get_header_value("Authorization");
  3355. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3356. EXPECT_NE(std::string::npos,
  3357. authorization.find("realm=\"" + expected_realm + "\""));
  3358. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3359. res.set_content("ok", "text/plain");
  3360. }
  3361. });
  3362. auto port = svr.bind_to_any_port(HOST);
  3363. std::thread t([&]() { svr.listen_after_bind(); });
  3364. auto se = detail::scope_exit([&] {
  3365. svr.stop();
  3366. t.join();
  3367. });
  3368. svr.wait_until_ready();
  3369. Client cli(HOST, port);
  3370. cli.set_digest_auth("hello", "world");
  3371. auto res = cli.Get("/x");
  3372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3373. EXPECT_EQ(2, hits.load());
  3374. }
  3375. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3376. static const char *kDigestChallenge =
  3377. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3378. "algorithm=MD5";
  3379. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3380. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3381. "testrealm");
  3382. }
  3383. // Same challenge list with the schemes in the opposite order, to make sure
  3384. // the fix above didn't just special-case "Basic first".
  3385. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3386. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3387. "testrealm");
  3388. }
  3389. // A comma inside a quoted auth-param value must not be mistaken for the
  3390. // separator between two challenges (or two auth-params).
  3391. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3392. run_digest_challenge_list_test(
  3393. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3394. "algorithm=MD5"},
  3395. "test,realm");
  3396. }
  3397. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3398. // the params and leaves out the fragment.
  3399. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3400. Server svr;
  3401. std::string uri, target;
  3402. svr.Get("/a b", [&](const Request &req, Response &res) {
  3403. auto auth = req.get_header_value("Authorization");
  3404. if (auth.empty()) {
  3405. res.status = StatusCode::Unauthorized_401;
  3406. res.set_header("WWW-Authenticate",
  3407. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3408. return;
  3409. }
  3410. auto b = auth.find("uri=\"") + 5;
  3411. uri = auth.substr(b, auth.find('"', b) - b);
  3412. target = req.target;
  3413. });
  3414. auto port = svr.bind_to_any_port(HOST);
  3415. std::thread t([&]() { svr.listen_after_bind(); });
  3416. auto se = detail::scope_exit([&] {
  3417. svr.stop();
  3418. t.join();
  3419. });
  3420. svr.wait_until_ready();
  3421. Client cli(HOST, port);
  3422. cli.set_digest_auth("hello", "world");
  3423. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3425. EXPECT_EQ("/a%20b?x=1", target);
  3426. EXPECT_EQ(target, uri);
  3427. }
  3428. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3429. // make_digest_authentication_header() dereferences both unconditionally, so
  3430. // a server sending a challenge missing either one must not be treated as
  3431. // usable -- doing so used to crash the client with std::out_of_range.
  3432. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3433. Server svr;
  3434. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3435. res.status = StatusCode::Unauthorized_401;
  3436. res.set_header("WWW-Authenticate", challenge);
  3437. });
  3438. auto port = svr.bind_to_any_port(HOST);
  3439. std::thread t([&]() { svr.listen_after_bind(); });
  3440. auto se = detail::scope_exit([&] {
  3441. svr.stop();
  3442. t.join();
  3443. });
  3444. svr.wait_until_ready();
  3445. Client cli(HOST, port);
  3446. cli.set_digest_auth("hello", "world");
  3447. auto res = cli.Get("/x");
  3448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3449. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3450. }
  3451. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3452. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3453. }
  3454. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3455. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3456. }
  3457. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3458. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3459. }
  3460. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3461. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3462. // when storing the values, so the header builder has to re-escape them (and
  3463. // keep algorithm a bare token); otherwise the value breaks out of its
  3464. // quoted-string and injects extra auth-params into the client's Authorization.
  3465. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3466. std::atomic<int> hits{0};
  3467. std::string authorization;
  3468. Server svr;
  3469. svr.Get("/x", [&](const Request &req, Response &res) {
  3470. if (++hits == 1) {
  3471. res.status = StatusCode::Unauthorized_401;
  3472. // On the wire the quotes embedded in the values are backslash-escaped.
  3473. res.set_header("WWW-Authenticate",
  3474. "Digest realm=\"testrealm\", "
  3475. "nonce=\"n\\\"; injected=\\\"x\", "
  3476. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3477. } else {
  3478. authorization = req.get_header_value("Authorization");
  3479. res.set_content("ok", "text/plain");
  3480. }
  3481. });
  3482. auto port = svr.bind_to_any_port(HOST);
  3483. std::thread t([&]() { svr.listen_after_bind(); });
  3484. auto se = detail::scope_exit([&] {
  3485. svr.stop();
  3486. t.join();
  3487. });
  3488. svr.wait_until_ready();
  3489. Client cli(HOST, port);
  3490. cli.set_digest_auth("hello", "world");
  3491. auto res = cli.Get("/x");
  3492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3493. EXPECT_EQ(2, hits.load());
  3494. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3495. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3496. // inside its quoted-string rather than starting an "injected" auth-param.
  3497. EXPECT_NE(std::string::npos,
  3498. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3499. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3500. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3501. }
  3502. #endif
  3503. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3504. auto host = "google.com";
  3505. auto another_host = "example.com";
  3506. auto wrong_ip = "0.0.0.0";
  3507. #ifdef CPPHTTPLIB_SSL_ENABLED
  3508. SSLClient cli(host);
  3509. #else
  3510. Client cli(host);
  3511. #endif
  3512. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3513. auto res = cli.Get("/");
  3514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3515. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3516. }
  3517. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3518. auto host = "google.com";
  3519. auto wrong_ip = "0.0.0.0";
  3520. #ifdef CPPHTTPLIB_SSL_ENABLED
  3521. SSLClient cli(host);
  3522. #else
  3523. Client cli(host);
  3524. #endif
  3525. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3526. auto res = cli.Get("/");
  3527. ASSERT_TRUE(!res);
  3528. EXPECT_EQ(Error::Connection, res.error());
  3529. }
  3530. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3531. // A mapped value that is not an IP literal must be resolved. "localhost"
  3532. // resolves from the hosts file, so this test needs no external DNS.
  3533. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3534. auto host = "target.invalid";
  3535. Server svr;
  3536. std::string received_host;
  3537. svr.Get("/hi", [&](const Request &req, Response &res) {
  3538. received_host = req.get_header_value("Host");
  3539. res.set_content("Hello World!", "text/plain");
  3540. });
  3541. auto port = svr.bind_to_any_port(HOST);
  3542. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3543. auto se = detail::scope_exit([&] {
  3544. svr.stop();
  3545. thread.join();
  3546. ASSERT_FALSE(svr.is_running());
  3547. });
  3548. svr.wait_until_ready();
  3549. Client cli(host, port);
  3550. cli.set_direct_hostname_addr_map({{host, HOST}});
  3551. auto res = cli.Get("/hi");
  3552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3553. EXPECT_EQ(StatusCode::OK_200, res->status);
  3554. // The mapping only redirects the connection; the identity stays host_.
  3555. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3556. }
  3557. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3558. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3559. auto host = "target.invalid";
  3560. Server svr;
  3561. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3562. res.set_content("Hello World!", "text/plain");
  3563. });
  3564. auto port = svr.bind_to_any_port("127.0.0.1");
  3565. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3566. auto se = detail::scope_exit([&] {
  3567. svr.stop();
  3568. thread.join();
  3569. ASSERT_FALSE(svr.is_running());
  3570. });
  3571. svr.wait_until_ready();
  3572. Client cli(host, port);
  3573. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3574. auto res = cli.Get("/hi");
  3575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3576. EXPECT_EQ(StatusCode::OK_200, res->status);
  3577. }
  3578. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3579. // An empty mapped value must leave host_ as the connection target. Without
  3580. // that guard the empty value would become the host argument, getaddrinfo
  3581. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3582. // loopback - silently connecting somewhere the caller never asked for.
  3583. // The server listens on loopback, so such a fallback would succeed and is
  3584. // therefore observable as a failure of this test.
  3585. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3586. Server svr;
  3587. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3588. res.set_content("Hello World!", "text/plain");
  3589. });
  3590. auto port = svr.bind_to_any_port(HOST);
  3591. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3592. auto se = detail::scope_exit([&] {
  3593. svr.stop();
  3594. thread.join();
  3595. ASSERT_FALSE(svr.is_running());
  3596. });
  3597. svr.wait_until_ready();
  3598. Client cli(blackhole, port);
  3599. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3600. cli.set_connection_timeout(1);
  3601. auto res = cli.Get("/hi");
  3602. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3603. }
  3604. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3605. auto host = "target.invalid";
  3606. Server svr;
  3607. std::string received_host;
  3608. svr.Get("/hi", [&](const Request &req, Response &res) {
  3609. received_host = req.get_header_value("Host");
  3610. res.set_content("Hello World!", "text/plain");
  3611. });
  3612. auto port = svr.bind_to_any_port("127.0.0.1");
  3613. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3614. auto se = detail::scope_exit([&] {
  3615. svr.stop();
  3616. thread.join();
  3617. ASSERT_FALSE(svr.is_running());
  3618. });
  3619. svr.wait_until_ready();
  3620. Client cli(host, port);
  3621. #pragma GCC diagnostic push
  3622. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3623. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3624. #pragma GCC diagnostic pop
  3625. auto res = cli.Get("/hi");
  3626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3627. EXPECT_EQ(StatusCode::OK_200, res->status);
  3628. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3629. }
  3630. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3631. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3632. Server svr;
  3633. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3634. res.set_content("Hello World!", "text/plain");
  3635. });
  3636. auto port = svr.bind_to_any_port("127.0.0.1");
  3637. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3638. auto se = detail::scope_exit([&] {
  3639. svr.stop();
  3640. thread.join();
  3641. ASSERT_FALSE(svr.is_running());
  3642. });
  3643. svr.wait_until_ready();
  3644. Client cli("127.0.0.1", port);
  3645. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3646. cli.set_connection_timeout(1);
  3647. auto res = cli.Get("/hi");
  3648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3649. EXPECT_EQ(StatusCode::OK_200, res->status);
  3650. }
  3651. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3652. auto host = "httpbingo.org";
  3653. auto path = std::string{"/absolute-redirect/3"};
  3654. #ifdef CPPHTTPLIB_SSL_ENABLED
  3655. SSLClient cli(host);
  3656. #else
  3657. Client cli(host);
  3658. #endif
  3659. cli.set_follow_location(true);
  3660. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3661. SKIP_ON_GATEWAY_ERROR(res);
  3662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3663. EXPECT_EQ(StatusCode::OK_200, res->status);
  3664. }
  3665. TEST(RedirectTest, Redirect_Online) {
  3666. auto host = "httpbingo.org";
  3667. auto path = std::string{"/redirect/3"};
  3668. #ifdef CPPHTTPLIB_SSL_ENABLED
  3669. SSLClient cli(host);
  3670. #else
  3671. Client cli(host);
  3672. #endif
  3673. cli.set_follow_location(true);
  3674. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3675. SKIP_ON_GATEWAY_ERROR(res);
  3676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3677. EXPECT_EQ(StatusCode::OK_200, res->status);
  3678. }
  3679. TEST(RelativeRedirectTest, Redirect_Online) {
  3680. auto host = "httpbingo.org";
  3681. auto path = std::string{"/relative-redirect/3"};
  3682. #ifdef CPPHTTPLIB_SSL_ENABLED
  3683. SSLClient cli(host);
  3684. #else
  3685. Client cli(host);
  3686. #endif
  3687. cli.set_follow_location(true);
  3688. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3689. SKIP_ON_GATEWAY_ERROR(res);
  3690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. }
  3693. TEST(TooManyRedirectTest, Redirect_Online) {
  3694. auto host = "httpbingo.org";
  3695. auto path = std::string{"/redirect/21"};
  3696. #ifdef CPPHTTPLIB_SSL_ENABLED
  3697. SSLClient cli(host);
  3698. #else
  3699. Client cli(host);
  3700. #endif
  3701. cli.set_follow_location(true);
  3702. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  3703. SKIP_ON_GATEWAY_ERROR(res);
  3704. ASSERT_TRUE(!res);
  3705. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3706. }
  3707. #ifdef CPPHTTPLIB_SSL_ENABLED
  3708. TEST(YahooRedirectTest, Redirect_Online) {
  3709. Client cli("yahoo.com");
  3710. auto res = cli.Get("/");
  3711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3712. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3713. cli.set_follow_location(true);
  3714. res = cli.Get("/");
  3715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3716. EXPECT_EQ(StatusCode::OK_200, res->status);
  3717. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3718. }
  3719. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3720. #define REDIR_HOST "httpbingo.org"
  3721. #define REDIR_PATH "/redirect-to"
  3722. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3723. SSLClient cli(REDIR_HOST);
  3724. cli.set_follow_location(true);
  3725. auto res = retry_gateway_errors([&] {
  3726. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3727. });
  3728. SKIP_ON_GATEWAY_ERROR(res);
  3729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3730. EXPECT_EQ(StatusCode::OK_200, res->status);
  3731. }
  3732. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3733. SSLClient cli(REDIR_HOST);
  3734. cli.set_follow_location(true);
  3735. Params params;
  3736. params.emplace("url", "http://example.com");
  3737. params.emplace("status_code", "302");
  3738. auto res = retry_gateway_errors(
  3739. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  3740. SKIP_ON_GATEWAY_ERROR(res);
  3741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3742. EXPECT_EQ(StatusCode::OK_200, res->status);
  3743. }
  3744. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3745. SSLClient cli(REDIR_HOST);
  3746. cli.set_follow_location(true);
  3747. Params params;
  3748. params.emplace("url", "http://example.com");
  3749. auto res = retry_gateway_errors([&] {
  3750. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3751. });
  3752. SKIP_ON_GATEWAY_ERROR(res);
  3753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3754. EXPECT_EQ(StatusCode::OK_200, res->status);
  3755. }
  3756. TEST(UrlWithSpace, Redirect_Online) {
  3757. SSLClient cli("edge.forgecdn.net");
  3758. cli.set_follow_location(true);
  3759. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3761. EXPECT_EQ(StatusCode::OK_200, res->status);
  3762. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3763. }
  3764. #endif
  3765. #if !defined(_WIN32) && !defined(_WIN64)
  3766. TEST(ReceiveSignals, Signal) {
  3767. auto setupSignalHandlers = []() {
  3768. struct sigaction act;
  3769. sigemptyset(&act.sa_mask);
  3770. act.sa_flags = SA_SIGINFO;
  3771. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3772. switch (sig) {
  3773. case SIGINT:
  3774. default: break;
  3775. }
  3776. };
  3777. ::sigaction(SIGINT, &act, nullptr);
  3778. };
  3779. Server svr;
  3780. int port = 0;
  3781. auto thread = std::thread([&]() {
  3782. setupSignalHandlers();
  3783. port = svr.bind_to_any_port(HOST);
  3784. svr.listen_after_bind();
  3785. });
  3786. auto se = detail::scope_exit([&] {
  3787. svr.stop();
  3788. thread.join();
  3789. ASSERT_FALSE(svr.is_running());
  3790. });
  3791. svr.wait_until_ready();
  3792. ASSERT_TRUE(svr.is_running());
  3793. pthread_kill(thread.native_handle(), SIGINT);
  3794. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3795. ASSERT_TRUE(svr.is_running());
  3796. }
  3797. #endif
  3798. TEST(RedirectToDifferentPort, Redirect) {
  3799. Server svr1;
  3800. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3801. res.set_content("Hello World!", "text/plain");
  3802. });
  3803. int svr1_port = 0;
  3804. auto thread1 = std::thread([&]() {
  3805. svr1_port = svr1.bind_to_any_port(HOST);
  3806. svr1.listen_after_bind();
  3807. });
  3808. Server svr2;
  3809. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3810. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3811. });
  3812. int svr2_port = 0;
  3813. auto thread2 = std::thread([&]() {
  3814. svr2_port = svr2.bind_to_any_port(HOST);
  3815. svr2.listen_after_bind();
  3816. });
  3817. auto se = detail::scope_exit([&] {
  3818. svr2.stop();
  3819. thread2.join();
  3820. svr1.stop();
  3821. thread1.join();
  3822. ASSERT_FALSE(svr2.is_running());
  3823. ASSERT_FALSE(svr1.is_running());
  3824. });
  3825. svr1.wait_until_ready();
  3826. svr2.wait_until_ready();
  3827. Client cli("localhost", svr2_port);
  3828. cli.set_follow_location(true);
  3829. auto res = cli.Get("/2");
  3830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3831. EXPECT_EQ(StatusCode::OK_200, res->status);
  3832. EXPECT_EQ("Hello World!", res->body);
  3833. }
  3834. // GET /redir on one server redirects to /target on another port, so the
  3835. // client follows it with a new client.
  3836. static Result
  3837. GetThroughRedirectToDifferentPort(Server::Handler target,
  3838. const std::function<void(Client &)> &setup,
  3839. const Headers &headers = Headers()) {
  3840. Server target_svr;
  3841. target_svr.Get("/target", target);
  3842. int target_port = 0;
  3843. auto target_thread = std::thread([&]() {
  3844. target_port = target_svr.bind_to_any_port(HOST);
  3845. target_svr.listen_after_bind();
  3846. });
  3847. Server origin_svr;
  3848. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3849. res.set_redirect(
  3850. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3851. });
  3852. int origin_port = 0;
  3853. auto origin_thread = std::thread([&]() {
  3854. origin_port = origin_svr.bind_to_any_port(HOST);
  3855. origin_svr.listen_after_bind();
  3856. });
  3857. auto se = detail::scope_exit([&] {
  3858. origin_svr.stop();
  3859. origin_thread.join();
  3860. target_svr.stop();
  3861. target_thread.join();
  3862. });
  3863. target_svr.wait_until_ready();
  3864. origin_svr.wait_until_ready();
  3865. Client cli("localhost", origin_port);
  3866. cli.set_follow_location(true);
  3867. setup(cli);
  3868. return cli.Get("/redir", headers);
  3869. }
  3870. static void
  3871. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3872. std::string captured_authorization;
  3873. auto result = GetThroughRedirectToDifferentPort(
  3874. [&](const Request &req, Response &res) {
  3875. captured_authorization = req.get_header_value("Authorization");
  3876. res.set_content("OK", "text/plain");
  3877. },
  3878. set_auth);
  3879. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3880. EXPECT_EQ(StatusCode::OK_200, result->status);
  3881. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3882. EXPECT_TRUE(captured_authorization.empty());
  3883. }
  3884. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3885. TestDoNotForwardCredentialsOnRedirect(
  3886. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3887. }
  3888. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3889. TestDoNotForwardCredentialsOnRedirect(
  3890. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3891. }
  3892. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3893. std::string captured_cookie;
  3894. auto result = GetThroughRedirectToDifferentPort(
  3895. [&](const Request &req, Response &res) {
  3896. captured_cookie = req.get_header_value("Cookie");
  3897. res.set_content("OK", "text/plain");
  3898. },
  3899. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3900. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3901. EXPECT_EQ(StatusCode::OK_200, result->status);
  3902. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3903. EXPECT_TRUE(captured_cookie.empty());
  3904. }
  3905. TEST(RedirectToSamePort, ForwardCookie) {
  3906. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3907. // header so that ordinary session flows keep working.
  3908. Server svr;
  3909. std::string captured_cookie;
  3910. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3911. res.set_redirect("/target", 302);
  3912. });
  3913. svr.Get("/target", [&](const Request &req, Response &res) {
  3914. captured_cookie = req.get_header_value("Cookie");
  3915. res.set_content("OK", "text/plain");
  3916. });
  3917. auto port = svr.bind_to_any_port(HOST);
  3918. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3919. auto se = detail::scope_exit([&] {
  3920. svr.stop();
  3921. thread.join();
  3922. ASSERT_FALSE(svr.is_running());
  3923. });
  3924. svr.wait_until_ready();
  3925. Client cli(HOST, port);
  3926. cli.set_follow_location(true);
  3927. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3928. auto res = cli.Get("/redir", headers);
  3929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3930. EXPECT_EQ(StatusCode::OK_200, res->status);
  3931. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3932. }
  3933. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3934. // The Location alone names the next target, on any origin.
  3935. Server target_svr;
  3936. std::string cross_target;
  3937. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3938. cross_target = req.target;
  3939. res.set_content("OK", "text/plain");
  3940. });
  3941. auto target_port = target_svr.bind_to_any_port(HOST);
  3942. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3943. Server origin_svr;
  3944. std::string same_target;
  3945. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3946. res.set_redirect(
  3947. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3948. });
  3949. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3950. res.set_redirect("/landing", 302);
  3951. });
  3952. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3953. same_target = req.target;
  3954. res.set_content("OK", "text/plain");
  3955. });
  3956. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3957. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3958. auto se = detail::scope_exit([&] {
  3959. origin_svr.stop();
  3960. origin_thread.join();
  3961. target_svr.stop();
  3962. target_thread.join();
  3963. });
  3964. target_svr.wait_until_ready();
  3965. origin_svr.wait_until_ready();
  3966. Client cli("localhost", origin_port);
  3967. cli.set_follow_location(true);
  3968. Request req;
  3969. req.method = "GET";
  3970. req.params = {{"api_key", "SECRET"}};
  3971. req.path = "/cross";
  3972. auto res = cli.send(req);
  3973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3974. EXPECT_EQ("/landing", cross_target);
  3975. req.path = "/same";
  3976. res = cli.send(req);
  3977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3978. EXPECT_EQ("/landing", same_target);
  3979. }
  3980. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3981. std::string authorization;
  3982. std::string trace_id;
  3983. auto result = GetThroughRedirectToDifferentPort(
  3984. [&](const Request &req, Response &res) {
  3985. authorization = req.get_header_value("Authorization");
  3986. trace_id = req.get_header_value("X-Trace-Id");
  3987. res.set_content("OK", "text/plain");
  3988. },
  3989. [](Client &cli) {
  3990. cli.set_default_headers(
  3991. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3992. });
  3993. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3994. EXPECT_EQ(StatusCode::OK_200, result->status);
  3995. // Like a header given with the request, a default one goes along unless it
  3996. // carries credentials (RFC 9110 15.4).
  3997. EXPECT_TRUE(authorization.empty());
  3998. EXPECT_EQ("42", trace_id);
  3999. }
  4000. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  4001. auto result = GetThroughRedirectToDifferentPort(
  4002. [](const Request &, Response &res) {
  4003. res.set_content(std::string(2048, 'x'), "text/plain");
  4004. },
  4005. [](Client &cli) { cli.set_payload_max_length(1024); });
  4006. EXPECT_FALSE(result);
  4007. }
  4008. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  4009. auto result = GetThroughRedirectToDifferentPort(
  4010. [](const Request &req, Response &res) {
  4011. // Answer after a second, or once the client gives up.
  4012. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  4013. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4014. }
  4015. res.set_content("late", "text/plain");
  4016. },
  4017. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  4018. ASSERT_FALSE(result);
  4019. EXPECT_EQ(Error::Read, result.error());
  4020. }
  4021. #ifdef CPPHTTPLIB_SSL_ENABLED
  4022. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  4023. auto result = GetThroughRedirectToDifferentPort(
  4024. [](const Request &, Response &res) {
  4025. res.status = StatusCode::Unauthorized_401;
  4026. res.set_header("WWW-Authenticate",
  4027. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  4028. },
  4029. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  4030. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4031. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  4032. }
  4033. #endif
  4034. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  4035. Server svr;
  4036. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4037. // Port number that overflows int — should not crash
  4038. res.set_redirect("http://localhost:99999999999999999999/target");
  4039. });
  4040. auto port = svr.bind_to_any_port(HOST);
  4041. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4042. auto se = detail::scope_exit([&] {
  4043. svr.stop();
  4044. thread.join();
  4045. ASSERT_FALSE(svr.is_running());
  4046. });
  4047. svr.wait_until_ready();
  4048. Client cli(HOST, port);
  4049. cli.set_follow_location(true);
  4050. auto res = cli.Get("/redir");
  4051. // Should fail gracefully, not crash (no valid response due to bad port)
  4052. EXPECT_FALSE(res);
  4053. }
  4054. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  4055. Server svr;
  4056. auto port = svr.bind_to_any_port(HOST);
  4057. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4058. // The server's own port followed by junk must not be followed
  4059. res.set_redirect("http://" + std::string(HOST) + ":" +
  4060. std::to_string(port) + "junk/target");
  4061. });
  4062. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4063. res.set_content("target", "text/plain");
  4064. });
  4065. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4066. auto se = detail::scope_exit([&] {
  4067. svr.stop();
  4068. thread.join();
  4069. ASSERT_FALSE(svr.is_running());
  4070. });
  4071. svr.wait_until_ready();
  4072. Client cli(HOST, port);
  4073. cli.set_follow_location(true);
  4074. auto res = cli.Get("/redir");
  4075. EXPECT_FALSE(res);
  4076. }
  4077. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4078. Server target_svr;
  4079. std::atomic<int> target_hits{0};
  4080. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4081. target_hits++;
  4082. res.set_content("target", "text/plain");
  4083. });
  4084. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4085. res.set_content("target", "text/plain");
  4086. });
  4087. int target_port = 0;
  4088. auto target_thread = std::thread([&]() {
  4089. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4090. target_svr.listen_after_bind();
  4091. });
  4092. Server origin_svr;
  4093. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4094. res.set_redirect(req.get_param_value("to"));
  4095. });
  4096. int origin_port = 0;
  4097. auto origin_thread = std::thread([&]() {
  4098. origin_port = origin_svr.bind_to_any_port(HOST);
  4099. origin_svr.listen_after_bind();
  4100. });
  4101. auto se = detail::scope_exit([&] {
  4102. origin_svr.stop();
  4103. origin_thread.join();
  4104. target_svr.stop();
  4105. target_thread.join();
  4106. ASSERT_FALSE(origin_svr.is_running());
  4107. ASSERT_FALSE(target_svr.is_running());
  4108. });
  4109. target_svr.wait_until_ready();
  4110. origin_svr.wait_until_ready();
  4111. auto port = std::to_string(target_port);
  4112. for (const auto &to :
  4113. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4114. Client cli(HOST, origin_port);
  4115. cli.set_follow_location(true);
  4116. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4117. EXPECT_FALSE(res) << to;
  4118. }
  4119. EXPECT_EQ(0, target_hits);
  4120. Client cli(HOST, origin_port);
  4121. cli.set_follow_location(true);
  4122. auto res = cli.Get("/redir?to=" +
  4123. encode_query_component("//127.0.0.1:" + port + "/target"));
  4124. ASSERT_TRUE(res) << to_string(res.error());
  4125. EXPECT_EQ(StatusCode::OK_200, res->status);
  4126. EXPECT_EQ("target", res->body);
  4127. }
  4128. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4129. Server svr;
  4130. std::atomic<bool> followed{false};
  4131. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4132. res.status = StatusCode::NotModified_304;
  4133. res.set_header("Location", "/target");
  4134. });
  4135. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4136. res.status = StatusCode::UseProxy_305;
  4137. res.set_header("Location", "/target");
  4138. });
  4139. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4140. followed = true;
  4141. res.set_content("target", "text/plain");
  4142. });
  4143. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4144. auto se = detail::scope_exit([&] {
  4145. svr.stop();
  4146. th.join();
  4147. ASSERT_FALSE(svr.is_running());
  4148. });
  4149. svr.wait_until_ready();
  4150. Client cli("localhost", PORT);
  4151. cli.set_follow_location(true);
  4152. auto res = cli.Get("/304");
  4153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4154. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4155. res = cli.Get("/305");
  4156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4157. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4158. EXPECT_FALSE(followed);
  4159. }
  4160. TEST(RedirectFromPageWithContent, Redirect) {
  4161. Server svr;
  4162. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4163. res.set_content("___", "text/plain");
  4164. res.set_redirect("/2");
  4165. });
  4166. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4167. res.set_content("Hello World!", "text/plain");
  4168. });
  4169. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4170. auto se = detail::scope_exit([&] {
  4171. svr.stop();
  4172. th.join();
  4173. ASSERT_FALSE(svr.is_running());
  4174. });
  4175. svr.wait_until_ready();
  4176. {
  4177. Client cli("localhost", PORT);
  4178. cli.set_follow_location(true);
  4179. std::string body;
  4180. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4181. body.append(data, data_length);
  4182. return true;
  4183. });
  4184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4185. EXPECT_EQ(StatusCode::OK_200, res->status);
  4186. EXPECT_EQ("Hello World!", body);
  4187. }
  4188. {
  4189. Client cli("localhost", PORT);
  4190. std::string body;
  4191. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4192. body.append(data, data_length);
  4193. return true;
  4194. });
  4195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4196. EXPECT_EQ(StatusCode::Found_302, res->status);
  4197. EXPECT_EQ("___", body);
  4198. }
  4199. }
  4200. // A server can close the connection after a request with "Connection: close"
  4201. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4202. // redirected request must go out on a new connection.
  4203. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4204. #ifndef _WIN32
  4205. signal(SIGPIPE, SIG_IGN);
  4206. #endif
  4207. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4208. default_socket_options(srv);
  4209. sockaddr_in addr{};
  4210. addr.sin_family = AF_INET;
  4211. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4212. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4213. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4214. ASSERT_EQ(0, ::listen(srv, 2));
  4215. auto send_text = [](socket_t sock, const std::string &text) {
  4216. ::send(sock,
  4217. #ifdef _WIN32
  4218. static_cast<const char *>(text.c_str()),
  4219. static_cast<int>(text.size()),
  4220. #else
  4221. text.c_str(), text.size(),
  4222. #endif
  4223. 0);
  4224. };
  4225. auto reused = false;
  4226. auto server_thread = std::thread([&] {
  4227. char buf[4096];
  4228. auto first = ::accept(srv, nullptr, nullptr);
  4229. if (first == INVALID_SOCKET) { return; }
  4230. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4231. ::recv(first, buf, sizeof(buf), 0);
  4232. send_text(
  4233. first,
  4234. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4235. auto next = first;
  4236. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4237. reused = true;
  4238. } else {
  4239. detail::close_socket(first);
  4240. next = ::accept(srv, nullptr, nullptr);
  4241. if (next == INVALID_SOCKET) { return; }
  4242. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4243. ::recv(next, buf, sizeof(buf), 0);
  4244. }
  4245. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4246. "Connection: close\r\n\r\nok");
  4247. detail::close_socket(next);
  4248. });
  4249. Client cli("127.0.0.1", PORT + 2);
  4250. cli.set_follow_location(true);
  4251. cli.set_read_timeout(5, 0);
  4252. auto res = cli.Get("/1");
  4253. server_thread.join();
  4254. detail::close_socket(srv);
  4255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4256. EXPECT_EQ(StatusCode::OK_200, res->status);
  4257. EXPECT_EQ("ok", res->body);
  4258. EXPECT_FALSE(reused);
  4259. }
  4260. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4261. Server svr;
  4262. auto port_str = std::to_string(PORT);
  4263. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4264. auto expected_host = "[::1]:" + port_str;
  4265. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4266. res.set_content("___", "text/plain");
  4267. // res.set_redirect("/2");
  4268. res.set_redirect(redirect_url);
  4269. });
  4270. svr.Get("/2", [&](const Request &req, Response &res) {
  4271. auto host_header = req.headers.find("Host");
  4272. ASSERT_TRUE(host_header != req.headers.end());
  4273. EXPECT_EQ(expected_host, host_header->second);
  4274. res.set_content("Hello World!", "text/plain");
  4275. });
  4276. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4277. auto se = detail::scope_exit([&] {
  4278. svr.stop();
  4279. th.join();
  4280. ASSERT_FALSE(svr.is_running());
  4281. });
  4282. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4283. // actually starts anything, so the condition !svr.is_running() will
  4284. // always remain true, and the loop never stops.
  4285. // This basically counts how many milliseconds have passed since the
  4286. // call to svr.listen(), and if after 5 seconds nothing started yet
  4287. // aborts the test.
  4288. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4289. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4290. ASSERT_LT(milliseconds, 5000U);
  4291. }
  4292. {
  4293. Client cli("::1", PORT);
  4294. cli.set_follow_location(true);
  4295. std::string body;
  4296. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4297. body.append(data, data_length);
  4298. return true;
  4299. });
  4300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4301. EXPECT_EQ(StatusCode::OK_200, res->status);
  4302. EXPECT_EQ("Hello World!", body);
  4303. }
  4304. {
  4305. Client cli("::1", PORT);
  4306. std::string body;
  4307. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4308. body.append(data, data_length);
  4309. return true;
  4310. });
  4311. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4312. EXPECT_EQ(StatusCode::Found_302, res->status);
  4313. EXPECT_EQ("___", body);
  4314. }
  4315. }
  4316. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4317. Server svr;
  4318. svr.Get("/foo", [](const Request &req, Response &res) {
  4319. auto a = req.params.find("a");
  4320. if (a != req.params.end()) {
  4321. res.set_content((*a).second, "text/plain");
  4322. res.status = StatusCode::OK_200;
  4323. } else {
  4324. res.status = StatusCode::BadRequest_400;
  4325. }
  4326. });
  4327. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4328. auto se = detail::scope_exit([&] {
  4329. svr.stop();
  4330. thread.join();
  4331. ASSERT_FALSE(svr.is_running());
  4332. });
  4333. svr.wait_until_ready();
  4334. {
  4335. Client cli(HOST, PORT);
  4336. cli.set_path_encode(false);
  4337. auto res = cli.Get("/foo?a=explicitly+encoded");
  4338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4339. EXPECT_EQ(StatusCode::OK_200, res->status);
  4340. // This expects it back with a space, as the `+` won't have been
  4341. // url-encoded, and server-side the params get decoded turning `+`
  4342. // into spaces.
  4343. EXPECT_EQ("explicitly encoded", res->body);
  4344. }
  4345. }
  4346. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4347. // When path encoding is disabled the client must transmit the supplied
  4348. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4349. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4350. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4351. // than a space (0x20). Assert on the raw wire target to catch this.
  4352. Server svr;
  4353. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4354. svr.Get("/foo", [&](const Request &req, Response &res) {
  4355. EXPECT_EQ(expected_target, req.target);
  4356. res.status = StatusCode::OK_200;
  4357. });
  4358. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4359. auto se = detail::scope_exit([&] {
  4360. svr.stop();
  4361. thread.join();
  4362. ASSERT_FALSE(svr.is_running());
  4363. });
  4364. svr.wait_until_ready();
  4365. {
  4366. Client cli(HOST, PORT);
  4367. cli.set_path_encode(false);
  4368. auto res = cli.Get(expected_target.c_str());
  4369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4370. EXPECT_EQ(StatusCode::OK_200, res->status);
  4371. }
  4372. }
  4373. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4374. // `open_stream()` used to skip the path encoding that the buffered send
  4375. // path applies, so the same `path` produced different bytes in the request
  4376. // line depending on which API was used. Assert the two agree.
  4377. Server svr;
  4378. std::string target;
  4379. svr.Get(".*", [&](const Request &req, Response &res) {
  4380. target = req.target;
  4381. res.status = StatusCode::OK_200;
  4382. });
  4383. auto port = svr.bind_to_any_port(HOST);
  4384. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4385. auto se = detail::scope_exit([&] {
  4386. svr.stop();
  4387. thread.join();
  4388. ASSERT_FALSE(svr.is_running());
  4389. });
  4390. svr.wait_until_ready();
  4391. struct {
  4392. const char *path;
  4393. const char *expected;
  4394. } cases[] = {
  4395. {"/a b?x=1", "/a%20b?x=1"},
  4396. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4397. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4398. };
  4399. for (const auto &c : cases) {
  4400. Client cli(HOST, port);
  4401. target.clear();
  4402. auto res = cli.Get(c.path);
  4403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4404. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4405. auto buffered_target = target;
  4406. target.clear();
  4407. auto handle = cli.open_stream("GET", c.path);
  4408. EXPECT_TRUE(handle.is_valid())
  4409. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4410. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4411. }
  4412. }
  4413. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4414. // The `set_path_encode(false)` contract — transmit the supplied target
  4415. // verbatim — must hold for the streaming API too.
  4416. Server svr;
  4417. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4418. std::string target;
  4419. svr.Get("/foo", [&](const Request &req, Response &res) {
  4420. target = req.target;
  4421. res.status = StatusCode::OK_200;
  4422. });
  4423. auto port = svr.bind_to_any_port(HOST);
  4424. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4425. auto se = detail::scope_exit([&] {
  4426. svr.stop();
  4427. thread.join();
  4428. ASSERT_FALSE(svr.is_running());
  4429. });
  4430. svr.wait_until_ready();
  4431. {
  4432. Client cli(HOST, port);
  4433. cli.set_path_encode(false);
  4434. auto handle = cli.open_stream("GET", expected_target);
  4435. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4436. EXPECT_EQ(expected_target, target);
  4437. }
  4438. }
  4439. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4440. // With path encoding enabled a CR/LF in the target is percent-encoded
  4441. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4442. // write_request_line still backstops `set_path_encode(false)`, which is
  4443. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4444. Server svr;
  4445. // Captured before routing: the decoded path contains a newline, which a
  4446. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4447. std::string target;
  4448. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4449. target = req.target;
  4450. res.status = StatusCode::OK_200;
  4451. return Server::HandlerResponse::Handled;
  4452. });
  4453. auto port = svr.bind_to_any_port(HOST);
  4454. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4455. auto se = detail::scope_exit([&] {
  4456. svr.stop();
  4457. thread.join();
  4458. ASSERT_FALSE(svr.is_running());
  4459. });
  4460. svr.wait_until_ready();
  4461. {
  4462. Client cli(HOST, port);
  4463. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4464. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4465. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4466. }
  4467. }
  4468. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4469. // Every control character is percent-encoded, not just CR/LF, so the target
  4470. // passes the request-target check in write_request_line.
  4471. Server svr;
  4472. std::string target;
  4473. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4474. target = req.target;
  4475. res.status = StatusCode::OK_200;
  4476. return Server::HandlerResponse::Handled;
  4477. });
  4478. auto port = svr.bind_to_any_port(HOST);
  4479. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4480. auto se = detail::scope_exit([&] {
  4481. svr.stop();
  4482. thread.join();
  4483. ASSERT_FALSE(svr.is_running());
  4484. });
  4485. svr.wait_until_ready();
  4486. {
  4487. Client cli(HOST, port);
  4488. auto res = cli.Get("/a\tb\x1b\x7f");
  4489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4490. EXPECT_EQ("/a%09b%1B%7F", target);
  4491. }
  4492. }
  4493. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4494. // Nothing may reach the wire: a raw CR/LF target would split the request
  4495. // line and inject headers.
  4496. Server svr;
  4497. // Pre-routing so that "not called" means nothing reached the server at all,
  4498. // rather than merely failing to match a handler pattern.
  4499. auto handler_called = false;
  4500. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4501. handler_called = true;
  4502. res.status = StatusCode::OK_200;
  4503. return Server::HandlerResponse::Handled;
  4504. });
  4505. auto port = svr.bind_to_any_port(HOST);
  4506. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4507. auto se = detail::scope_exit([&] {
  4508. svr.stop();
  4509. thread.join();
  4510. ASSERT_FALSE(svr.is_running());
  4511. });
  4512. svr.wait_until_ready();
  4513. {
  4514. Client cli(HOST, port);
  4515. cli.set_path_encode(false);
  4516. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4517. EXPECT_FALSE(handle.is_valid());
  4518. EXPECT_EQ(Error::Write, handle.error);
  4519. EXPECT_FALSE(handler_called);
  4520. }
  4521. }
  4522. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4523. // Which of the two branches runs is decided by whether the query component
  4524. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4525. // an empty query and must still fall back to building one from
  4526. // `req.params`, while a non-empty query must win over `req.params`.
  4527. Server svr;
  4528. std::string target;
  4529. svr.Get("/foo", [&](const Request &req, Response &res) {
  4530. target = req.target;
  4531. res.status = StatusCode::OK_200;
  4532. });
  4533. auto port = svr.bind_to_any_port(HOST);
  4534. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4535. auto se = detail::scope_exit([&] {
  4536. svr.stop();
  4537. thread.join();
  4538. ASSERT_FALSE(svr.is_running());
  4539. });
  4540. svr.wait_until_ready();
  4541. {
  4542. // Trailing `?` -> empty query component -> `req.params` is used.
  4543. Client cli(HOST, port);
  4544. Request req;
  4545. req.method = "GET";
  4546. req.path = "/foo?";
  4547. req.params.emplace("a", "1");
  4548. target.clear();
  4549. auto res = cli.send(req);
  4550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4551. EXPECT_EQ("/foo?a=1", target);
  4552. }
  4553. {
  4554. // Non-empty query in `req.path` -> `req.params` is not appended.
  4555. Client cli(HOST, port);
  4556. Request req;
  4557. req.method = "GET";
  4558. req.path = "/foo?b=2";
  4559. req.params.emplace("a", "1");
  4560. target.clear();
  4561. auto res = cli.send(req);
  4562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4563. EXPECT_EQ("/foo?b=2", target);
  4564. }
  4565. }
  4566. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4567. Server svr;
  4568. svr.Get("/", [](const Request &req, Response &) {
  4569. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4570. });
  4571. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4572. auto se = detail::scope_exit([&] {
  4573. svr.stop();
  4574. thread.join();
  4575. ASSERT_FALSE(svr.is_running());
  4576. });
  4577. svr.wait_until_ready();
  4578. {
  4579. Client cli(HOST, PORT);
  4580. cli.set_path_encode(false);
  4581. auto res = cli.Get("/?something=%0A");
  4582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4583. EXPECT_EQ(StatusCode::OK_200, res->status);
  4584. }
  4585. }
  4586. TEST(BindServerTest, BindDualStack) {
  4587. Server svr;
  4588. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4589. res.set_content("Hello World!", "text/plain");
  4590. });
  4591. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4592. auto se = detail::scope_exit([&] {
  4593. svr.stop();
  4594. thread.join();
  4595. ASSERT_FALSE(svr.is_running());
  4596. });
  4597. svr.wait_until_ready();
  4598. {
  4599. Client cli("127.0.0.1", PORT);
  4600. auto res = cli.Get("/1");
  4601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4602. EXPECT_EQ(StatusCode::OK_200, res->status);
  4603. EXPECT_EQ("Hello World!", res->body);
  4604. }
  4605. {
  4606. Client cli("::1", PORT);
  4607. auto res = cli.Get("/1");
  4608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4609. EXPECT_EQ(StatusCode::OK_200, res->status);
  4610. EXPECT_EQ("Hello World!", res->body);
  4611. }
  4612. }
  4613. TEST(BindServerTest, BindAndListenSeparately) {
  4614. Server svr;
  4615. int port = svr.bind_to_any_port("0.0.0.0");
  4616. ASSERT_TRUE(svr.is_valid());
  4617. ASSERT_TRUE(port > 0);
  4618. svr.stop();
  4619. }
  4620. // Reports whether anything is still listening on a loopback port. A plain
  4621. // connect() is used instead of a Client request because a socket left bound by
  4622. // mistake accepts the connection into its backlog and never answers, which
  4623. // would hang the test instead of failing it.
  4624. static bool is_loopback_port_accepting(int port) {
  4625. sockaddr_in addr{};
  4626. addr.sin_family = AF_INET;
  4627. addr.sin_port = htons(static_cast<uint16_t>(port));
  4628. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4629. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4630. EXPECT_NE(sock, INVALID_SOCKET);
  4631. if (sock == INVALID_SOCKET) { return false; }
  4632. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4633. static_cast<socklen_t>(sizeof(addr)));
  4634. detail::close_socket(sock);
  4635. return ret == 0;
  4636. }
  4637. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4638. Server svr;
  4639. auto port = svr.bind_to_any_port("127.0.0.1");
  4640. ASSERT_TRUE(port > 0);
  4641. svr.stop();
  4642. // bind_to_any_port() already called listen(2), so until stop() closed the
  4643. // descriptor the port kept accepting connections into the backlog. ASSERT
  4644. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4645. // below blocks forever in the accept loop.
  4646. ASSERT_FALSE(is_loopback_port_accepting(port));
  4647. // Nothing is left to accept on, so listen_after_bind() must report failure
  4648. // instead of returning success without ever serving.
  4649. EXPECT_FALSE(svr.listen_after_bind());
  4650. // The failed listen marks the server decommissioned, so a waiter returns
  4651. // instead of spinning forever.
  4652. svr.wait_until_ready();
  4653. }
  4654. #ifdef CPPHTTPLIB_SSL_ENABLED
  4655. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4657. CLIENT_CA_CERT_DIR);
  4658. int port = svr.bind_to_any_port("0.0.0.0");
  4659. ASSERT_TRUE(svr.is_valid());
  4660. ASSERT_TRUE(port > 0);
  4661. svr.stop();
  4662. }
  4663. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4664. // or a rejected CustomRoute() registration would not stop the server binding.
  4665. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4666. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4667. CLIENT_CA_CERT_DIR);
  4668. ASSERT_TRUE(svr.is_valid());
  4669. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4670. EXPECT_FALSE(svr.is_valid());
  4671. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4672. }
  4673. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4674. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4675. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4676. int port = svr.bind_to_any_port("0.0.0.0");
  4677. ASSERT_TRUE(svr.is_valid());
  4678. ASSERT_TRUE(port > 0);
  4679. svr.stop();
  4680. }
  4681. TEST(BindServerTest, UpdateCertsPem) {
  4682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4683. int port = svr.bind_to_any_port("0.0.0.0");
  4684. ASSERT_TRUE(svr.is_valid());
  4685. ASSERT_TRUE(port > 0);
  4686. // Read PEM files
  4687. std::string cert_pem, key_pem, ca_pem;
  4688. read_file(SERVER_CERT_FILE, cert_pem);
  4689. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4690. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4691. // Update server certificates using PEM API
  4692. ASSERT_TRUE(
  4693. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4694. ASSERT_TRUE(svr.is_valid());
  4695. svr.stop();
  4696. }
  4697. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4698. // Start server with client CA (enables client auth)
  4699. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4700. ASSERT_TRUE(svr.is_valid());
  4701. bool handler_called = false;
  4702. svr.Get("/test", [&](const Request &req, Response &res) {
  4703. handler_called = true;
  4704. // Verify client certificate is present
  4705. auto cert = req.peer_cert();
  4706. EXPECT_TRUE(static_cast<bool>(cert));
  4707. res.set_content("ok", "text/plain");
  4708. });
  4709. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4710. auto se = detail::scope_exit([&] {
  4711. svr.stop();
  4712. t.join();
  4713. ASSERT_FALSE(svr.is_running());
  4714. });
  4715. svr.wait_until_ready();
  4716. // Read PEM files
  4717. std::string cert_pem, key_pem, ca_pem;
  4718. read_file(SERVER_CERT_FILE, cert_pem);
  4719. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4720. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4721. // Update server certificates and client CA using PEM API while server running
  4722. ASSERT_TRUE(
  4723. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4724. // Connect with client certificate
  4725. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4726. cli.enable_server_certificate_verification(false);
  4727. cli.set_connection_timeout(30);
  4728. auto res = cli.Get("/test");
  4729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4730. ASSERT_EQ(StatusCode::OK_200, res->status);
  4731. ASSERT_TRUE(handler_called);
  4732. EXPECT_EQ("ok", res->body);
  4733. }
  4734. // Puts a CA that did not sign the client's certificate in the old one's place.
  4735. static bool replace_client_ca(SSLServer &svr) {
  4736. std::string cert_pem, key_pem, ca_pem;
  4737. read_file(SERVER_CERT_FILE, cert_pem);
  4738. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4739. read_file(SERVER_CERT2_FILE, ca_pem);
  4740. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4741. ca_pem.c_str());
  4742. }
  4743. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4744. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4745. ASSERT_TRUE(svr.is_valid());
  4746. svr.Get("/test", [](const Request &, Response &res) {
  4747. res.set_content("ok", "text/plain");
  4748. });
  4749. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4750. auto se = detail::scope_exit([&] {
  4751. svr.stop();
  4752. t.join();
  4753. ASSERT_FALSE(svr.is_running());
  4754. });
  4755. svr.wait_until_ready();
  4756. auto get = [] {
  4757. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4758. cli.enable_server_certificate_verification(false);
  4759. return cli.Get("/test");
  4760. };
  4761. ASSERT_TRUE(get());
  4762. ASSERT_TRUE(replace_client_ca(svr));
  4763. EXPECT_FALSE(get());
  4764. }
  4765. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4766. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4767. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4768. ASSERT_TRUE(svr.is_valid());
  4769. tls::set_verify_callback(svr.tls_context(),
  4770. [](const tls::VerifyContext &) -> bool {
  4771. throw std::runtime_error("verify");
  4772. });
  4773. svr.Get("/test", [](const Request &, Response &res) {
  4774. res.set_content("ok", "text/plain");
  4775. });
  4776. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4777. auto se = detail::scope_exit([&] {
  4778. svr.stop();
  4779. t.join();
  4780. ASSERT_FALSE(svr.is_running());
  4781. });
  4782. svr.wait_until_ready();
  4783. auto get = [] {
  4784. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4785. cli.enable_server_certificate_verification(false);
  4786. return cli.Get("/test");
  4787. };
  4788. EXPECT_FALSE(get());
  4789. // The handshake is over, so an update does not wait for it.
  4790. std::string cert_pem, key_pem;
  4791. read_file(SERVER_CERT_FILE, cert_pem);
  4792. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4793. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4794. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4795. return v.preverify_ok;
  4796. });
  4797. auto res = get();
  4798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4799. EXPECT_EQ("ok", res->body);
  4800. }
  4801. #endif
  4802. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4803. // Sends each request over a new connection with a client certificate,
  4804. // resuming the session of the one before when there is one.
  4805. class ResumingClient {
  4806. public:
  4807. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4808. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4809. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4810. SSL_FILETYPE_PEM);
  4811. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4812. // callback, not through SSL_get1_session().
  4813. SSL_CTX_set_app_data(ctx_, this);
  4814. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4815. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4816. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4817. auto self = static_cast<ResumingClient *>(
  4818. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4819. SSL_SESSION_free(self->session_);
  4820. self->session_ = session;
  4821. return 1; // Keeps the reference
  4822. });
  4823. }
  4824. ~ResumingClient() {
  4825. SSL_SESSION_free(session_);
  4826. SSL_CTX_free(ctx_);
  4827. }
  4828. // Tells whether the request was answered.
  4829. bool get() {
  4830. auto error = Error::Success;
  4831. auto sock = detail::create_client_socket(
  4832. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4833. /*connection_timeout_sec=*/5, 0,
  4834. /*read_timeout_sec=*/5, 0,
  4835. /*write_timeout_sec=*/5, 0, std::string(), error);
  4836. if (sock == INVALID_SOCKET) { return false; }
  4837. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4838. auto ssl = SSL_new(ctx_);
  4839. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4840. SSL_set_fd(ssl, static_cast<int>(sock));
  4841. if (session_) { SSL_set_session(ssl, session_); }
  4842. if (SSL_connect(ssl) != 1) { return false; }
  4843. reused_ = SSL_session_reused(ssl) == 1;
  4844. // Reading the response also takes in a TLS 1.3 session ticket.
  4845. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4846. "Connection: close\r\n\r\n";
  4847. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4848. std::string res;
  4849. char buf[256];
  4850. int n;
  4851. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4852. res.append(buf, static_cast<size_t>(n));
  4853. }
  4854. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4855. SSL_shutdown(ssl);
  4856. return res.find("200 OK") != std::string::npos;
  4857. }
  4858. // Whether the last connection resumed a session
  4859. bool reused() const { return reused_; }
  4860. private:
  4861. SSL_CTX *ctx_;
  4862. SSL_SESSION *session_ = nullptr;
  4863. bool reused_ = false;
  4864. };
  4865. // A client that resumes its session gets through, but not once the client CA
  4866. // has changed, as a resumed session does not show the certificate again.
  4867. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4869. ASSERT_TRUE(svr.is_valid());
  4870. svr.Get("/test", [](const Request &, Response &res) {
  4871. res.set_content("ok", "text/plain");
  4872. });
  4873. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4874. auto se = detail::scope_exit([&] {
  4875. svr.stop();
  4876. t.join();
  4877. ASSERT_FALSE(svr.is_running());
  4878. });
  4879. svr.wait_until_ready();
  4880. ResumingClient cli;
  4881. ASSERT_TRUE(cli.get());
  4882. ASSERT_TRUE(cli.get());
  4883. EXPECT_TRUE(cli.reused());
  4884. ASSERT_TRUE(replace_client_ca(svr));
  4885. EXPECT_FALSE(cli.get());
  4886. }
  4887. // A resumed session does not show the certificate again, so the server does
  4888. // not resume one with a verify callback to run on it.
  4889. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4890. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4891. ASSERT_TRUE(svr.is_valid());
  4892. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4893. return v.preverify_ok;
  4894. });
  4895. svr.Get("/test", [](const Request &, Response &res) {
  4896. res.set_content("ok", "text/plain");
  4897. });
  4898. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4899. auto se = detail::scope_exit([&] {
  4900. svr.stop();
  4901. t.join();
  4902. ASSERT_FALSE(svr.is_running());
  4903. });
  4904. svr.wait_until_ready();
  4905. ResumingClient cli;
  4906. ASSERT_TRUE(cli.get());
  4907. ASSERT_TRUE(cli.get());
  4908. EXPECT_FALSE(cli.reused());
  4909. }
  4910. #endif
  4911. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4912. // wolfSSL shares its session cache between contexts, so a resumed session
  4913. // could carry a client certificate checked against another server's CA, or
  4914. // against a client CA since replaced.
  4915. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4916. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4917. ASSERT_TRUE(svr.is_valid());
  4918. // Trusts a CA that did not sign the client's certificate.
  4919. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4920. ASSERT_TRUE(other.is_valid());
  4921. for (auto s : {&svr, &other}) {
  4922. s->Get("/test", [](const Request &, Response &res) {
  4923. res.set_content("ok", "text/plain");
  4924. });
  4925. }
  4926. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4927. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4928. auto se = detail::scope_exit([&] {
  4929. other.stop();
  4930. svr.stop();
  4931. t2.join();
  4932. t.join();
  4933. });
  4934. svr.wait_until_ready();
  4935. other.wait_until_ready();
  4936. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4937. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4938. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4939. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4940. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4941. ASSERT_EQ(WOLFSSL_SUCCESS,
  4942. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4943. WOLFSSL_FILETYPE_PEM));
  4944. WOLFSSL_SESSION *session = nullptr;
  4945. auto session_se = detail::scope_exit([&] {
  4946. if (session) { wolfSSL_SESSION_free(session); }
  4947. });
  4948. // A request over a new connection, resuming `session` when there is one and
  4949. // keeping the connection's own in its place. Tells whether it was answered.
  4950. auto get = [&](int port) {
  4951. auto error = Error::Success;
  4952. auto sock = detail::create_client_socket(
  4953. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4954. /*connection_timeout_sec=*/5, 0,
  4955. /*read_timeout_sec=*/5, 0,
  4956. /*write_timeout_sec=*/5, 0, std::string(), error);
  4957. if (sock == INVALID_SOCKET) { return false; }
  4958. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4959. auto ssl = wolfSSL_new(ctx);
  4960. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4961. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4962. if (session) { wolfSSL_set_session(ssl, session); }
  4963. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4964. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4965. "Connection: close\r\n\r\n";
  4966. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4967. std::string res;
  4968. char buf[256];
  4969. int n;
  4970. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4971. res.append(buf, static_cast<size_t>(n));
  4972. }
  4973. wolfSSL_shutdown(ssl);
  4974. if (session) { wolfSSL_SESSION_free(session); }
  4975. session = wolfSSL_get1_session(ssl);
  4976. return res.find("200 OK") != std::string::npos;
  4977. };
  4978. ASSERT_TRUE(get(PORT));
  4979. EXPECT_FALSE(get(PORT + 1));
  4980. ASSERT_TRUE(get(PORT));
  4981. ASSERT_TRUE(replace_client_ca(svr));
  4982. EXPECT_FALSE(get(PORT));
  4983. }
  4984. #endif
  4985. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4986. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4987. ASSERT_TRUE(svr.is_valid());
  4988. // Keep-alive parking would wait for the ClientHello without a handshake.
  4989. svr.set_keep_alive_parking(false);
  4990. svr.Get("/test", [](const Request &, Response &res) {
  4991. res.set_content("ok", "text/plain");
  4992. });
  4993. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4994. auto se = detail::scope_exit([&] {
  4995. svr.stop();
  4996. t.join();
  4997. ASSERT_FALSE(svr.is_running());
  4998. });
  4999. svr.wait_until_ready();
  5000. // A connection that sends no ClientHello keeps its handshake in progress,
  5001. // once the server has had a moment to start it.
  5002. auto error = Error::Success;
  5003. auto sock = detail::create_client_socket(
  5004. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5005. /*connection_timeout_sec=*/5, 0,
  5006. /*read_timeout_sec=*/5, 0,
  5007. /*write_timeout_sec=*/5, 0, std::string(), error);
  5008. ASSERT_NE(INVALID_SOCKET, sock);
  5009. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5010. std::string cert_pem, key_pem;
  5011. read_file(SERVER_CERT_FILE, cert_pem);
  5012. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  5013. auto update = std::async(std::launch::async, [&]() {
  5014. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  5015. });
  5016. EXPECT_EQ(std::future_status::timeout,
  5017. update.wait_for(std::chrono::milliseconds(200)));
  5018. detail::close_socket(sock);
  5019. EXPECT_TRUE(update.get());
  5020. SSLClient cli(HOST, PORT);
  5021. cli.enable_server_certificate_verification(false);
  5022. auto res = cli.Get("/test");
  5023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5024. EXPECT_EQ(StatusCode::OK_200, res->status);
  5025. }
  5026. #endif
  5027. TEST(ErrorHandlerTest, ContentLength) {
  5028. Server svr;
  5029. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5030. res.status = StatusCode::OK_200;
  5031. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5032. "text/html"); // <= Content-Length still 13
  5033. });
  5034. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5035. res.set_content("Hello World!\n", "text/plain");
  5036. res.status = 524;
  5037. });
  5038. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5039. auto se = detail::scope_exit([&] {
  5040. svr.stop();
  5041. thread.join();
  5042. ASSERT_FALSE(svr.is_running());
  5043. });
  5044. svr.wait_until_ready();
  5045. {
  5046. Client cli(HOST, PORT);
  5047. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5049. EXPECT_EQ(StatusCode::OK_200, res->status);
  5050. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5051. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5052. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5053. }
  5054. }
  5055. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5056. TEST(ExceptionTest, WithoutExceptionHandler) {
  5057. Server svr;
  5058. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5059. throw std::runtime_error("exception...");
  5060. });
  5061. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5062. throw std::runtime_error("exception\r\n...");
  5063. });
  5064. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5065. auto se = detail::scope_exit([&] {
  5066. svr.stop();
  5067. listen_thread.join();
  5068. ASSERT_FALSE(svr.is_running());
  5069. });
  5070. svr.wait_until_ready();
  5071. Client cli("localhost", PORT);
  5072. {
  5073. auto res = cli.Get("/exception");
  5074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5075. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5076. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5077. }
  5078. {
  5079. auto res = cli.Get("/unknown");
  5080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5081. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5082. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5083. }
  5084. }
  5085. TEST(ExceptionTest, WithExceptionHandler) {
  5086. Server svr;
  5087. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5088. std::exception_ptr ep) {
  5089. EXPECT_FALSE(ep == nullptr);
  5090. try {
  5091. std::rethrow_exception(ep);
  5092. } catch (std::exception &e) {
  5093. EXPECT_EQ("abc", std::string(e.what()));
  5094. } catch (...) {}
  5095. res.status = StatusCode::InternalServerError_500;
  5096. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5097. "text/html"); // <= Content-Length still 13 at this point
  5098. });
  5099. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5100. res.set_content("Hello World!\n", "text/plain");
  5101. throw std::runtime_error("abc");
  5102. });
  5103. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5104. auto se = detail::scope_exit([&] {
  5105. svr.stop();
  5106. thread.join();
  5107. ASSERT_FALSE(svr.is_running());
  5108. });
  5109. svr.wait_until_ready();
  5110. for (size_t i = 0; i < 10; i++) {
  5111. Client cli(HOST, PORT);
  5112. for (size_t j = 0; j < 100; j++) {
  5113. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5115. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5116. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5117. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5118. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5119. }
  5120. cli.set_keep_alive(true);
  5121. for (size_t j = 0; j < 100; j++) {
  5122. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5125. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5126. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5127. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5128. }
  5129. }
  5130. }
  5131. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5132. Server svr;
  5133. svr.set_exception_handler(
  5134. [](const Request &, Response &res, std::exception_ptr) {
  5135. res.set_content("oops", "text/plain");
  5136. });
  5137. svr.Get("/throw", [](const Request &, Response &) {
  5138. throw std::runtime_error("throw");
  5139. });
  5140. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5141. res.status = StatusCode::Created_201;
  5142. throw std::runtime_error("created-then-throw");
  5143. });
  5144. auto port = svr.bind_to_any_port(HOST);
  5145. ASSERT_GT(port, 0);
  5146. thread t = thread([&] { svr.listen_after_bind(); });
  5147. auto se = detail::scope_exit([&] {
  5148. svr.stop();
  5149. t.join();
  5150. ASSERT_FALSE(svr.is_running());
  5151. });
  5152. svr.wait_until_ready();
  5153. Client cli(HOST, port);
  5154. for (auto path : {"/throw", "/created-then-throw"}) {
  5155. auto res = cli.Get(path);
  5156. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5157. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5158. }
  5159. }
  5160. TEST(ExceptionTest, AndErrorHandler) {
  5161. Server svr;
  5162. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5163. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5164. });
  5165. svr.set_exception_handler(
  5166. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5167. EXPECT_FALSE(ep == nullptr);
  5168. try {
  5169. std::rethrow_exception(ep);
  5170. } catch (std::exception &e) {
  5171. res.set_content(e.what(), "text/html");
  5172. } catch (...) {}
  5173. res.status = StatusCode::InternalServerError_500;
  5174. });
  5175. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5176. throw std::runtime_error("EXCEPTION");
  5177. });
  5178. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5179. res.set_content("ERROR", "text/html");
  5180. res.status = StatusCode::InternalServerError_500;
  5181. });
  5182. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5183. auto se = detail::scope_exit([&] {
  5184. svr.stop();
  5185. thread.join();
  5186. ASSERT_FALSE(svr.is_running());
  5187. });
  5188. svr.wait_until_ready();
  5189. Client cli(HOST, PORT);
  5190. {
  5191. auto res = cli.Get("/exception");
  5192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5193. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5194. EXPECT_EQ("EXCEPTION", res->body);
  5195. }
  5196. {
  5197. auto res = cli.Get("/error");
  5198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5199. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5200. EXPECT_EQ("ERROR", res->body);
  5201. }
  5202. {
  5203. auto res = cli.Get("/invalid");
  5204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5205. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5206. EXPECT_EQ("NOT_FOUND", res->body);
  5207. }
  5208. }
  5209. #endif
  5210. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5211. // An exception from a user callback outside process_request()'s try/catch
  5212. // used to unwind into the task queue - which does not catch - and terminate
  5213. // the process. Each test below runs the server on a single worker thread: a
  5214. // guard that catches the exception but still loses the thread would otherwise
  5215. // be hidden by a spare worker serving the follow-up request. Note that a
  5216. // regression here aborts the whole test binary rather than failing one test.
  5217. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5218. Server svr;
  5219. svr.new_task_queue = [] { return new ThreadPool(1); };
  5220. std::atomic<int> reported{0};
  5221. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5222. if (err == Error::UserCallbackException) { reported++; }
  5223. });
  5224. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5225. res.set_content_provider(
  5226. 1024, "text/plain",
  5227. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5228. sink.write("hello", 5);
  5229. throw std::runtime_error("from the content provider");
  5230. });
  5231. });
  5232. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5233. res.set_content("ok", "text/plain");
  5234. });
  5235. auto port = svr.bind_to_any_port(HOST);
  5236. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5237. auto se = detail::scope_exit([&] {
  5238. svr.stop();
  5239. listen_thread.join();
  5240. ASSERT_FALSE(svr.is_running());
  5241. });
  5242. svr.wait_until_ready();
  5243. {
  5244. Client cli(HOST, port);
  5245. cli.set_read_timeout(5, 0);
  5246. EXPECT_FALSE(cli.Get("/throw"));
  5247. }
  5248. EXPECT_TRUE(svr.is_running());
  5249. EXPECT_EQ(1, reported.load());
  5250. // A request on a fresh connection is still served.
  5251. {
  5252. Client cli(HOST, port);
  5253. auto res = cli.Get("/ok");
  5254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5255. EXPECT_EQ(StatusCode::OK_200, res->status);
  5256. EXPECT_EQ("ok", res->body);
  5257. }
  5258. }
  5259. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5260. Server svr;
  5261. svr.new_task_queue = [] { return new ThreadPool(1); };
  5262. std::atomic<bool> should_throw{true};
  5263. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5264. res.set_content("hi", "text/plain");
  5265. });
  5266. svr.set_post_routing_handler(
  5267. [&](const Request & /*req*/, Response & /*res*/) {
  5268. if (should_throw) {
  5269. throw std::runtime_error("from the post-routing handler");
  5270. }
  5271. });
  5272. auto port = svr.bind_to_any_port(HOST);
  5273. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5274. auto se = detail::scope_exit([&] {
  5275. svr.stop();
  5276. listen_thread.join();
  5277. ASSERT_FALSE(svr.is_running());
  5278. });
  5279. svr.wait_until_ready();
  5280. {
  5281. Client cli(HOST, port);
  5282. cli.set_read_timeout(5, 0);
  5283. EXPECT_FALSE(cli.Get("/hi"));
  5284. }
  5285. EXPECT_TRUE(svr.is_running());
  5286. should_throw = false;
  5287. {
  5288. Client cli(HOST, port);
  5289. auto res = cli.Get("/hi");
  5290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5291. EXPECT_EQ(StatusCode::OK_200, res->status);
  5292. EXPECT_EQ("hi", res->body);
  5293. }
  5294. }
  5295. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5296. // The guard reports the caught exception through the error logger, which is
  5297. // a user callback too. A logger that throws has to be contained as well, or
  5298. // the process would terminate from inside the catch.
  5299. Server svr;
  5300. svr.new_task_queue = [] { return new ThreadPool(1); };
  5301. std::atomic<int> reported{0};
  5302. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5303. if (err == Error::UserCallbackException) {
  5304. reported++;
  5305. throw std::runtime_error("from the error logger");
  5306. }
  5307. });
  5308. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5309. res.set_content_provider(
  5310. 1024, "text/plain",
  5311. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5312. sink.write("hello", 5);
  5313. throw std::runtime_error("from the content provider");
  5314. });
  5315. });
  5316. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5317. res.set_content("ok", "text/plain");
  5318. });
  5319. auto port = svr.bind_to_any_port(HOST);
  5320. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5321. auto se = detail::scope_exit([&] {
  5322. svr.stop();
  5323. listen_thread.join();
  5324. ASSERT_FALSE(svr.is_running());
  5325. });
  5326. svr.wait_until_ready();
  5327. {
  5328. Client cli(HOST, port);
  5329. cli.set_read_timeout(5, 0);
  5330. EXPECT_FALSE(cli.Get("/throw"));
  5331. }
  5332. EXPECT_TRUE(svr.is_running());
  5333. EXPECT_EQ(1, reported.load());
  5334. {
  5335. Client cli(HOST, port);
  5336. auto res = cli.Get("/ok");
  5337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5338. EXPECT_EQ(StatusCode::OK_200, res->status);
  5339. EXPECT_EQ("ok", res->body);
  5340. }
  5341. }
  5342. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5343. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5344. // so the exception unwinds through the ws::WebSocket object on its way to
  5345. // the guard. None of the HTTP cases above cross that.
  5346. Server svr;
  5347. svr.new_task_queue = [] { return new ThreadPool(1); };
  5348. std::atomic<int> reported{0};
  5349. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5350. if (err == Error::UserCallbackException) { reported++; }
  5351. });
  5352. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5353. throw std::runtime_error("from the WebSocket handler");
  5354. });
  5355. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5356. res.set_content("ok", "text/plain");
  5357. });
  5358. auto port = svr.bind_to_any_port(HOST);
  5359. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5360. auto se = detail::scope_exit([&] {
  5361. svr.stop();
  5362. listen_thread.join();
  5363. ASSERT_FALSE(svr.is_running());
  5364. });
  5365. svr.wait_until_ready();
  5366. {
  5367. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5368. "/ws");
  5369. auto res = client.connect();
  5370. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5371. // The server dropped the connection instead of dying.
  5372. std::string msg;
  5373. EXPECT_FALSE(client.read(msg));
  5374. client.close();
  5375. }
  5376. EXPECT_TRUE(svr.is_running());
  5377. EXPECT_EQ(1, reported.load());
  5378. {
  5379. Client cli(HOST, port);
  5380. auto res = cli.Get("/ok");
  5381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5382. EXPECT_EQ(StatusCode::OK_200, res->status);
  5383. EXPECT_EQ("ok", res->body);
  5384. }
  5385. }
  5386. #ifdef CPPHTTPLIB_SSL_ENABLED
  5387. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5388. // SSLServer::process_and_close_socket() is a separate overload with its own
  5389. // guard, so it is exercised on its own.
  5390. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5391. ASSERT_TRUE(svr.is_valid());
  5392. svr.new_task_queue = [] { return new ThreadPool(1); };
  5393. std::atomic<int> reported{0};
  5394. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5395. if (err == Error::UserCallbackException) { reported++; }
  5396. });
  5397. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5398. res.set_content_provider(
  5399. 1024, "text/plain",
  5400. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5401. sink.write("hello", 5);
  5402. throw std::runtime_error("from the content provider");
  5403. });
  5404. });
  5405. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5406. res.set_content("ok", "text/plain");
  5407. });
  5408. auto port = svr.bind_to_any_port(HOST);
  5409. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5410. auto se = detail::scope_exit([&] {
  5411. svr.stop();
  5412. listen_thread.join();
  5413. ASSERT_FALSE(svr.is_running());
  5414. });
  5415. svr.wait_until_ready();
  5416. {
  5417. SSLClient cli(HOST, port);
  5418. cli.enable_server_certificate_verification(false);
  5419. cli.set_read_timeout(5, 0);
  5420. EXPECT_FALSE(cli.Get("/throw"));
  5421. }
  5422. EXPECT_TRUE(svr.is_running());
  5423. EXPECT_EQ(1, reported.load());
  5424. {
  5425. SSLClient cli(HOST, port);
  5426. cli.enable_server_certificate_verification(false);
  5427. auto res = cli.Get("/ok");
  5428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5429. EXPECT_EQ(StatusCode::OK_200, res->status);
  5430. EXPECT_EQ("ok", res->body);
  5431. }
  5432. }
  5433. #endif
  5434. #endif
  5435. TEST(NoContentTest, ContentLength) {
  5436. Server svr;
  5437. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5438. res.status = StatusCode::NoContent_204;
  5439. });
  5440. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5441. auto se = detail::scope_exit([&] {
  5442. svr.stop();
  5443. thread.join();
  5444. ASSERT_FALSE(svr.is_running());
  5445. });
  5446. svr.wait_until_ready();
  5447. {
  5448. Client cli(HOST, PORT);
  5449. auto res = cli.Get("/hi");
  5450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5451. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5452. // RFC 9110 8.6: none in a 204 response
  5453. EXPECT_FALSE(res->has_header("Content-Length"));
  5454. }
  5455. }
  5456. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5457. Server svr;
  5458. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5459. res.set_header("Content-Length", "5");
  5460. res.set_content("hello world", "text/plain");
  5461. });
  5462. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5463. // A body that reads as the last chunk, were it taken as chunked
  5464. res.set_header("Transfer-Encoding", "chunked");
  5465. res.set_content("0\r\n\r\n", "text/plain");
  5466. });
  5467. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5468. res.set_header("Content-Length", "2");
  5469. res.set_content_provider(5, "text/plain",
  5470. [](size_t offset, size_t length, DataSink &sink) {
  5471. sink.write(&"hello"[offset], length);
  5472. return true;
  5473. });
  5474. });
  5475. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5476. res.set_header("Content-Length", "1234");
  5477. });
  5478. thread t = thread([&] { svr.listen(HOST, PORT); });
  5479. auto se = detail::scope_exit([&] {
  5480. svr.stop();
  5481. t.join();
  5482. ASSERT_FALSE(svr.is_running());
  5483. });
  5484. svr.wait_until_ready();
  5485. Client cli(HOST, PORT);
  5486. cli.set_read_timeout(1, 0);
  5487. auto expect_body = [&](const Result &res, const std::string &body) {
  5488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5489. EXPECT_EQ(body, res->body);
  5490. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5491. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5492. };
  5493. Headers identity{{"Accept-Encoding", ""}};
  5494. expect_body(cli.Get("/body", identity), "hello world");
  5495. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5496. expect_body(cli.Get("/body",
  5497. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5498. "he");
  5499. expect_body(cli.Get("/provider", identity), "hello");
  5500. expect_body(cli.Get("/empty", identity), "");
  5501. // A HEAD response may give the length of the body a GET would get.
  5502. auto res = cli.Head("/empty");
  5503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5504. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5505. }
  5506. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5507. Server svr;
  5508. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5509. res.set_content("short", "text/plain");
  5510. });
  5511. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5512. res.body += " with a footer";
  5513. res.set_header("Transfer-Encoding", "chunked");
  5514. });
  5515. thread t = thread([&] { svr.listen(HOST, PORT); });
  5516. auto se = detail::scope_exit([&] {
  5517. svr.stop();
  5518. t.join();
  5519. ASSERT_FALSE(svr.is_running());
  5520. });
  5521. svr.wait_until_ready();
  5522. Client cli(HOST, PORT);
  5523. cli.set_read_timeout(1, 0);
  5524. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5526. EXPECT_EQ("short with a footer", res->body);
  5527. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5528. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5529. }
  5530. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5531. Server svr;
  5532. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5533. res.set_header("Content-Length", "3");
  5534. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5535. sink.write("abc", 3);
  5536. sink.done();
  5537. return true;
  5538. });
  5539. });
  5540. thread t = thread([&] { svr.listen(HOST, PORT); });
  5541. auto se = detail::scope_exit([&] {
  5542. svr.stop();
  5543. t.join();
  5544. ASSERT_FALSE(svr.is_running());
  5545. });
  5546. svr.wait_until_ready();
  5547. Client cli(HOST, PORT);
  5548. cli.set_keep_alive(true);
  5549. auto res = cli.Get("/");
  5550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5551. EXPECT_EQ("abc", res->body);
  5552. EXPECT_FALSE(res->has_header("Content-Length"));
  5553. EXPECT_EQ("close", res->get_header_value("Connection"));
  5554. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5555. // No body to delimit
  5556. auto head = cli.Head("/");
  5557. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5558. EXPECT_FALSE(head->has_header("Connection"));
  5559. }
  5560. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5561. #ifdef CPPHTTPLIB_SSL_ENABLED
  5562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5563. ASSERT_TRUE(svr.is_valid());
  5564. #else
  5565. Server svr;
  5566. #endif
  5567. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5568. if (req.path == "/routing_handler") {
  5569. res.set_header("PRE_ROUTING", "on");
  5570. res.set_content("Routing Handler", "text/plain");
  5571. return httplib::Server::HandlerResponse::Handled;
  5572. }
  5573. return httplib::Server::HandlerResponse::Unhandled;
  5574. });
  5575. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5576. res.set_content("Error", "text/html");
  5577. });
  5578. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5579. if (req.path == "/routing_handler") {
  5580. res.set_header("POST_ROUTING", "on");
  5581. }
  5582. });
  5583. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5584. res.set_content("Hello World!\n", "text/plain");
  5585. });
  5586. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5587. auto se = detail::scope_exit([&] {
  5588. svr.stop();
  5589. thread.join();
  5590. ASSERT_FALSE(svr.is_running());
  5591. });
  5592. svr.wait_until_ready();
  5593. {
  5594. #ifdef CPPHTTPLIB_SSL_ENABLED
  5595. SSLClient cli(HOST, PORT);
  5596. cli.enable_server_certificate_verification(false);
  5597. #else
  5598. Client cli(HOST, PORT);
  5599. #endif
  5600. auto res = cli.Get("/routing_handler");
  5601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5602. EXPECT_EQ(StatusCode::OK_200, res->status);
  5603. EXPECT_EQ("Routing Handler", res->body);
  5604. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5605. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5606. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5607. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5608. }
  5609. {
  5610. #ifdef CPPHTTPLIB_SSL_ENABLED
  5611. SSLClient cli(HOST, PORT);
  5612. cli.enable_server_certificate_verification(false);
  5613. #else
  5614. Client cli(HOST, PORT);
  5615. #endif
  5616. auto res = cli.Get("/hi");
  5617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5618. EXPECT_EQ(StatusCode::OK_200, res->status);
  5619. EXPECT_EQ("Hello World!\n", res->body);
  5620. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5621. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5622. }
  5623. {
  5624. #ifdef CPPHTTPLIB_SSL_ENABLED
  5625. SSLClient cli(HOST, PORT);
  5626. cli.enable_server_certificate_verification(false);
  5627. #else
  5628. Client cli(HOST, PORT);
  5629. #endif
  5630. auto res = cli.Get("/aaa");
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5633. EXPECT_EQ("Error", res->body);
  5634. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5635. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5636. }
  5637. }
  5638. TEST(RequestHandlerTest, PreRequestHandler) {
  5639. auto route_path = "/user/:user";
  5640. Server svr;
  5641. svr.Get("/hi", [](const Request &, Response &res) {
  5642. res.set_content("hi", "text/plain");
  5643. });
  5644. svr.Get(route_path, [](const Request &req, Response &res) {
  5645. res.set_content(req.path_params.at("user"), "text/plain");
  5646. });
  5647. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5648. if (req.matched_route == route_path) {
  5649. auto user = req.path_params.at("user");
  5650. if (user != "john") {
  5651. res.status = StatusCode::Forbidden_403;
  5652. res.set_content("error", "text/html");
  5653. return Server::HandlerResponse::Handled;
  5654. }
  5655. }
  5656. return Server::HandlerResponse::Unhandled;
  5657. });
  5658. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5659. auto se = detail::scope_exit([&] {
  5660. svr.stop();
  5661. thread.join();
  5662. ASSERT_FALSE(svr.is_running());
  5663. });
  5664. svr.wait_until_ready();
  5665. Client cli(HOST, PORT);
  5666. {
  5667. auto res = cli.Get("/hi");
  5668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5669. EXPECT_EQ(StatusCode::OK_200, res->status);
  5670. EXPECT_EQ("hi", res->body);
  5671. }
  5672. {
  5673. auto res = cli.Get("/user/john");
  5674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5675. EXPECT_EQ(StatusCode::OK_200, res->status);
  5676. EXPECT_EQ("john", res->body);
  5677. }
  5678. {
  5679. auto res = cli.Get("/user/invalid-user");
  5680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5681. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5682. EXPECT_EQ("error", res->body);
  5683. }
  5684. }
  5685. // The pre-request handler must run before the request body is read, so a
  5686. // rejected request never forces the server to buffer a (potentially large)
  5687. // body. Here the posted body is larger than the payload limit: if the body
  5688. // were read first the server would answer 413, but because the pre-request
  5689. // handler runs first it answers 403 and the body is never read.
  5690. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5691. Server svr;
  5692. svr.set_payload_max_length(8);
  5693. auto handler_ran = false;
  5694. svr.Post("/reject", [&](const Request &req, Response &res) {
  5695. handler_ran = true;
  5696. res.set_content(req.body, "text/plain");
  5697. });
  5698. svr.Post("/accept", [](const Request &req, Response &res) {
  5699. res.set_content(req.body, "text/plain");
  5700. });
  5701. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5702. if (req.matched_route == "/reject") {
  5703. res.status = StatusCode::Forbidden_403;
  5704. res.set_content("denied", "text/plain");
  5705. return Server::HandlerResponse::Handled;
  5706. }
  5707. return Server::HandlerResponse::Unhandled;
  5708. });
  5709. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5710. auto se = detail::scope_exit([&] {
  5711. svr.stop();
  5712. thread.join();
  5713. ASSERT_FALSE(svr.is_running());
  5714. });
  5715. svr.wait_until_ready();
  5716. Client cli(HOST, PORT);
  5717. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5718. // rejects with 403 before the body is read, so 413 is never reached.
  5719. {
  5720. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5722. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5723. EXPECT_EQ("denied", res->body);
  5724. EXPECT_FALSE(handler_ran);
  5725. }
  5726. // An approved route still reads the body and enforces the payload limit.
  5727. {
  5728. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5730. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5731. }
  5732. }
  5733. TEST(UserDataTest, BasicOperations) {
  5734. httplib::UserData ud;
  5735. // Initially empty
  5736. EXPECT_FALSE(ud.has("key"));
  5737. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5738. // set and get
  5739. ud.set("key", 42);
  5740. EXPECT_TRUE(ud.has("key"));
  5741. auto *p = ud.get<int>("key");
  5742. ASSERT_NE(nullptr, p);
  5743. EXPECT_EQ(42, *p);
  5744. // Type mismatch → nullptr
  5745. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5746. // Overwrite with different type
  5747. ud.set("key", std::string("hello"));
  5748. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5749. auto *s = ud.get<std::string>("key");
  5750. ASSERT_NE(nullptr, s);
  5751. EXPECT_EQ("hello", *s);
  5752. // erase
  5753. ud.erase("key");
  5754. EXPECT_FALSE(ud.has("key"));
  5755. // clear
  5756. ud.set("a", 1);
  5757. ud.set("b", 2);
  5758. ud.clear();
  5759. EXPECT_FALSE(ud.has("a"));
  5760. EXPECT_FALSE(ud.has("b"));
  5761. }
  5762. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5763. struct AuthCtx {
  5764. std::string user_id;
  5765. };
  5766. Server svr;
  5767. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5768. res.user_data.set("auth", AuthCtx{"alice"});
  5769. return Server::HandlerResponse::Unhandled;
  5770. });
  5771. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5772. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5773. ASSERT_NE(nullptr, ctx);
  5774. res.set_content("Hello " + ctx->user_id, "text/plain");
  5775. });
  5776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5777. auto se = detail::scope_exit([&] {
  5778. svr.stop();
  5779. thread.join();
  5780. ASSERT_FALSE(svr.is_running());
  5781. });
  5782. svr.wait_until_ready();
  5783. Client cli(HOST, PORT);
  5784. auto res = cli.Get("/me");
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. EXPECT_EQ(StatusCode::OK_200, res->status);
  5787. EXPECT_EQ("Hello alice", res->body);
  5788. }
  5789. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5790. struct RoleCtx {
  5791. std::string role;
  5792. };
  5793. Server svr;
  5794. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5795. res.user_data.set("role", RoleCtx{"admin"});
  5796. return Server::HandlerResponse::Unhandled;
  5797. });
  5798. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5799. auto *ctx = res.user_data.get<RoleCtx>("role");
  5800. ASSERT_NE(nullptr, ctx);
  5801. res.set_content(ctx->role, "text/plain");
  5802. });
  5803. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5804. auto se = detail::scope_exit([&] {
  5805. svr.stop();
  5806. thread.join();
  5807. ASSERT_FALSE(svr.is_running());
  5808. });
  5809. svr.wait_until_ready();
  5810. Client cli(HOST, PORT);
  5811. auto res = cli.Get("/role");
  5812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5813. EXPECT_EQ(StatusCode::OK_200, res->status);
  5814. EXPECT_EQ("admin", res->body);
  5815. }
  5816. TEST(InvalidFormatTest, StatusCode) {
  5817. Server svr;
  5818. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5819. res.set_content("Hello World!\n", "text/plain");
  5820. res.status = 9999; // Status should be a three-digit code...
  5821. });
  5822. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5823. auto se = detail::scope_exit([&] {
  5824. svr.stop();
  5825. thread.join();
  5826. ASSERT_FALSE(svr.is_running());
  5827. });
  5828. svr.wait_until_ready();
  5829. {
  5830. Client cli(HOST, PORT);
  5831. auto res = cli.Get("/hi");
  5832. ASSERT_FALSE(res);
  5833. }
  5834. }
  5835. TEST(URLFragmentTest, WithFragment) {
  5836. Server svr;
  5837. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5838. EXPECT_TRUE(req.target == "/hi");
  5839. });
  5840. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5841. auto se = detail::scope_exit([&] {
  5842. svr.stop();
  5843. thread.join();
  5844. ASSERT_FALSE(svr.is_running());
  5845. });
  5846. svr.wait_until_ready();
  5847. {
  5848. Client cli(HOST, PORT);
  5849. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5850. EXPECT_TRUE(res);
  5851. EXPECT_EQ(StatusCode::OK_200, res->status);
  5852. res = cli.Get("/hi%23key1=val1=key2=val2");
  5853. EXPECT_TRUE(res);
  5854. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5855. }
  5856. }
  5857. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5858. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5859. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5860. Server svr;
  5861. std::vector<std::string> targets;
  5862. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5863. targets.push_back(req.target);
  5864. });
  5865. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5866. auto se = detail::scope_exit([&] {
  5867. svr.stop();
  5868. thread.join();
  5869. ASSERT_FALSE(svr.is_running());
  5870. });
  5871. svr.wait_until_ready();
  5872. Client cli(HOST, PORT);
  5873. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5874. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5875. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5876. // A '?' after the '#' belongs to the fragment, not to the query.
  5877. Request req;
  5878. req.method = "GET";
  5879. req.path = "/hi#f?x=1";
  5880. req.params.emplace("a", "1");
  5881. Response res;
  5882. auto error = Error::Success;
  5883. EXPECT_TRUE(cli.send(req, res, error));
  5884. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5885. "/hi?a=1"}),
  5886. targets);
  5887. }
  5888. TEST(HeaderWriter, SetHeaderWriter) {
  5889. Server svr;
  5890. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5891. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5892. return detail::write_headers(strm, hdrs);
  5893. });
  5894. svr.Get("/hi", [](const Request &req, Response &res) {
  5895. auto it = req.headers.find("CustomClientHeader");
  5896. EXPECT_TRUE(it != req.headers.end());
  5897. EXPECT_EQ(it->second, "CustomClientValue");
  5898. res.set_content("Hello World!\n", "text/plain");
  5899. });
  5900. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5901. auto se = detail::scope_exit([&] {
  5902. svr.stop();
  5903. thread.join();
  5904. ASSERT_FALSE(svr.is_running());
  5905. });
  5906. svr.wait_until_ready();
  5907. {
  5908. Client cli(HOST, PORT);
  5909. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5910. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5911. return detail::write_headers(strm, hdrs);
  5912. });
  5913. auto res = cli.Get("/hi");
  5914. EXPECT_TRUE(res);
  5915. EXPECT_EQ(StatusCode::OK_200, res->status);
  5916. auto it = res->headers.find("CustomServerHeader");
  5917. EXPECT_TRUE(it != res->headers.end());
  5918. EXPECT_EQ(it->second, "CustomServerValue");
  5919. }
  5920. }
  5921. class ServerTest : public ::testing::Test {
  5922. protected:
  5923. ServerTest()
  5924. : cli_(HOST, PORT)
  5925. #ifdef CPPHTTPLIB_SSL_ENABLED
  5926. ,
  5927. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5928. #endif
  5929. {
  5930. #ifdef CPPHTTPLIB_SSL_ENABLED
  5931. cli_.enable_server_certificate_verification(false);
  5932. #endif
  5933. // Allow LARGE_DATA (100MB) responses
  5934. cli_.set_payload_max_length(200 * 1024 * 1024);
  5935. }
  5936. virtual void SetUp() {
  5937. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5938. svr_.set_payload_max_length(200 * 1024 * 1024);
  5939. svr_.set_mount_point("/", "./www");
  5940. svr_.set_mount_point("/mount", "./www2");
  5941. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5942. svr_.Get("/hi",
  5943. [&](const Request & /*req*/, Response &res) {
  5944. res.set_content("Hello World!", "text/plain");
  5945. })
  5946. .Get("/file_content",
  5947. [&](const Request & /*req*/, Response &res) {
  5948. res.set_file_content("./www/dir/test.html");
  5949. })
  5950. .Get("/file_content_with_content_type",
  5951. [&](const Request & /*req*/, Response &res) {
  5952. res.set_file_content("./www/file", "text/plain");
  5953. })
  5954. .Get("/invalid_file_content",
  5955. [&](const Request & /*req*/, Response &res) {
  5956. res.set_file_content("./www/dir/invalid_file_path");
  5957. })
  5958. .Get("/http_response_splitting",
  5959. [&](const Request & /*req*/, Response &res) {
  5960. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5961. EXPECT_EQ(0U, res.headers.size());
  5962. EXPECT_FALSE(res.has_header("a"));
  5963. res.set_header("a", "1\nSet-Cookie: a=1");
  5964. EXPECT_EQ(0U, res.headers.size());
  5965. EXPECT_FALSE(res.has_header("a"));
  5966. res.set_header("a", "1\rSet-Cookie: a=1");
  5967. EXPECT_EQ(0U, res.headers.size());
  5968. EXPECT_FALSE(res.has_header("a"));
  5969. res.set_header("a\r\nb", "0");
  5970. EXPECT_EQ(0U, res.headers.size());
  5971. EXPECT_FALSE(res.has_header("a"));
  5972. res.set_header("a\rb", "0");
  5973. EXPECT_EQ(0U, res.headers.size());
  5974. EXPECT_FALSE(res.has_header("a"));
  5975. res.set_header("a\nb", "0");
  5976. EXPECT_EQ(0U, res.headers.size());
  5977. EXPECT_FALSE(res.has_header("a"));
  5978. res.set_redirect("1\r\nSet-Cookie: a=1");
  5979. EXPECT_EQ(0U, res.headers.size());
  5980. EXPECT_FALSE(res.has_header("Location"));
  5981. })
  5982. .Get("/slow",
  5983. [&](const Request & /*req*/, Response &res) {
  5984. std::this_thread::sleep_for(std::chrono::seconds(4));
  5985. res.set_content("slow", "text/plain");
  5986. })
  5987. #if 0
  5988. .Post("/slowpost",
  5989. [&](const Request & /*req*/, Response &res) {
  5990. std::this_thread::sleep_for(std::chrono::seconds(2));
  5991. res.set_content("slow", "text/plain");
  5992. })
  5993. #endif
  5994. .Get("/remote_addr",
  5995. [&](const Request &req, Response &res) {
  5996. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5997. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5998. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5999. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  6000. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  6001. #endif
  6002. res.set_content(req.remote_addr, "text/plain");
  6003. })
  6004. .Get("/local_addr",
  6005. [&](const Request &req, Response &res) {
  6006. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  6007. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  6008. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6009. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  6010. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  6011. #endif
  6012. auto local_addr = req.local_addr;
  6013. auto local_port = std::to_string(req.local_port);
  6014. res.set_content(local_addr.append(":").append(local_port),
  6015. "text/plain");
  6016. })
  6017. .Get("/endwith%",
  6018. [&](const Request & /*req*/, Response &res) {
  6019. res.set_content("Hello World!", "text/plain");
  6020. })
  6021. .Get("/a\\+\\+b",
  6022. [&](const Request &req, Response &res) {
  6023. ASSERT_TRUE(req.has_param("a +b"));
  6024. auto val = req.get_param_value("a +b");
  6025. res.set_content(val, "text/plain");
  6026. })
  6027. .Get("/", [&](const Request & /*req*/,
  6028. Response &res) { res.set_redirect("/hi"); })
  6029. .Post("/1",
  6030. [](const Request & /*req*/, Response &res) {
  6031. res.set_redirect("/2", StatusCode::SeeOther_303);
  6032. })
  6033. .Get("/2",
  6034. [](const Request & /*req*/, Response &res) {
  6035. res.set_content("redirected.", "text/plain");
  6036. res.status = StatusCode::OK_200;
  6037. })
  6038. .Post("/person",
  6039. [&](const Request &req, Response &res) {
  6040. if (req.has_param("name") && req.has_param("note")) {
  6041. persons_[req.get_param_value("name")] =
  6042. req.get_param_value("note");
  6043. } else {
  6044. res.status = StatusCode::BadRequest_400;
  6045. }
  6046. })
  6047. .Put("/person",
  6048. [&](const Request &req, Response &res) {
  6049. if (req.has_param("name") && req.has_param("note")) {
  6050. persons_[req.get_param_value("name")] =
  6051. req.get_param_value("note");
  6052. } else {
  6053. res.status = StatusCode::BadRequest_400;
  6054. }
  6055. })
  6056. .Get("/person/(.*)",
  6057. [&](const Request &req, Response &res) {
  6058. string name = req.matches[1];
  6059. if (persons_.find(name) != persons_.end()) {
  6060. auto note = persons_[name];
  6061. res.set_content(note, "text/plain");
  6062. } else {
  6063. res.status = StatusCode::NotFound_404;
  6064. }
  6065. })
  6066. .Delete("/person",
  6067. [&](const Request &req, Response &res) {
  6068. if (req.has_param("name")) {
  6069. string name = req.get_param_value("name");
  6070. if (persons_.find(name) != persons_.end()) {
  6071. persons_.erase(name);
  6072. res.set_content("DELETED", "text/plain");
  6073. } else {
  6074. res.status = StatusCode::NotFound_404;
  6075. }
  6076. } else {
  6077. res.status = StatusCode::BadRequest_400;
  6078. }
  6079. })
  6080. .Post("/x-www-form-urlencoded-json",
  6081. [&](const Request &req, Response &res) {
  6082. auto json = req.get_param_value("json");
  6083. ASSERT_EQ(JSON_DATA, json);
  6084. res.set_content(json, "appliation/json");
  6085. res.status = StatusCode::OK_200;
  6086. })
  6087. .Get("/streamed-chunked",
  6088. [&](const Request & /*req*/, Response &res) {
  6089. res.set_chunked_content_provider(
  6090. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6091. sink.os << "123";
  6092. sink.os << "456";
  6093. sink.os << "789";
  6094. sink.done();
  6095. return true;
  6096. });
  6097. })
  6098. .Get("/streamed-chunked-with-prohibited-trailer",
  6099. [&](const Request & /*req*/, Response &res) {
  6100. auto i = new int(0);
  6101. // Declare both a prohibited trailer (Content-Length) and an
  6102. // allowed one
  6103. res.set_header("Trailer", "Content-Length, X-Allowed");
  6104. res.set_chunked_content_provider(
  6105. "text/plain",
  6106. [i](size_t /*offset*/, DataSink &sink) {
  6107. switch (*i) {
  6108. case 0: sink.os << "123"; break;
  6109. case 1: sink.os << "456"; break;
  6110. case 2: sink.os << "789"; break;
  6111. case 3: {
  6112. sink.done_with_trailer(
  6113. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6114. } break;
  6115. }
  6116. (*i)++;
  6117. return true;
  6118. },
  6119. [i](bool success) {
  6120. EXPECT_TRUE(success);
  6121. delete i;
  6122. });
  6123. })
  6124. .Get("/streamed-chunked2",
  6125. [&](const Request & /*req*/, Response &res) {
  6126. auto i = new int(0);
  6127. res.set_chunked_content_provider(
  6128. "text/plain",
  6129. [i](size_t /*offset*/, DataSink &sink) {
  6130. switch (*i) {
  6131. case 0: sink.os << "123"; break;
  6132. case 1: sink.os << "456"; break;
  6133. case 2: sink.os << "789"; break;
  6134. case 3: sink.done(); break;
  6135. }
  6136. (*i)++;
  6137. return true;
  6138. },
  6139. [i](bool success) {
  6140. EXPECT_TRUE(success);
  6141. delete i;
  6142. });
  6143. })
  6144. .Get("/streamed-chunked-with-trailer",
  6145. [&](const Request & /*req*/, Response &res) {
  6146. auto i = new int(0);
  6147. res.set_header("Trailer", "Dummy1, Dummy2");
  6148. res.set_chunked_content_provider(
  6149. "text/plain",
  6150. [i](size_t /*offset*/, DataSink &sink) {
  6151. switch (*i) {
  6152. case 0: sink.os << "123"; break;
  6153. case 1: sink.os << "456"; break;
  6154. case 2: sink.os << "789"; break;
  6155. case 3: {
  6156. sink.done_with_trailer(
  6157. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6158. } break;
  6159. }
  6160. (*i)++;
  6161. return true;
  6162. },
  6163. [i](bool success) {
  6164. EXPECT_TRUE(success);
  6165. delete i;
  6166. });
  6167. })
  6168. .Get("/streamed",
  6169. [&](const Request & /*req*/, Response &res) {
  6170. res.set_content_provider(
  6171. 6, "text/plain",
  6172. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6173. sink.os << (offset < 3 ? "a" : "b");
  6174. return true;
  6175. });
  6176. })
  6177. .Get("/streamed-without-length",
  6178. [&](const Request & /*req*/, Response &res) {
  6179. auto data = new std::string("abcdefg");
  6180. res.set_content_provider(
  6181. "text/plain",
  6182. [data](size_t offset, DataSink &sink) {
  6183. if (offset < data->size()) {
  6184. sink.os << data->substr(offset);
  6185. }
  6186. sink.done();
  6187. return true;
  6188. },
  6189. [data](bool success) {
  6190. EXPECT_TRUE(success);
  6191. delete data;
  6192. });
  6193. })
  6194. .Get("/streamed-with-range",
  6195. [&](const Request &req, Response &res) {
  6196. auto data = new std::string("abcdefg");
  6197. // An explicit status keeps the server from picking the 206 it
  6198. // would otherwise choose for a ranged request, so the response
  6199. // is not a partial representation.
  6200. auto status = req.get_param_value("status");
  6201. if (status == "200") {
  6202. res.status = StatusCode::OK_200;
  6203. } else if (status == "403") {
  6204. res.status = StatusCode::Forbidden_403;
  6205. }
  6206. res.set_content_provider(
  6207. data->size(), "text/plain",
  6208. [data](size_t offset, size_t length, DataSink &sink) {
  6209. size_t DATA_CHUNK_SIZE = 4;
  6210. const auto &d = *data;
  6211. auto out_len =
  6212. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6213. auto ret =
  6214. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6215. EXPECT_TRUE(ret);
  6216. return true;
  6217. },
  6218. [data, &req](bool success) {
  6219. EXPECT_EQ(success, !req.has_param("error"));
  6220. delete data;
  6221. });
  6222. })
  6223. .Get("/streamed-cancel",
  6224. [&](const Request & /*req*/, Response &res) {
  6225. res.set_content_provider(
  6226. size_t(-1), "text/plain",
  6227. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6228. sink.os << "data_chunk";
  6229. return true;
  6230. });
  6231. })
  6232. .Get("/regex-with-delimiter",
  6233. [&](const Request &req, Response & /*res*/) {
  6234. ASSERT_TRUE(req.has_param("key"));
  6235. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6236. })
  6237. .Get("/with-range",
  6238. [&](const Request & /*req*/, Response &res) {
  6239. res.set_content("abcdefg", "text/plain");
  6240. })
  6241. .Get("/test-start-time",
  6242. [&](const Request &req, Response & /*res*/) {
  6243. EXPECT_NE(req.start_time_,
  6244. std::chrono::steady_clock::time_point::min());
  6245. })
  6246. .Get("/with-range-customized-response",
  6247. [&](const Request & /*req*/, Response &res) {
  6248. res.status = StatusCode::BadRequest_400;
  6249. res.set_content(JSON_DATA, "application/json");
  6250. })
  6251. .Post("/chunked",
  6252. [&](const Request &req, Response & /*res*/) {
  6253. EXPECT_EQ(req.body, "dechunked post body");
  6254. })
  6255. .Post("/large-chunked",
  6256. [&](const Request &req, Response & /*res*/) {
  6257. std::string expected(6 * 30 * 1024u, 'a');
  6258. EXPECT_EQ(req.body, expected);
  6259. })
  6260. .Post("/multipart",
  6261. [&](const Request &req, Response & /*res*/) {
  6262. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6263. req.form.get_field_count("text2") +
  6264. req.form.get_field_count("file3") +
  6265. req.form.get_field_count("file4"));
  6266. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6267. req.form.get_file_count("file2"));
  6268. ASSERT_TRUE(!req.form.has_file("???"));
  6269. ASSERT_TRUE(!req.form.has_field("???"));
  6270. ASSERT_TRUE(req.body.empty());
  6271. {
  6272. const auto &text = req.form.get_field("text1");
  6273. EXPECT_EQ("text default", text);
  6274. }
  6275. {
  6276. const auto &text = req.form.get_field("text2");
  6277. EXPECT_EQ("aωb", text);
  6278. }
  6279. {
  6280. const auto &file = req.form.get_file("file1");
  6281. EXPECT_EQ("hello.txt", file.filename);
  6282. EXPECT_EQ("text/plain", file.content_type);
  6283. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6284. }
  6285. {
  6286. const auto &file = req.form.get_file("file2");
  6287. EXPECT_EQ("world.json", file.filename);
  6288. EXPECT_EQ("application/json", file.content_type);
  6289. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6290. }
  6291. {
  6292. const auto &text = req.form.get_field("file3");
  6293. EXPECT_EQ(0u, text.size());
  6294. }
  6295. {
  6296. const auto &text = req.form.get_field("file4");
  6297. EXPECT_EQ(0u, text.size());
  6298. }
  6299. })
  6300. .Post("/multipart/multi_file_values",
  6301. [&](const Request &req, Response & /*res*/) {
  6302. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6303. req.form.get_field_count("multi_text1"));
  6304. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6305. ASSERT_TRUE(!req.form.has_file("???"));
  6306. ASSERT_TRUE(!req.form.has_field("???"));
  6307. ASSERT_TRUE(req.body.empty());
  6308. {
  6309. const auto &text = req.form.get_field("text");
  6310. EXPECT_EQ("default text", text);
  6311. }
  6312. {
  6313. const auto &text1_values = req.form.get_fields("multi_text1");
  6314. EXPECT_EQ(2u, text1_values.size());
  6315. EXPECT_EQ("aaaaa", text1_values[0]);
  6316. EXPECT_EQ("bbbbb", text1_values[1]);
  6317. }
  6318. {
  6319. const auto &file1_values = req.form.get_files("multi_file1");
  6320. EXPECT_EQ(2u, file1_values.size());
  6321. auto file1 = file1_values[0];
  6322. EXPECT_EQ(file1.filename, "hello.txt");
  6323. EXPECT_EQ(file1.content_type, "text/plain");
  6324. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6325. auto file2 = file1_values[1];
  6326. EXPECT_EQ(file2.filename, "world.json");
  6327. EXPECT_EQ(file2.content_type, "application/json");
  6328. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6329. }
  6330. })
  6331. .Post("/empty",
  6332. [&](const Request &req, Response &res) {
  6333. EXPECT_EQ(req.body, "");
  6334. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6335. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6336. res.set_content("empty", "text/plain");
  6337. })
  6338. .Post("/empty-no-content-type",
  6339. [&](const Request &req, Response &res) {
  6340. EXPECT_EQ(req.body, "");
  6341. EXPECT_FALSE(req.has_header("Content-Type"));
  6342. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6343. res.set_content("empty-no-content-type", "text/plain");
  6344. })
  6345. .Post("/path-only",
  6346. [&](const Request &req, Response &res) {
  6347. EXPECT_EQ(req.body, "");
  6348. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6349. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6350. res.set_content("path-only", "text/plain");
  6351. })
  6352. .Post("/path-headers-only",
  6353. [&](const Request &req, Response &res) {
  6354. EXPECT_EQ(req.body, "");
  6355. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6356. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6357. EXPECT_EQ("world", req.get_header_value("hello"));
  6358. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6359. res.set_content("path-headers-only", "text/plain");
  6360. })
  6361. .Post("/post-large",
  6362. [&](const Request &req, Response &res) {
  6363. EXPECT_EQ(req.body, LARGE_DATA);
  6364. res.set_content(req.body, "text/plain");
  6365. })
  6366. .Post("/post-loopback",
  6367. [&](const Request &, Response &res,
  6368. ContentReader const &content_reader) {
  6369. std::string body;
  6370. content_reader([&](const char *data, size_t data_length) {
  6371. body.append(data, data_length);
  6372. return true;
  6373. });
  6374. res.set_content(body, "text/plain");
  6375. })
  6376. .Put("/put-loopback",
  6377. [&](const Request &, Response &res,
  6378. ContentReader const &content_reader) {
  6379. std::string body;
  6380. content_reader([&](const char *data, size_t data_length) {
  6381. body.append(data, data_length);
  6382. return true;
  6383. });
  6384. res.set_content(body, "text/plain");
  6385. })
  6386. .Patch("/patch-loopback",
  6387. [&](const Request &, Response &res,
  6388. ContentReader const &content_reader) {
  6389. std::string body;
  6390. content_reader([&](const char *data, size_t data_length) {
  6391. body.append(data, data_length);
  6392. return true;
  6393. });
  6394. res.set_content(body, "text/plain");
  6395. })
  6396. .Put("/empty-no-content-type",
  6397. [&](const Request &req, Response &res) {
  6398. EXPECT_EQ(req.body, "");
  6399. EXPECT_FALSE(req.has_header("Content-Type"));
  6400. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6401. res.set_content("empty-no-content-type", "text/plain");
  6402. })
  6403. .Put("/put",
  6404. [&](const Request &req, Response &res) {
  6405. EXPECT_EQ(req.body, "PUT");
  6406. res.set_content(req.body, "text/plain");
  6407. })
  6408. .Put("/put-large",
  6409. [&](const Request &req, Response &res) {
  6410. EXPECT_EQ(req.body, LARGE_DATA);
  6411. res.set_content(req.body, "text/plain");
  6412. })
  6413. .Patch("/patch",
  6414. [&](const Request &req, Response &res) {
  6415. EXPECT_EQ(req.body, "PATCH");
  6416. res.set_content(req.body, "text/plain");
  6417. })
  6418. .Delete("/delete",
  6419. [&](const Request & /*req*/, Response &res) {
  6420. res.set_content("DELETE", "text/plain");
  6421. })
  6422. .Delete("/delete-body",
  6423. [&](const Request &req, Response &res) {
  6424. EXPECT_EQ(req.body, "content");
  6425. res.set_content(req.body, "text/plain");
  6426. })
  6427. .Options(R"(\*)",
  6428. [&](const Request & /*req*/, Response &res) {
  6429. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6430. })
  6431. .CustomRoute("PROPFIND", "/dav/:id",
  6432. [&](const Request &req, Response &res) {
  6433. res.set_header("x-body-size",
  6434. std::to_string(req.body.size()));
  6435. res.set_header("x-matched-route", req.matched_route);
  6436. res.set_header("x-dav-id", req.path_params.at("id"));
  6437. res.status = StatusCode::MultiStatus_207;
  6438. res.set_content(req.body, "application/xml");
  6439. })
  6440. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6441. [&](const Request &req, Response &res) {
  6442. res.set_header("x-dav-match", req.matches[1]);
  6443. res.status = StatusCode::MultiStatus_207;
  6444. })
  6445. .CustomRoute("MKCOL", "/dav-mkcol",
  6446. [&](const Request &req, Response &res) {
  6447. EXPECT_TRUE(req.body.empty());
  6448. res.status = StatusCode::Created_201;
  6449. })
  6450. .CustomRoute(
  6451. "REPORT", "/dav-report",
  6452. [&](const Request & /*req*/, Response &res,
  6453. const ContentReader &content_reader) {
  6454. std::string body;
  6455. content_reader([&](const char *data, size_t data_length) {
  6456. body.append(data, data_length);
  6457. return true;
  6458. });
  6459. res.set_header("x-body-size", std::to_string(body.size()));
  6460. res.status = StatusCode::MultiStatus_207;
  6461. res.set_content(body, "application/xml");
  6462. })
  6463. .Get("/request-target",
  6464. [&](const Request &req, Response & /*res*/) {
  6465. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6466. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6467. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6468. })
  6469. .Get("/long-query-value",
  6470. [&](const Request &req, Response & /*res*/) {
  6471. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6472. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6473. })
  6474. .Get("/too-long-query-value",
  6475. [&](const Request &req, Response & /*res*/) {
  6476. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6477. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6478. })
  6479. .Get("/array-param",
  6480. [&](const Request &req, Response & /*res*/) {
  6481. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6482. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6483. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6484. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6485. })
  6486. .Get("/array-param-values",
  6487. [&](const Request &req, Response & /*res*/) {
  6488. auto values = req.get_param_values("array");
  6489. EXPECT_EQ(3u, values.size());
  6490. EXPECT_EQ("value1", values[0]);
  6491. EXPECT_EQ("value2", values[1]);
  6492. EXPECT_EQ("value3", values[2]);
  6493. auto empty = req.get_param_values("nonexistent");
  6494. EXPECT_TRUE(empty.empty());
  6495. })
  6496. .Post("/validate-no-multiple-headers",
  6497. [&](const Request &req, Response & /*res*/) {
  6498. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6499. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6500. })
  6501. .Post("/content_receiver",
  6502. [&](const Request &req, Response &res,
  6503. const ContentReader &content_reader) {
  6504. if (req.is_multipart_form_data()) {
  6505. std::vector<FormData> items;
  6506. content_reader(
  6507. [&](const FormData &file) {
  6508. items.push_back(file);
  6509. return true;
  6510. },
  6511. [&](const char *data, size_t data_length) {
  6512. items.back().content.append(data, data_length);
  6513. return true;
  6514. });
  6515. EXPECT_EQ(5u, items.size());
  6516. {
  6517. const auto &file = get_file_value(items, "text1");
  6518. EXPECT_TRUE(file.filename.empty());
  6519. EXPECT_EQ("text default", file.content);
  6520. }
  6521. {
  6522. const auto &file = get_file_value(items, "text2");
  6523. EXPECT_TRUE(file.filename.empty());
  6524. EXPECT_EQ("aωb", file.content);
  6525. }
  6526. {
  6527. const auto &file = get_file_value(items, "file1");
  6528. EXPECT_EQ("hello.txt", file.filename);
  6529. EXPECT_EQ("text/plain", file.content_type);
  6530. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6531. }
  6532. {
  6533. const auto &file = get_file_value(items, "file2");
  6534. EXPECT_EQ("world.json", file.filename);
  6535. EXPECT_EQ("application/json", file.content_type);
  6536. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6537. }
  6538. {
  6539. const auto &file = get_file_value(items, "file3");
  6540. EXPECT_TRUE(file.filename.empty());
  6541. EXPECT_EQ("application/octet-stream", file.content_type);
  6542. EXPECT_EQ(0u, file.content.size());
  6543. }
  6544. } else {
  6545. std::string body;
  6546. content_reader([&](const char *data, size_t data_length) {
  6547. EXPECT_EQ(7U, data_length);
  6548. body.append(data, data_length);
  6549. return true;
  6550. });
  6551. EXPECT_EQ(body, "content");
  6552. res.set_content(body, "text/plain");
  6553. }
  6554. })
  6555. .Put("/content_receiver",
  6556. [&](const Request & /*req*/, Response &res,
  6557. const ContentReader &content_reader) {
  6558. std::string body;
  6559. content_reader([&](const char *data, size_t data_length) {
  6560. body.append(data, data_length);
  6561. return true;
  6562. });
  6563. EXPECT_EQ(body, "content");
  6564. res.set_content(body, "text/plain");
  6565. })
  6566. .Patch("/content_receiver",
  6567. [&](const Request & /*req*/, Response &res,
  6568. const ContentReader &content_reader) {
  6569. std::string body;
  6570. content_reader([&](const char *data, size_t data_length) {
  6571. body.append(data, data_length);
  6572. return true;
  6573. });
  6574. EXPECT_EQ(body, "content");
  6575. res.set_content(body, "text/plain");
  6576. })
  6577. .Post("/query-string-and-body",
  6578. [&](const Request &req, Response & /*res*/) {
  6579. ASSERT_TRUE(req.has_param("key"));
  6580. EXPECT_EQ(req.get_param_value("key"), "value");
  6581. EXPECT_EQ(req.body, "content");
  6582. })
  6583. .Get("/last-request",
  6584. [&](const Request &req, Response & /*res*/) {
  6585. EXPECT_EQ("close", req.get_header_value("Connection"));
  6586. })
  6587. .Get(R"(/redirect/(\d+))",
  6588. [&](const Request &req, Response &res) {
  6589. auto num = std::stoi(req.matches[1]) + 1;
  6590. std::string url = "/redirect/" + std::to_string(num);
  6591. res.set_redirect(url);
  6592. })
  6593. .Post("/binary",
  6594. [&](const Request &req, Response &res) {
  6595. EXPECT_EQ(4U, req.body.size());
  6596. EXPECT_EQ("application/octet-stream",
  6597. req.get_header_value("Content-Type"));
  6598. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6599. res.set_content(req.body, "application/octet-stream");
  6600. })
  6601. .Put("/binary",
  6602. [&](const Request &req, Response &res) {
  6603. EXPECT_EQ(4U, req.body.size());
  6604. EXPECT_EQ("application/octet-stream",
  6605. req.get_header_value("Content-Type"));
  6606. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6607. res.set_content(req.body, "application/octet-stream");
  6608. })
  6609. .Patch("/binary",
  6610. [&](const Request &req, Response &res) {
  6611. EXPECT_EQ(4U, req.body.size());
  6612. EXPECT_EQ("application/octet-stream",
  6613. req.get_header_value("Content-Type"));
  6614. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6615. res.set_content(req.body, "application/octet-stream");
  6616. })
  6617. .Delete("/binary",
  6618. [&](const Request &req, Response &res) {
  6619. EXPECT_EQ(4U, req.body.size());
  6620. EXPECT_EQ("application/octet-stream",
  6621. req.get_header_value("Content-Type"));
  6622. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6623. res.set_content(req.body, "application/octet-stream");
  6624. })
  6625. .Get("/issue1772",
  6626. [&](const Request & /*req*/, Response &res) {
  6627. res.status = 401;
  6628. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6629. })
  6630. .Delete("/issue609",
  6631. [](const httplib::Request &, httplib::Response &res,
  6632. const httplib::ContentReader &) {
  6633. res.set_content("ok", "text/plain");
  6634. })
  6635. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6636. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6637. .Get("/compress",
  6638. [&](const Request & /*req*/, Response &res) {
  6639. res.set_content(
  6640. "12345678901234567890123456789012345678901234567890123456789"
  6641. "01234567890123456789012345678901234567890",
  6642. "text/plain");
  6643. })
  6644. .Get("/compress-with-charset",
  6645. [&](const Request & /*req*/, Response &res) {
  6646. res.set_content(
  6647. "12345678901234567890123456789012345678901234567890123456789"
  6648. "01234567890123456789012345678901234567890",
  6649. "application/json; charset=utf-8");
  6650. })
  6651. .Get("/nocompress",
  6652. [&](const Request & /*req*/, Response &res) {
  6653. res.set_content(
  6654. "12345678901234567890123456789012345678901234567890123456789"
  6655. "01234567890123456789012345678901234567890",
  6656. "application/octet-stream");
  6657. })
  6658. .Post("/compress-multipart",
  6659. [&](const Request &req, Response & /*res*/) {
  6660. EXPECT_EQ(2u, req.form.fields.size());
  6661. ASSERT_TRUE(!req.form.has_field("???"));
  6662. {
  6663. const auto &text = req.form.get_field("key1");
  6664. EXPECT_EQ("test", text);
  6665. }
  6666. {
  6667. const auto &text = req.form.get_field("key2");
  6668. EXPECT_EQ("--abcdefg123", text);
  6669. }
  6670. })
  6671. #endif
  6672. ;
  6673. persons_["john"] = "programmer";
  6674. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6675. svr_.wait_until_ready();
  6676. }
  6677. virtual void TearDown() {
  6678. svr_.stop();
  6679. if (!request_threads_.empty()) {
  6680. std::this_thread::sleep_for(std::chrono::seconds(1));
  6681. for (auto &t : request_threads_) {
  6682. t.join();
  6683. }
  6684. }
  6685. t_.join();
  6686. }
  6687. map<string, string> persons_;
  6688. #ifdef CPPHTTPLIB_SSL_ENABLED
  6689. SSLClient cli_;
  6690. SSLServer svr_;
  6691. #else
  6692. Client cli_;
  6693. Server svr_;
  6694. #endif
  6695. thread t_;
  6696. std::vector<thread> request_threads_;
  6697. };
  6698. TEST_F(ServerTest, GetMethod200) {
  6699. auto res = cli_.Get("/hi");
  6700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6701. EXPECT_EQ("HTTP/1.1", res->version);
  6702. EXPECT_EQ(StatusCode::OK_200, res->status);
  6703. EXPECT_EQ("OK", res->reason);
  6704. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6705. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6706. EXPECT_EQ("Hello World!", res->body);
  6707. }
  6708. TEST_F(ServerTest, GetEmptyFile) {
  6709. auto res = cli_.Get("/empty_file");
  6710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6711. EXPECT_EQ(StatusCode::OK_200, res->status);
  6712. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6713. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6714. EXPECT_EQ("", res->body);
  6715. }
  6716. TEST_F(ServerTest, GetFileContent) {
  6717. auto res = cli_.Get("/file_content");
  6718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6719. EXPECT_EQ(StatusCode::OK_200, res->status);
  6720. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6721. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6722. EXPECT_EQ("test.html", res->body);
  6723. }
  6724. TEST_F(ServerTest, GetFileContentWithRange) {
  6725. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6727. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6728. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6729. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6730. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6731. EXPECT_EQ("est", res->body);
  6732. }
  6733. TEST_F(ServerTest, GetFileContentWithContentType) {
  6734. auto res = cli_.Get("/file_content_with_content_type");
  6735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6736. EXPECT_EQ(StatusCode::OK_200, res->status);
  6737. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6738. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6739. EXPECT_EQ("file\n", res->body);
  6740. }
  6741. TEST_F(ServerTest, GetInvalidFileContent) {
  6742. auto res = cli_.Get("/invalid_file_content");
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6745. }
  6746. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6747. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6749. EXPECT_EQ("HTTP/1.1", res->version);
  6750. EXPECT_EQ(StatusCode::OK_200, res->status);
  6751. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6752. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6753. EXPECT_EQ("Hello World!", res->body);
  6754. }
  6755. TEST_F(ServerTest, GetMethod302) {
  6756. auto res = cli_.Get("/");
  6757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6758. EXPECT_EQ(StatusCode::Found_302, res->status);
  6759. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6760. }
  6761. TEST_F(ServerTest, GetMethod302Redirect) {
  6762. cli_.set_follow_location(true);
  6763. auto res = cli_.Get("/");
  6764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6765. EXPECT_EQ(StatusCode::OK_200, res->status);
  6766. EXPECT_EQ("Hello World!", res->body);
  6767. EXPECT_EQ("/hi", res->location);
  6768. }
  6769. TEST_F(ServerTest, GetMethod404) {
  6770. auto res = cli_.Get("/invalid");
  6771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6772. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6773. }
  6774. TEST_F(ServerTest, HeadMethod200) {
  6775. auto res = cli_.Head("/hi");
  6776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6777. EXPECT_EQ(StatusCode::OK_200, res->status);
  6778. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6779. EXPECT_TRUE(res->body.empty());
  6780. }
  6781. TEST_F(ServerTest, HeadMethod200Static) {
  6782. auto res = cli_.Head("/mount/dir/index.html");
  6783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6784. EXPECT_EQ(StatusCode::OK_200, res->status);
  6785. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6786. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6787. EXPECT_TRUE(res->body.empty());
  6788. }
  6789. TEST_F(ServerTest, HeadMethod404) {
  6790. auto res = cli_.Head("/invalid");
  6791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6792. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6793. EXPECT_TRUE(res->body.empty());
  6794. }
  6795. TEST_F(ServerTest, GetMethodPersonJohn) {
  6796. auto res = cli_.Get("/person/john");
  6797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6798. EXPECT_EQ(StatusCode::OK_200, res->status);
  6799. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6800. EXPECT_EQ("programmer", res->body);
  6801. }
  6802. TEST_F(ServerTest, PostMethod1) {
  6803. auto res = cli_.Get("/person/john1");
  6804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6805. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6806. res = cli_.Post("/person", "name=john1&note=coder",
  6807. "application/x-www-form-urlencoded");
  6808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6809. ASSERT_EQ(StatusCode::OK_200, res->status);
  6810. res = cli_.Get("/person/john1");
  6811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6812. ASSERT_EQ(StatusCode::OK_200, res->status);
  6813. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6814. ASSERT_EQ("coder", res->body);
  6815. }
  6816. TEST_F(ServerTest, PostMethod2) {
  6817. auto res = cli_.Get("/person/john2");
  6818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6819. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6820. Params params;
  6821. params.emplace("name", "john2");
  6822. params.emplace("note", "coder");
  6823. res = cli_.Post("/person", params);
  6824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6825. ASSERT_EQ(StatusCode::OK_200, res->status);
  6826. res = cli_.Get("/person/john2");
  6827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6828. ASSERT_EQ(StatusCode::OK_200, res->status);
  6829. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6830. ASSERT_EQ("coder", res->body);
  6831. }
  6832. TEST_F(ServerTest, PutMethod3) {
  6833. auto res = cli_.Get("/person/john3");
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6836. Params params;
  6837. params.emplace("name", "john3");
  6838. params.emplace("note", "coder");
  6839. res = cli_.Put("/person", params);
  6840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6841. ASSERT_EQ(StatusCode::OK_200, res->status);
  6842. res = cli_.Get("/person/john3");
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. ASSERT_EQ(StatusCode::OK_200, res->status);
  6845. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6846. ASSERT_EQ("coder", res->body);
  6847. }
  6848. TEST_F(ServerTest, DeleteMethod1) {
  6849. auto res = cli_.Get("/person/john4");
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6852. Params params;
  6853. params.emplace("name", "john4");
  6854. params.emplace("note", "coder");
  6855. res = cli_.Post("/person", params);
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. ASSERT_EQ(StatusCode::OK_200, res->status);
  6858. res = cli_.Get("/person/john4");
  6859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6860. ASSERT_EQ(StatusCode::OK_200, res->status);
  6861. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6862. ASSERT_EQ("coder", res->body);
  6863. Params delete_params;
  6864. delete_params.emplace("name", "john4");
  6865. res = cli_.Delete("/person", delete_params);
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. ASSERT_EQ(StatusCode::OK_200, res->status);
  6868. ASSERT_EQ("DELETED", res->body);
  6869. res = cli_.Get("/person/john4");
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6872. }
  6873. TEST_F(ServerTest, DeleteMethod2) {
  6874. auto res = cli_.Get("/person/john5");
  6875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6876. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6877. Params params;
  6878. params.emplace("name", "john5");
  6879. params.emplace("note", "developer");
  6880. res = cli_.Post("/person", params);
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. ASSERT_EQ(StatusCode::OK_200, res->status);
  6883. res = cli_.Get("/person/john5");
  6884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6885. ASSERT_EQ(StatusCode::OK_200, res->status);
  6886. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6887. ASSERT_EQ("developer", res->body);
  6888. Params delete_params;
  6889. delete_params.emplace("name", "john5");
  6890. Headers headers;
  6891. headers.emplace("Custom-Header", "test-value");
  6892. res = cli_.Delete("/person", headers, delete_params);
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. ASSERT_EQ(StatusCode::OK_200, res->status);
  6895. ASSERT_EQ("DELETED", res->body);
  6896. res = cli_.Get("/person/john5");
  6897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6898. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6899. }
  6900. TEST_F(ServerTest, DeleteMethod3) {
  6901. auto res = cli_.Get("/person/john6");
  6902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6903. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6904. Params params;
  6905. params.emplace("name", "john6");
  6906. params.emplace("note", "tester");
  6907. res = cli_.Post("/person", params);
  6908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6909. ASSERT_EQ(StatusCode::OK_200, res->status);
  6910. res = cli_.Get("/person/john6");
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. ASSERT_EQ(StatusCode::OK_200, res->status);
  6913. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6914. ASSERT_EQ("tester", res->body);
  6915. Params delete_params;
  6916. delete_params.emplace("name", "john6");
  6917. Headers headers;
  6918. headers.emplace("Custom-Header", "test-value");
  6919. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6921. ASSERT_EQ(StatusCode::OK_200, res->status);
  6922. ASSERT_EQ("DELETED", res->body);
  6923. res = cli_.Get("/person/john6");
  6924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6925. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6926. }
  6927. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6928. Params params;
  6929. params.emplace("json", JSON_DATA);
  6930. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6932. ASSERT_EQ(StatusCode::OK_200, res->status);
  6933. ASSERT_EQ(JSON_DATA, res->body);
  6934. }
  6935. TEST_F(ServerTest, PostEmptyContent) {
  6936. auto res = cli_.Post("/empty", "", "text/plain");
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. ASSERT_EQ(StatusCode::OK_200, res->status);
  6939. ASSERT_EQ("empty", res->body);
  6940. }
  6941. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6942. auto res = cli_.Post("/empty-no-content-type");
  6943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6944. ASSERT_EQ(StatusCode::OK_200, res->status);
  6945. ASSERT_EQ("empty-no-content-type", res->body);
  6946. }
  6947. TEST_F(ServerTest, PostPathOnly) {
  6948. auto res = cli_.Post("/path-only");
  6949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6950. ASSERT_EQ(StatusCode::OK_200, res->status);
  6951. ASSERT_EQ("path-only", res->body);
  6952. }
  6953. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6954. auto res = cli_.Post("/path-headers-only",
  6955. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6957. ASSERT_EQ(StatusCode::OK_200, res->status);
  6958. ASSERT_EQ("path-headers-only", res->body);
  6959. }
  6960. TEST_F(ServerTest, PostLarge) {
  6961. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6963. ASSERT_EQ(StatusCode::OK_200, res->status);
  6964. EXPECT_EQ(LARGE_DATA, res->body);
  6965. }
  6966. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6967. auto res = cli_.Put("/empty-no-content-type");
  6968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6969. ASSERT_EQ(StatusCode::OK_200, res->status);
  6970. ASSERT_EQ("empty-no-content-type", res->body);
  6971. }
  6972. TEST_F(ServerTest, GetMethodDir) {
  6973. auto res = cli_.Get("/dir/");
  6974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6975. EXPECT_EQ(StatusCode::OK_200, res->status);
  6976. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6977. auto body = R"(<html>
  6978. <head>
  6979. </head>
  6980. <body>
  6981. <a href="/dir/test.html">Test</a>
  6982. <a href="/hi">hi</a>
  6983. </body>
  6984. </html>
  6985. )";
  6986. EXPECT_EQ(body, res->body);
  6987. }
  6988. TEST_F(ServerTest, GetMethodDirTest) {
  6989. auto res = cli_.Get("/dir/test.html");
  6990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6991. EXPECT_EQ(StatusCode::OK_200, res->status);
  6992. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6993. EXPECT_EQ("test.html", res->body);
  6994. }
  6995. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6996. auto res = cli_.Get("/dir/../dir/test.html");
  6997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6998. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6999. }
  7000. TEST_F(ServerTest, GetMethodInvalidPath) {
  7001. auto res = cli_.Get("/dir/../test.html");
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7004. }
  7005. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  7006. auto res = cli_.Get("/../www/dir/test.html");
  7007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7008. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7009. }
  7010. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  7011. auto res = cli_.Get("/dir/../../www/dir/test.html");
  7012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7013. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7014. }
  7015. TEST_F(ServerTest, GetMethodDirMountTest) {
  7016. auto res = cli_.Get("/mount/dir/test.html");
  7017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7018. EXPECT_EQ(StatusCode::OK_200, res->status);
  7019. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7020. EXPECT_EQ("test.html", res->body);
  7021. }
  7022. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  7023. auto res = cli_.Get("/mount/dir/../dir/test.html");
  7024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7025. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7026. }
  7027. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  7028. auto res = cli_.Get("/mount/dir/../test.html");
  7029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7030. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7031. }
  7032. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  7033. auto res = cli_.Get("/mount/dir/test.html%00.js");
  7034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7035. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7036. }
  7037. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  7038. auto res = cli_.Get("/mount/../www2/dir/test.html");
  7039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7040. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7041. }
  7042. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  7043. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  7044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7045. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7046. }
  7047. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  7048. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  7049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7050. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7051. }
  7052. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  7053. auto res = cli_.Get("/mount/dir");
  7054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7055. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7056. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7057. }
  7058. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7059. auto res = cli_.Get("//dir");
  7060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7061. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7062. EXPECT_FALSE(res->has_header("Location"));
  7063. }
  7064. TEST_F(ServerTest, PostMethod303) {
  7065. auto res = cli_.Post("/1", "body", "text/plain");
  7066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7067. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7068. EXPECT_EQ("/2", res->get_header_value("Location"));
  7069. }
  7070. TEST_F(ServerTest, PostMethod303Redirect) {
  7071. cli_.set_follow_location(true);
  7072. auto res = cli_.Post("/1", "body", "text/plain");
  7073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7074. EXPECT_EQ(StatusCode::OK_200, res->status);
  7075. EXPECT_EQ("redirected.", res->body);
  7076. EXPECT_EQ("/2", res->location);
  7077. }
  7078. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7079. auto res = cli_.Get("/dir/test.abcde");
  7080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7081. EXPECT_EQ(StatusCode::OK_200, res->status);
  7082. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7083. EXPECT_EQ("abcde", res->body);
  7084. }
  7085. TEST_F(ServerTest, StaticFileRange) {
  7086. auto res =
  7087. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7089. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7090. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7091. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7092. EXPECT_EQ(true, res->has_header("Content-Range"));
  7093. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7094. EXPECT_EQ(std::string("cd"), res->body);
  7095. }
  7096. TEST_F(ServerTest, StaticFileRanges) {
  7097. auto res = cli_.Get("/dir/test.abcde",
  7098. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7100. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7101. EXPECT_TRUE(
  7102. res->get_header_value("Content-Type")
  7103. .find(
  7104. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7105. 0);
  7106. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7107. }
  7108. TEST_F(ServerTest, StaticFileRangeHead) {
  7109. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7111. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7112. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7113. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7114. EXPECT_EQ(true, res->has_header("Content-Range"));
  7115. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7116. }
  7117. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7118. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7120. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7121. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7122. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7123. EXPECT_EQ(true, res->has_header("Content-Range"));
  7124. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7125. res->get_header_value("Content-Range"));
  7126. EXPECT_EQ("LAST\n", res->body);
  7127. }
  7128. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7129. auto res =
  7130. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7132. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7133. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7134. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7135. EXPECT_EQ(true, res->has_header("Content-Range"));
  7136. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7137. }
  7138. TEST_F(ServerTest, StaticFileBigFile) {
  7139. auto res = cli_.Get("/dir/1MB.txt");
  7140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7141. EXPECT_EQ(StatusCode::OK_200, res->status);
  7142. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7143. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7144. }
  7145. TEST_F(ServerTest, InvalidBaseDirMount) {
  7146. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7147. }
  7148. TEST_F(ServerTest, Binary) {
  7149. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7150. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7151. "application/octet-stream");
  7152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7153. ASSERT_EQ(StatusCode::OK_200, res->status);
  7154. ASSERT_EQ(4U, res->body.size());
  7155. res = cli_.Put("/binary", binary.data(), binary.size(),
  7156. "application/octet-stream");
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. ASSERT_EQ(StatusCode::OK_200, res->status);
  7159. ASSERT_EQ(4U, res->body.size());
  7160. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7161. "application/octet-stream");
  7162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7163. ASSERT_EQ(StatusCode::OK_200, res->status);
  7164. ASSERT_EQ(4U, res->body.size());
  7165. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7166. "application/octet-stream");
  7167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7168. ASSERT_EQ(StatusCode::OK_200, res->status);
  7169. ASSERT_EQ(4U, res->body.size());
  7170. }
  7171. TEST_F(ServerTest, BinaryString) {
  7172. auto binary = std::string("\x00\x01\x02\x03", 4);
  7173. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7175. ASSERT_EQ(StatusCode::OK_200, res->status);
  7176. ASSERT_EQ(4U, res->body.size());
  7177. res = cli_.Put("/binary", binary, "application/octet-stream");
  7178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7179. ASSERT_EQ(StatusCode::OK_200, res->status);
  7180. ASSERT_EQ(4U, res->body.size());
  7181. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7183. ASSERT_EQ(StatusCode::OK_200, res->status);
  7184. ASSERT_EQ(4U, res->body.size());
  7185. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7187. ASSERT_EQ(StatusCode::OK_200, res->status);
  7188. ASSERT_EQ(4U, res->body.size());
  7189. }
  7190. TEST_F(ServerTest, EmptyRequest) {
  7191. auto res = cli_.Get("");
  7192. ASSERT_TRUE(!res);
  7193. EXPECT_EQ(Error::Connection, res.error());
  7194. }
  7195. TEST_F(ServerTest, LongRequest) {
  7196. std::string request;
  7197. for (size_t i = 0; i < 545; i++) {
  7198. request += "/TooLongRequest";
  7199. }
  7200. request += "OK";
  7201. auto res = cli_.Get(request.c_str());
  7202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7203. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7204. }
  7205. TEST_F(ServerTest, TooLongRequest) {
  7206. std::string request;
  7207. for (size_t i = 0; i < 546; i++) {
  7208. request += "/TooLongRequest";
  7209. }
  7210. request += "_NG";
  7211. auto start = std::chrono::high_resolution_clock::now();
  7212. cli_.set_keep_alive(true);
  7213. auto res = cli_.Get(request.c_str());
  7214. auto end = std::chrono::high_resolution_clock::now();
  7215. auto elapsed =
  7216. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7217. .count();
  7218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7219. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7220. EXPECT_LE(elapsed, 1000);
  7221. EXPECT_EQ("close", res->get_header_value("Connection"));
  7222. EXPECT_FALSE(cli_.is_socket_open());
  7223. }
  7224. TEST_F(ServerTest, AlmostTooLongRequest) {
  7225. // test for #2046 - URI length check shouldn't include other content on req
  7226. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7227. // leading /, space, HTTP/1.1)
  7228. std::string request =
  7229. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7230. auto res = cli_.Get(request.c_str());
  7231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7232. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7233. }
  7234. TEST_F(ServerTest, LongHeader) {
  7235. Request req;
  7236. req.method = "GET";
  7237. req.path = "/hi";
  7238. std::string host_and_port;
  7239. host_and_port += HOST;
  7240. host_and_port += ":";
  7241. host_and_port += std::to_string(PORT);
  7242. req.headers.emplace("Host", host_and_port.c_str());
  7243. req.headers.emplace("Accept", "*/*");
  7244. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7245. req.headers.emplace(
  7246. "Header-Name",
  7247. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7248. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7249. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7250. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7251. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7252. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7253. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7254. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7255. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7256. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7257. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7258. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7259. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7260. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7261. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7262. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7263. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7264. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7265. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7266. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7267. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7268. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7269. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7270. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7271. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7272. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7273. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7274. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7275. "@@@@@@@@@@@@@@@@");
  7276. auto res = std::make_shared<Response>();
  7277. auto error = Error::Success;
  7278. auto ret = cli_.send(req, *res, error);
  7279. ASSERT_TRUE(ret);
  7280. EXPECT_EQ(StatusCode::OK_200, res->status);
  7281. }
  7282. TEST_F(ServerTest, LongQueryValue) {
  7283. auto start = std::chrono::high_resolution_clock::now();
  7284. cli_.set_keep_alive(true);
  7285. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7286. auto end = std::chrono::high_resolution_clock::now();
  7287. auto elapsed =
  7288. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7289. .count();
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7292. EXPECT_LE(elapsed, 1000);
  7293. EXPECT_EQ("close", res->get_header_value("Connection"));
  7294. EXPECT_FALSE(cli_.is_socket_open());
  7295. }
  7296. TEST_F(ServerTest, TooLongQueryValue) {
  7297. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7298. ASSERT_FALSE(res);
  7299. EXPECT_EQ(Error::Read, res.error());
  7300. }
  7301. TEST_F(ServerTest, TooLongHeader) {
  7302. Request req;
  7303. req.method = "GET";
  7304. req.path = "/hi";
  7305. std::string host_and_port;
  7306. host_and_port += HOST;
  7307. host_and_port += ":";
  7308. host_and_port += std::to_string(PORT);
  7309. req.headers.emplace("Host", host_and_port.c_str());
  7310. req.headers.emplace("Accept", "*/*");
  7311. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7312. req.headers.emplace(
  7313. "Header-Name",
  7314. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7315. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7316. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7317. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7318. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7319. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7320. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7321. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7322. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7323. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7324. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7325. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7326. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7327. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7328. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7329. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7330. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7331. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7332. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7333. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7334. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7335. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7336. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7337. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7338. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7339. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7340. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7341. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7342. "@@@@@@@@@@@@@@@@@");
  7343. auto res = std::make_shared<Response>();
  7344. auto error = Error::Success;
  7345. auto ret = cli_.send(req, *res, error);
  7346. ASSERT_TRUE(ret);
  7347. EXPECT_EQ(StatusCode::OK_200, res->status);
  7348. }
  7349. TEST_F(ServerTest, HeaderCountAtLimit) {
  7350. // Test with headers just under the 100 limit
  7351. httplib::Headers headers;
  7352. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7353. // This should keep us just under the 100 header limit
  7354. for (int i = 0; i < 95; i++) {
  7355. std::string name = "X-Test-Header-" + std::to_string(i);
  7356. std::string value = "value" + std::to_string(i);
  7357. headers.emplace(name, value);
  7358. }
  7359. // This should work fine as we're under the limit
  7360. auto res = cli_.Get("/hi", headers);
  7361. EXPECT_TRUE(res);
  7362. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7363. }
  7364. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7365. // Test with many headers to exceed the 100 limit
  7366. httplib::Headers headers;
  7367. // Add 150 headers to definitely exceed the 100 limit
  7368. for (int i = 0; i < 150; i++) {
  7369. std::string name = "X-Test-Header-" + std::to_string(i);
  7370. std::string value = "value" + std::to_string(i);
  7371. headers.emplace(name, value);
  7372. }
  7373. // This should fail due to exceeding header count limit
  7374. cli_.set_keep_alive(true);
  7375. auto res = cli_.Get("/hi", headers);
  7376. // The server should respond with 400 Bad Request
  7377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7378. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7379. EXPECT_EQ("close", res->get_header_value("Connection"));
  7380. EXPECT_FALSE(cli_.is_socket_open());
  7381. }
  7382. TEST_F(ServerTest, PercentEncoding) {
  7383. auto res = cli_.Get("/e%6edwith%");
  7384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7385. EXPECT_EQ(StatusCode::OK_200, res->status);
  7386. }
  7387. TEST_F(ServerTest, PercentEncodingUnicode) {
  7388. auto res = cli_.Get("/e%u006edwith%");
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::OK_200, res->status);
  7391. }
  7392. TEST_F(ServerTest, InvalidPercentEncoding) {
  7393. auto res = cli_.Get("/%endwith%");
  7394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7395. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7396. }
  7397. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7398. auto res = cli_.Get("/%uendwith%");
  7399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7400. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7401. }
  7402. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7403. auto res = cli_.Get("/hello?aaa=bbb%");
  7404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7405. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7406. }
  7407. TEST_F(ServerTest, PlusSignEncoding) {
  7408. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7410. EXPECT_EQ(StatusCode::OK_200, res->status);
  7411. EXPECT_EQ("a +b", res->body);
  7412. }
  7413. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7414. // This test simulates a potential DoS attack using many headers
  7415. // to verify our security fix prevents memory exhaustion
  7416. httplib::Headers attack_headers;
  7417. // Attempt to add many headers like an attacker would (200 headers to far
  7418. // exceed limit)
  7419. for (int i = 0; i < 200; i++) {
  7420. std::string name = "X-Attack-Header-" + std::to_string(i);
  7421. std::string value = "attack_payload_" + std::to_string(i);
  7422. attack_headers.emplace(name, value);
  7423. }
  7424. // Try to POST with excessive headers
  7425. cli_.set_keep_alive(true);
  7426. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7427. // Should either fail or return 400 Bad Request due to security limit
  7428. if (res) {
  7429. // If we get a response, it should be 400 Bad Request
  7430. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7431. EXPECT_EQ("close", res->get_header_value("Connection"));
  7432. }
  7433. EXPECT_FALSE(cli_.is_socket_open());
  7434. }
  7435. TEST_F(ServerTest, MultipartFormData) {
  7436. UploadFormDataItems items = {
  7437. {"text1", "text default", "", ""},
  7438. {"text2", "aωb", "", ""},
  7439. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7440. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7441. {"file3", "", "", "application/octet-stream"},
  7442. {"file4", "", "", " application/json tmp-string "}};
  7443. auto res = cli_.Post("/multipart", items);
  7444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7445. EXPECT_EQ(StatusCode::OK_200, res->status);
  7446. }
  7447. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7448. UploadFormDataItems items = {
  7449. {"text", "default text", "", ""},
  7450. {"multi_text1", "aaaaa", "", ""},
  7451. {"multi_text1", "bbbbb", "", ""},
  7452. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7453. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7454. "application/json"},
  7455. };
  7456. auto res = cli_.Post("/multipart/multi_file_values", items);
  7457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7458. EXPECT_EQ(StatusCode::OK_200, res->status);
  7459. }
  7460. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7461. auto res = cli_.Get("/hi");
  7462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7463. EXPECT_EQ(StatusCode::OK_200, res->status);
  7464. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7465. EXPECT_EQ("Hello World!", res->body);
  7466. }
  7467. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7468. Request req;
  7469. req.method = "POST";
  7470. req.path = "/chunked";
  7471. std::string host_and_port;
  7472. host_and_port += HOST;
  7473. host_and_port += ":";
  7474. host_and_port += std::to_string(PORT);
  7475. req.headers.emplace("Host", host_and_port.c_str());
  7476. req.headers.emplace("Accept", "*/*");
  7477. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7478. req.headers.emplace("Content-Type", "text/plain");
  7479. req.headers.emplace("Content-Length", "0");
  7480. req.headers.emplace(
  7481. "Transfer-Encoding",
  7482. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7483. // Client does not chunk, so make a chunked body manually.
  7484. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7485. auto res = std::make_shared<Response>();
  7486. auto error = Error::Success;
  7487. auto ret = cli_.send(req, *res, error);
  7488. ASSERT_TRUE(ret);
  7489. EXPECT_EQ(StatusCode::OK_200, res->status);
  7490. }
  7491. template <typename ClientT>
  7492. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7493. int expected_status) {
  7494. Request req;
  7495. req.method = "POST";
  7496. req.path = "/chunked";
  7497. std::string host_and_port;
  7498. host_and_port += HOST;
  7499. host_and_port += ":";
  7500. host_and_port += std::to_string(PORT);
  7501. req.headers.emplace("Host", host_and_port.c_str());
  7502. req.headers.emplace("Content-Length", "0");
  7503. req.headers.emplace("Transfer-Encoding", "chunked");
  7504. req.body = body;
  7505. auto res = std::make_shared<Response>();
  7506. auto error = Error::Success;
  7507. ASSERT_TRUE(cli.send(req, *res, error));
  7508. EXPECT_EQ(expected_status, res->status);
  7509. }
  7510. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7511. // rather than treat them as valid lengths.
  7512. template <typename ClientT>
  7513. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7514. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7515. }
  7516. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7517. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7518. }
  7519. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7520. expect_chunked_body_rejected(
  7521. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7522. }
  7523. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7524. // chunk-size line carries no CR, LF or other control character ahead of its
  7525. // terminator. Such a line must be refused rather than read as extension text.
  7526. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7527. expect_chunked_body_rejected(
  7528. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7529. }
  7530. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7531. expect_chunked_body_rejected(
  7532. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7533. }
  7534. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7535. expect_chunked_body_rejected(
  7536. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7537. }
  7538. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7539. // The literal stays split: a hex escape consumes every hex digit that
  7540. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7541. expect_chunked_body_rejected(
  7542. cli_, "4;a\x01"
  7543. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7544. }
  7545. // The bytes around chunk data are no payload, so they cannot ride on the
  7546. // payload limit
  7547. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7548. // Small enough that the whole request is sent before the server turns it
  7549. // down, yet past the limit by the last chunks
  7550. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7551. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7552. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7553. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7554. SCOPED_TRACE(size_line.substr(0, 2));
  7555. std::string body;
  7556. for (auto c : std::string("dechunked post body")) {
  7557. body += size_line + "\r\n" + c + "\r\n";
  7558. }
  7559. body += "0\r\n\r\n";
  7560. expect_chunked_body_rejected(cli_, body.c_str());
  7561. }
  7562. }
  7563. TEST_F(ServerTest, AcceptsChunkExtension) {
  7564. expect_chunked_body_status(cli_,
  7565. "4;name=value\r\ndech\r\n"
  7566. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7567. "0;last\r\n\r\n",
  7568. StatusCode::OK_200);
  7569. }
  7570. TEST_F(ServerTest, GetStreamed2) {
  7571. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7572. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7573. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7574. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7575. EXPECT_EQ(true, res->has_header("Content-Range"));
  7576. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7577. EXPECT_EQ(std::string("ab"), res->body);
  7578. }
  7579. TEST_F(ServerTest, GetStreamed) {
  7580. auto res = cli_.Get("/streamed");
  7581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7582. EXPECT_EQ(StatusCode::OK_200, res->status);
  7583. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7584. EXPECT_EQ(std::string("aaabbb"), res->body);
  7585. }
  7586. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7587. auto res = cli_.Get("/streamed-without-length",
  7588. Headers{make_range_header({{0, -1}})});
  7589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7590. EXPECT_EQ(StatusCode::OK_200, res->status);
  7591. EXPECT_EQ(false, res->has_header("Content-Length"));
  7592. EXPECT_EQ(false, res->has_header("Content-Range"));
  7593. EXPECT_EQ(std::string("abcdefg"), res->body);
  7594. }
  7595. TEST_F(ServerTest, GetStreamedWithRange1) {
  7596. auto res =
  7597. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7599. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7600. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7601. EXPECT_EQ(true, res->has_header("Content-Range"));
  7602. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7603. EXPECT_EQ(std::string("def"), res->body);
  7604. }
  7605. TEST_F(ServerTest, GetStreamedWithRange2) {
  7606. auto res =
  7607. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7609. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7610. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7611. EXPECT_EQ(true, res->has_header("Content-Range"));
  7612. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7613. EXPECT_EQ(std::string("bcdefg"), res->body);
  7614. }
  7615. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7616. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7618. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7619. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7620. EXPECT_EQ(true, res->has_header("Content-Range"));
  7621. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7622. EXPECT_EQ(std::string("efg"), res->body);
  7623. }
  7624. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7625. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7626. // the entire representation.
  7627. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7628. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7630. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7631. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7632. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7633. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7634. }
  7635. }
  7636. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7637. auto res =
  7638. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7640. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7641. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7642. EXPECT_EQ(false, res->has_header("Content-Range"));
  7643. EXPECT_EQ(0U, res->body.size());
  7644. }
  7645. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7646. // Only a 206 is served as a partial representation. Under any other status
  7647. // `apply_ranges()` reported the full content length, so the body must match
  7648. // that header, and the content provider must never be asked for an offset
  7649. // outside the representation.
  7650. auto check = [&](int status, const char *range) {
  7651. auto path =
  7652. std::string("/streamed-with-range?status=") + std::to_string(status);
  7653. auto ctx = path + " Range: " + range;
  7654. auto res = cli_.Get(path, Headers{{"Range", range}});
  7655. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7656. EXPECT_EQ(status, res->status) << ctx;
  7657. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7658. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7659. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7660. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7661. };
  7662. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7663. check(403, "bytes=3-5");
  7664. // The offset is far past the representation.
  7665. check(403, "bytes=100000-100200");
  7666. // `first_pos` is still -1 here, and the bounds asserts in
  7667. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7668. check(403, "bytes=-3");
  7669. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7670. // multipart branch would have written one that is empty.
  7671. check(403, "bytes=1-2, 4-5");
  7672. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7673. // covers the whole representation.
  7674. check(200, "bytes=3-5");
  7675. check(200, "bytes=1-2, 4-5");
  7676. }
  7677. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7678. auto res =
  7679. cli_.Get("/streamed-with-range",
  7680. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7681. "92233720368547758079223372036854775807"}});
  7682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7683. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7684. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7685. EXPECT_EQ(false, res->has_header("Content-Range"));
  7686. EXPECT_EQ(0U, res->body.size());
  7687. }
  7688. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7689. auto res = cli_.Get(
  7690. "/with-range",
  7691. Headers{{"Range",
  7692. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7693. {"Accept-Encoding", ""}});
  7694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7695. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7696. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7697. EXPECT_EQ(true, res->has_header("Content-Range"));
  7698. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7699. EXPECT_EQ(std::string("abcdefg"), res->body);
  7700. }
  7701. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7702. auto res = cli_.Get("/with-range", Headers{
  7703. {"Range", "bytes=0-"},
  7704. {"Accept-Encoding", ""},
  7705. });
  7706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7707. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7708. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7709. EXPECT_EQ(true, res->has_header("Content-Range"));
  7710. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7711. EXPECT_EQ(std::string("abcdefg"), res->body);
  7712. }
  7713. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7714. auto res = cli_.Get("/streamed-with-range",
  7715. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7717. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7718. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7719. EXPECT_EQ(false, res->has_header("Content-Range"));
  7720. EXPECT_EQ(267U, res->body.size());
  7721. // Check that both range contents are present
  7722. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7723. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7724. // Check that Content-Range headers are present for both ranges
  7725. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7726. std::string::npos);
  7727. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7728. std::string::npos);
  7729. }
  7730. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7731. Ranges ranges;
  7732. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7733. ranges.emplace_back(0, -1);
  7734. }
  7735. auto res = cli_.Get("/streamed-with-range?error",
  7736. Headers{{make_range_header(ranges)}});
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7739. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7740. EXPECT_EQ(false, res->has_header("Content-Range"));
  7741. EXPECT_EQ(0U, res->body.size());
  7742. }
  7743. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7744. auto res = cli_.Get("/streamed-with-range",
  7745. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7747. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7748. EXPECT_EQ(5U, res->body.size());
  7749. // Check that overlapping ranges are coalesced into a single range
  7750. EXPECT_EQ("bcdef", res->body);
  7751. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7752. // Should be single range, not multipart
  7753. EXPECT_TRUE(res->has_header("Content-Range"));
  7754. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7755. }
  7756. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7757. auto res = cli_.Get("/streamed-with-range",
  7758. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7760. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7761. EXPECT_EQ(268U, res->body.size());
  7762. // Check that both range contents are present
  7763. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7764. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7765. // Check that Content-Range headers are present for both ranges
  7766. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7767. std::string::npos);
  7768. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7769. std::string::npos);
  7770. }
  7771. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7772. auto res = cli_.Get("/streamed-with-range",
  7773. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7775. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7776. EXPECT_EQ(269U, res->body.size());
  7777. // Check that both duplicate range contents are present
  7778. size_t first_abc = res->body.find("abc\r\n");
  7779. EXPECT_TRUE(first_abc != std::string::npos);
  7780. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7781. EXPECT_TRUE(second_abc != std::string::npos);
  7782. // Check that Content-Range headers are present for both ranges
  7783. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7784. EXPECT_TRUE(first_range != std::string::npos);
  7785. size_t second_range =
  7786. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7787. EXPECT_TRUE(second_range != std::string::npos);
  7788. }
  7789. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7790. auto res =
  7791. cli_.Get("/streamed-with-range?error",
  7792. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7794. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7795. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7796. EXPECT_EQ(false, res->has_header("Content-Range"));
  7797. EXPECT_EQ(0U, res->body.size());
  7798. }
  7799. TEST_F(ServerTest, GetStreamedEndless) {
  7800. uint64_t offset = 0;
  7801. auto res = cli_.Get("/streamed-cancel",
  7802. [&](const char * /*data*/, uint64_t data_length) {
  7803. if (offset < 100) {
  7804. offset += data_length;
  7805. return true;
  7806. }
  7807. return false;
  7808. });
  7809. ASSERT_TRUE(!res);
  7810. EXPECT_EQ(Error::Canceled, res.error());
  7811. }
  7812. TEST_F(ServerTest, ClientStop) {
  7813. std::atomic_size_t count{4};
  7814. std::vector<std::thread> threads;
  7815. for (auto i = count.load(); i != 0; --i) {
  7816. threads.emplace_back([&]() {
  7817. auto res = cli_.Get("/streamed-cancel",
  7818. [&](const char *, uint64_t) { return true; });
  7819. --count;
  7820. ASSERT_TRUE(!res);
  7821. EXPECT_TRUE(res.error() == Error::Canceled ||
  7822. res.error() == Error::Read || res.error() == Error::Write);
  7823. });
  7824. }
  7825. std::this_thread::sleep_for(std::chrono::seconds(2));
  7826. while (count != 0) {
  7827. cli_.stop();
  7828. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7829. }
  7830. for (auto &t : threads) {
  7831. t.join();
  7832. }
  7833. }
  7834. TEST_F(ServerTest, GetWithRange1) {
  7835. auto res = cli_.Get("/with-range", Headers{
  7836. make_range_header({{3, 5}}),
  7837. {"Accept-Encoding", ""},
  7838. });
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7841. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7842. EXPECT_EQ(true, res->has_header("Content-Range"));
  7843. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7844. EXPECT_EQ(std::string("def"), res->body);
  7845. }
  7846. TEST_F(ServerTest, GetWithRange2) {
  7847. auto res = cli_.Get("/with-range", Headers{
  7848. make_range_header({{1, -1}}),
  7849. {"Accept-Encoding", ""},
  7850. });
  7851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7852. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7853. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7854. EXPECT_EQ(true, res->has_header("Content-Range"));
  7855. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7856. EXPECT_EQ(std::string("bcdefg"), res->body);
  7857. }
  7858. TEST_F(ServerTest, GetWithRange3) {
  7859. auto res = cli_.Get("/with-range", Headers{
  7860. make_range_header({{0, 0}}),
  7861. {"Accept-Encoding", ""},
  7862. });
  7863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7864. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7865. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7866. EXPECT_EQ(true, res->has_header("Content-Range"));
  7867. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7868. EXPECT_EQ(std::string("a"), res->body);
  7869. }
  7870. TEST_F(ServerTest, GetWithRange4) {
  7871. auto res = cli_.Get("/with-range", Headers{
  7872. make_range_header({{-1, 2}}),
  7873. {"Accept-Encoding", ""},
  7874. });
  7875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7876. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7877. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7878. EXPECT_EQ(true, res->has_header("Content-Range"));
  7879. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7880. EXPECT_EQ(std::string("fg"), res->body);
  7881. }
  7882. TEST_F(ServerTest, GetWithRange5) {
  7883. auto res = cli_.Get("/with-range", Headers{
  7884. make_range_header({{0, 5}}),
  7885. {"Accept-Encoding", ""},
  7886. });
  7887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7888. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7889. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7890. EXPECT_EQ(true, res->has_header("Content-Range"));
  7891. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7892. EXPECT_EQ(std::string("abcdef"), res->body);
  7893. }
  7894. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7895. auto res =
  7896. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7898. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7899. }
  7900. TEST_F(ServerTest, GetWithRangeMultipart) {
  7901. auto res =
  7902. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7904. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7905. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7906. EXPECT_EQ(false, res->has_header("Content-Range"));
  7907. EXPECT_EQ(267U, res->body.size());
  7908. }
  7909. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7910. auto res = cli_.Get("/with-range",
  7911. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7913. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7914. }
  7915. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7916. auto res = cli_.Get("/with-range-customized-response",
  7917. Headers{{make_range_header({{1, 2}})}});
  7918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7919. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7920. EXPECT_EQ(true, res->has_header("Content-Length"));
  7921. EXPECT_EQ(false, res->has_header("Content-Range"));
  7922. EXPECT_EQ(JSON_DATA, res->body);
  7923. }
  7924. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7925. auto res = cli_.Get("/with-range-customized-response",
  7926. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7928. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7929. EXPECT_EQ(true, res->has_header("Content-Length"));
  7930. EXPECT_EQ(false, res->has_header("Content-Range"));
  7931. EXPECT_EQ(JSON_DATA, res->body);
  7932. }
  7933. TEST_F(ServerTest, Issue1772) {
  7934. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7936. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7937. }
  7938. TEST_F(ServerTest, Issue609) {
  7939. auto res = cli_.Delete("/issue609");
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ(StatusCode::OK_200, res->status);
  7942. EXPECT_EQ(std::string("ok"), res->body);
  7943. }
  7944. TEST_F(ServerTest, GetStreamedChunked) {
  7945. auto res = cli_.Get("/streamed-chunked");
  7946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7947. EXPECT_EQ(StatusCode::OK_200, res->status);
  7948. EXPECT_EQ(std::string("123456789"), res->body);
  7949. }
  7950. TEST_F(ServerTest, GetStreamedChunked2) {
  7951. auto res = cli_.Get("/streamed-chunked2");
  7952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7953. EXPECT_EQ(StatusCode::OK_200, res->status);
  7954. EXPECT_EQ(std::string("123456789"), res->body);
  7955. }
  7956. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7957. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7959. EXPECT_EQ(StatusCode::OK_200, res->status);
  7960. EXPECT_EQ(std::string("123456789"), res->body);
  7961. EXPECT_TRUE(res->has_header("Trailer"));
  7962. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7963. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7964. // Trailers are now stored separately from headers (security fix)
  7965. EXPECT_EQ(2U, res->trailers.size());
  7966. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7967. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7968. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7969. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7970. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7971. // Verify trailers are NOT in headers (security verification)
  7972. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7973. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7974. }
  7975. TEST_F(ServerTest, LargeChunkedPost) {
  7976. Request req;
  7977. req.method = "POST";
  7978. req.path = "/large-chunked";
  7979. std::string host_and_port;
  7980. host_and_port += HOST;
  7981. host_and_port += ":";
  7982. host_and_port += std::to_string(PORT);
  7983. req.headers.emplace("Host", host_and_port.c_str());
  7984. req.headers.emplace("Accept", "*/*");
  7985. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7986. req.headers.emplace("Content-Type", "text/plain");
  7987. req.headers.emplace("Content-Length", "0");
  7988. req.headers.emplace("Transfer-Encoding", "chunked");
  7989. std::string long_string(30 * 1024u, 'a');
  7990. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7991. // Attempt to make a large enough post to exceed OS buffers, to test that
  7992. // the server handles short reads if the full chunk data isn't available.
  7993. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7994. auto res = std::make_shared<Response>();
  7995. auto error = Error::Success;
  7996. auto ret = cli_.send(req, *res, error);
  7997. ASSERT_TRUE(ret);
  7998. EXPECT_EQ(StatusCode::OK_200, res->status);
  7999. }
  8000. TEST_F(ServerTest, GetMethodRemoteAddr) {
  8001. auto res = cli_.Get("/remote_addr");
  8002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8003. EXPECT_EQ(StatusCode::OK_200, res->status);
  8004. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8005. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  8006. }
  8007. TEST_F(ServerTest, GetMethodLocalAddr) {
  8008. auto res = cli_.Get("/local_addr");
  8009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8010. EXPECT_EQ(StatusCode::OK_200, res->status);
  8011. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8012. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  8013. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  8014. }
  8015. TEST_F(ServerTest, HTTPResponseSplitting) {
  8016. auto res = cli_.Get("/http_response_splitting");
  8017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8018. EXPECT_EQ(StatusCode::OK_200, res->status);
  8019. }
  8020. TEST_F(ServerTest, SlowRequest) {
  8021. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8022. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8023. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8024. }
  8025. #if 0
  8026. TEST_F(ServerTest, SlowPost) {
  8027. char buffer[64 * 1024];
  8028. memset(buffer, 0x42, sizeof(buffer));
  8029. auto res = cli_.Post(
  8030. "/slowpost", 64 * 1024 * 1024,
  8031. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8032. auto ret = sink.write(buffer, sizeof(buffer));
  8033. EXPECT_TRUE(ret);
  8034. return true;
  8035. },
  8036. "text/plain");
  8037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8038. EXPECT_EQ(StatusCode::OK_200, res->status);
  8039. }
  8040. TEST_F(ServerTest, SlowPostFail) {
  8041. char buffer[64 * 1024];
  8042. memset(buffer, 0x42, sizeof(buffer));
  8043. cli_.set_write_timeout(std::chrono::seconds(0));
  8044. auto res = cli_.Post(
  8045. "/slowpost", 64 * 1024 * 1024,
  8046. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8047. sink.write(buffer, sizeof(buffer));
  8048. return true;
  8049. },
  8050. "text/plain");
  8051. ASSERT_TRUE(!res);
  8052. EXPECT_EQ(Error::Write, res.error());
  8053. }
  8054. #endif
  8055. TEST_F(ServerTest, Put) {
  8056. auto res = cli_.Put("/put", "PUT", "text/plain");
  8057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8058. EXPECT_EQ(StatusCode::OK_200, res->status);
  8059. EXPECT_EQ("PUT", res->body);
  8060. }
  8061. TEST_F(ServerTest, PutWithContentProvider) {
  8062. auto res = cli_.Put(
  8063. "/put", 3,
  8064. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8065. sink.os << "PUT";
  8066. return true;
  8067. },
  8068. "text/plain");
  8069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8070. EXPECT_EQ(StatusCode::OK_200, res->status);
  8071. EXPECT_EQ("PUT", res->body);
  8072. }
  8073. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8074. auto res = cli_.Post(
  8075. "/post", 42,
  8076. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8077. return false;
  8078. },
  8079. "text/plain");
  8080. ASSERT_TRUE(!res);
  8081. EXPECT_EQ(Error::Canceled, res.error());
  8082. }
  8083. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8084. auto res = cli_.Put(
  8085. "/put",
  8086. [](size_t /*offset*/, DataSink &sink) {
  8087. sink.os << "PUT";
  8088. sink.done();
  8089. return true;
  8090. },
  8091. "text/plain");
  8092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8093. EXPECT_EQ(StatusCode::OK_200, res->status);
  8094. EXPECT_EQ("PUT", res->body);
  8095. }
  8096. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8097. auto res = cli_.Post(
  8098. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8099. "text/plain");
  8100. ASSERT_TRUE(!res);
  8101. EXPECT_EQ(Error::Canceled, res.error());
  8102. }
  8103. TEST_F(ServerTest, PostLoopBack) {
  8104. std::string body;
  8105. auto res = cli_.Post(
  8106. "/post-loopback", 9,
  8107. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8108. EXPECT_EQ(9u, length);
  8109. sink.write("123", 3);
  8110. sink.write("456", 3);
  8111. sink.write("789", 3);
  8112. return true;
  8113. },
  8114. "text/plain",
  8115. [&body](const char *data, size_t data_length) {
  8116. body.append(data, data_length);
  8117. return true;
  8118. });
  8119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8120. EXPECT_EQ(StatusCode::OK_200, res->status);
  8121. EXPECT_EQ("123456789", body);
  8122. }
  8123. TEST_F(ServerTest, PutLoopBack) {
  8124. std::string body;
  8125. auto res = cli_.Put(
  8126. "/put-loopback", 9,
  8127. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8128. EXPECT_EQ(9u, length);
  8129. sink.write("123", 3);
  8130. sink.write("456", 3);
  8131. sink.write("789", 3);
  8132. return true;
  8133. },
  8134. "text/plain",
  8135. [&body](const char *data, size_t data_length) {
  8136. body.append(data, data_length);
  8137. return true;
  8138. });
  8139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8140. EXPECT_EQ(StatusCode::OK_200, res->status);
  8141. EXPECT_EQ("123456789", body);
  8142. }
  8143. TEST_F(ServerTest, PatchLoopBack) {
  8144. std::string body;
  8145. auto res = cli_.Patch(
  8146. "/patch-loopback", 9,
  8147. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8148. EXPECT_EQ(9u, length);
  8149. sink.write("123", 3);
  8150. sink.write("456", 3);
  8151. sink.write("789", 3);
  8152. return true;
  8153. },
  8154. "text/plain",
  8155. [&body](const char *data, size_t data_length) {
  8156. body.append(data, data_length);
  8157. return true;
  8158. });
  8159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8160. EXPECT_EQ(StatusCode::OK_200, res->status);
  8161. EXPECT_EQ("123456789", body);
  8162. }
  8163. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8164. std::string body;
  8165. auto res = cli_.Post(
  8166. "/post-loopback",
  8167. [](size_t /*offset*/, DataSink &sink) {
  8168. sink.write("123", 3);
  8169. sink.write("456", 3);
  8170. sink.write("789", 3);
  8171. sink.done();
  8172. return true;
  8173. },
  8174. "text/plain",
  8175. [&body](const char *data, size_t data_length) {
  8176. body.append(data, data_length);
  8177. return true;
  8178. });
  8179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8180. EXPECT_EQ(StatusCode::OK_200, res->status);
  8181. EXPECT_EQ("123456789", body);
  8182. }
  8183. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8184. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8185. cli_.set_compress(true);
  8186. auto res = cli_.Put(
  8187. "/put", 3,
  8188. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8189. sink.os << "PUT";
  8190. return true;
  8191. },
  8192. "text/plain");
  8193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8194. EXPECT_EQ(StatusCode::OK_200, res->status);
  8195. EXPECT_EQ("PUT", res->body);
  8196. }
  8197. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8198. cli_.set_compress(true);
  8199. auto res = cli_.Post(
  8200. "/post", 42,
  8201. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8202. return false;
  8203. },
  8204. "text/plain");
  8205. ASSERT_TRUE(!res);
  8206. EXPECT_EQ(Error::Canceled, res.error());
  8207. }
  8208. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8209. cli_.set_compress(true);
  8210. auto res = cli_.Put(
  8211. "/put",
  8212. [](size_t /*offset*/, DataSink &sink) {
  8213. sink.os << "PUT";
  8214. sink.done();
  8215. return true;
  8216. },
  8217. "text/plain");
  8218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8219. EXPECT_EQ(StatusCode::OK_200, res->status);
  8220. EXPECT_EQ("PUT", res->body);
  8221. }
  8222. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8223. cli_.set_compress(true);
  8224. auto res = cli_.Post(
  8225. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8226. "text/plain");
  8227. ASSERT_TRUE(!res);
  8228. EXPECT_EQ(Error::Canceled, res.error());
  8229. }
  8230. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8231. cli_.set_compress(true);
  8232. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8234. EXPECT_EQ(StatusCode::OK_200, res->status);
  8235. EXPECT_EQ(LARGE_DATA, res->body);
  8236. }
  8237. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8238. #ifdef CPPHTTPLIB_SSL_ENABLED
  8239. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8240. Client cli(s.c_str());
  8241. cli.enable_server_certificate_verification(false);
  8242. #else
  8243. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8244. Client cli(s.c_str());
  8245. #endif
  8246. cli.set_compress(true);
  8247. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8249. EXPECT_EQ(StatusCode::OK_200, res->status);
  8250. EXPECT_EQ(LARGE_DATA, res->body);
  8251. // The compressed size should be less than a 10th of the original. May vary
  8252. // depending on the zlib library.
  8253. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8254. static_cast<uint64_t>(10 * 1024 * 1024));
  8255. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8256. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8257. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8258. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8259. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8260. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8261. #endif
  8262. }
  8263. TEST_F(ServerTest, PutContentWithDeflate) {
  8264. cli_.set_compress(false);
  8265. Headers headers;
  8266. headers.emplace("Content-Encoding", "deflate");
  8267. // PUT in deflate format:
  8268. auto res = cli_.Put("/put", headers,
  8269. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8271. EXPECT_EQ(StatusCode::OK_200, res->status);
  8272. EXPECT_EQ("PUT", res->body);
  8273. }
  8274. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8275. Headers headers;
  8276. headers.emplace("Accept-Encoding", "gzip, deflate");
  8277. auto res = cli_.Get("/streamed-chunked", headers);
  8278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8279. EXPECT_EQ(StatusCode::OK_200, res->status);
  8280. EXPECT_EQ(std::string("123456789"), res->body);
  8281. }
  8282. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8283. Headers headers;
  8284. headers.emplace("Accept-Encoding", "gzip, deflate");
  8285. auto res = cli_.Get("/streamed-chunked2", headers);
  8286. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8287. EXPECT_EQ(StatusCode::OK_200, res->status);
  8288. EXPECT_EQ(std::string("123456789"), res->body);
  8289. }
  8290. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8291. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8293. EXPECT_EQ(StatusCode::OK_200, res->status);
  8294. }
  8295. TEST(GzipDecompressor, ChunkedDecompression) {
  8296. std::string data;
  8297. for (size_t i = 0; i < 32 * 1024; ++i) {
  8298. data.push_back(static_cast<char>('a' + i % 26));
  8299. }
  8300. std::string compressed_data;
  8301. {
  8302. httplib::detail::gzip_compressor compressor;
  8303. bool result = compressor.compress(
  8304. data.data(), data.size(),
  8305. /*last=*/true,
  8306. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8307. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8308. compressed_data_size);
  8309. return true;
  8310. });
  8311. ASSERT_TRUE(result);
  8312. }
  8313. std::string decompressed_data;
  8314. {
  8315. httplib::detail::gzip_decompressor decompressor;
  8316. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8317. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8318. size_t chunk_size = 130;
  8319. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8320. chunk_begin += chunk_size) {
  8321. size_t current_chunk_size =
  8322. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8323. bool result = decompressor.decompress(
  8324. compressed_data.data() + chunk_begin, current_chunk_size,
  8325. [&](const char *decompressed_data_chunk,
  8326. size_t decompressed_data_chunk_size) {
  8327. decompressed_data.insert(decompressed_data.size(),
  8328. decompressed_data_chunk,
  8329. decompressed_data_chunk_size);
  8330. return true;
  8331. });
  8332. ASSERT_TRUE(result);
  8333. }
  8334. }
  8335. ASSERT_EQ(data, decompressed_data);
  8336. }
  8337. TEST(GzipDecompressor, DeflateDecompression) {
  8338. std::string original_text = "Raw deflate without gzip";
  8339. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8340. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8341. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8342. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8343. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8344. std::string decompressed_data;
  8345. {
  8346. httplib::detail::gzip_decompressor decompressor;
  8347. bool result = decompressor.decompress(
  8348. compressed_data.data(), compressed_data.size(),
  8349. [&](const char *decompressed_data_chunk,
  8350. size_t decompressed_data_chunk_size) {
  8351. decompressed_data.insert(decompressed_data.size(),
  8352. decompressed_data_chunk,
  8353. decompressed_data_chunk_size);
  8354. return true;
  8355. });
  8356. ASSERT_TRUE(result);
  8357. }
  8358. ASSERT_EQ(original_text, decompressed_data);
  8359. }
  8360. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8361. std::string original_text = "Raw deflate without gzip";
  8362. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8363. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8364. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8365. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8366. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8367. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8368. std::string decompressed_data;
  8369. {
  8370. httplib::detail::gzip_decompressor decompressor;
  8371. bool result = decompressor.decompress(
  8372. compressed_data.data(), compressed_data.size(),
  8373. [&](const char *decompressed_data_chunk,
  8374. size_t decompressed_data_chunk_size) {
  8375. decompressed_data.insert(decompressed_data.size(),
  8376. decompressed_data_chunk,
  8377. decompressed_data_chunk_size);
  8378. return true;
  8379. });
  8380. ASSERT_TRUE(result);
  8381. }
  8382. ASSERT_EQ(original_text, decompressed_data);
  8383. }
  8384. #endif
  8385. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8386. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8387. Headers headers;
  8388. headers.emplace("Accept-Encoding", "br");
  8389. auto res = cli_.Get("/streamed-chunked", headers);
  8390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8391. EXPECT_EQ(StatusCode::OK_200, res->status);
  8392. EXPECT_EQ(std::string("123456789"), res->body);
  8393. }
  8394. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8395. Headers headers;
  8396. headers.emplace("Accept-Encoding", "br");
  8397. auto res = cli_.Get("/streamed-chunked2", headers);
  8398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8399. EXPECT_EQ(StatusCode::OK_200, res->status);
  8400. EXPECT_EQ(std::string("123456789"), res->body);
  8401. }
  8402. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8403. cli_.set_compress(true);
  8404. auto res = cli_.Put(
  8405. "/put", 3,
  8406. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8407. sink.os << "PUT";
  8408. return true;
  8409. },
  8410. "text/plain");
  8411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8412. EXPECT_EQ(StatusCode::OK_200, res->status);
  8413. EXPECT_EQ("PUT", res->body);
  8414. }
  8415. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8416. cli_.set_compress(true);
  8417. auto res = cli_.Put(
  8418. "/put",
  8419. [](size_t /*offset*/, DataSink &sink) {
  8420. sink.os << "PUT";
  8421. sink.done();
  8422. return true;
  8423. },
  8424. "text/plain");
  8425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8426. EXPECT_EQ(StatusCode::OK_200, res->status);
  8427. EXPECT_EQ("PUT", res->body);
  8428. }
  8429. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8430. cli_.set_compress(true);
  8431. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8433. EXPECT_EQ(StatusCode::OK_200, res->status);
  8434. EXPECT_EQ(LARGE_DATA, res->body);
  8435. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8436. }
  8437. #endif
  8438. TEST_F(ServerTest, Patch) {
  8439. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8441. EXPECT_EQ(StatusCode::OK_200, res->status);
  8442. EXPECT_EQ("PATCH", res->body);
  8443. }
  8444. TEST_F(ServerTest, Delete) {
  8445. auto res = cli_.Delete("/delete");
  8446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8447. EXPECT_EQ(StatusCode::OK_200, res->status);
  8448. EXPECT_EQ("DELETE", res->body);
  8449. }
  8450. TEST_F(ServerTest, DeleteContentReceiver) {
  8451. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8453. EXPECT_EQ(StatusCode::OK_200, res->status);
  8454. EXPECT_EQ("content", res->body);
  8455. }
  8456. TEST_F(ServerTest, Options) {
  8457. auto res = cli_.Options("*");
  8458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8459. EXPECT_EQ(StatusCode::OK_200, res->status);
  8460. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8461. EXPECT_TRUE(res->body.empty());
  8462. }
  8463. TEST_F(ServerTest, URL) {
  8464. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8466. EXPECT_EQ(StatusCode::OK_200, res->status);
  8467. }
  8468. TEST_F(ServerTest, ArrayParam) {
  8469. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8471. EXPECT_EQ(StatusCode::OK_200, res->status);
  8472. }
  8473. TEST_F(ServerTest, ArrayParamValues) {
  8474. auto res =
  8475. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8477. EXPECT_EQ(StatusCode::OK_200, res->status);
  8478. }
  8479. TEST_F(ServerTest, NoMultipleHeaders) {
  8480. Headers headers = {{"Content-Length", "5"}};
  8481. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8482. "text/plain");
  8483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8484. EXPECT_EQ(StatusCode::OK_200, res->status);
  8485. }
  8486. TEST_F(ServerTest, PostContentReceiver) {
  8487. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8489. ASSERT_EQ(StatusCode::OK_200, res->status);
  8490. ASSERT_EQ("content", res->body);
  8491. }
  8492. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8493. UploadFormDataItems items = {
  8494. {"text1", "text default", "", ""},
  8495. {"text2", "aωb", "", ""},
  8496. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8497. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8498. {"file3", "", "", "application/octet-stream"},
  8499. };
  8500. auto res = cli_.Post("/content_receiver", items);
  8501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8502. EXPECT_EQ(StatusCode::OK_200, res->status);
  8503. }
  8504. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8505. UploadFormDataItems items = {
  8506. {"text1", "text default", "", ""},
  8507. {"text2", "aωb", "", ""},
  8508. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8509. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8510. {"file3", "", "", "application/octet-stream"},
  8511. };
  8512. auto boundary = std::string("+++++");
  8513. std::string body;
  8514. for (const auto &item : items) {
  8515. body += "--" + boundary + "\r\n";
  8516. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8517. if (!item.filename.empty()) {
  8518. body += "; filename=\"" + item.filename + "\"";
  8519. }
  8520. body += "\r\n";
  8521. if (!item.content_type.empty()) {
  8522. body += "Content-Type: " + item.content_type + "\r\n";
  8523. }
  8524. body += "\r\n";
  8525. body += item.content + "\r\n";
  8526. }
  8527. body += "--" + boundary + "--\r\n";
  8528. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8529. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8531. EXPECT_EQ(StatusCode::OK_200, res->status);
  8532. }
  8533. TEST(MultipartFormDataTest, FieldEscaping) {
  8534. Server svr;
  8535. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8536. const ContentReader &content_reader) {
  8537. ASSERT_TRUE(req.is_multipart_form_data());
  8538. std::vector<FormData> received;
  8539. content_reader(
  8540. [&](const FormData &file) {
  8541. received.push_back(file);
  8542. return true;
  8543. },
  8544. [&](const char *data, size_t data_length) {
  8545. received.back().content.append(data, data_length);
  8546. return true;
  8547. });
  8548. // '"', CR and LF in names and filenames are escaped following the
  8549. // WHATWG HTML standard, so each part still parses as a single part
  8550. // with no injected headers. Content types get CR/LF escaped too,
  8551. // while '"' (legal there, e.g. quoted charset) is preserved.
  8552. ASSERT_EQ(4U, received.size());
  8553. EXPECT_EQ("na%22me", received[0].name);
  8554. EXPECT_EQ("quoted name", received[0].content);
  8555. EXPECT_EQ("file", received[1].name);
  8556. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8557. received[1].filename);
  8558. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8559. EXPECT_EQ("injected", received[1].content);
  8560. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8561. EXPECT_EQ("my%22file.txt", received[2].filename);
  8562. EXPECT_EQ("cr lf name", received[2].content);
  8563. EXPECT_EQ("typed", received[3].name);
  8564. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8565. received[3].content_type);
  8566. EXPECT_EQ("typed content", received[3].content);
  8567. });
  8568. auto port = svr.bind_to_any_port("localhost");
  8569. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8570. auto se = detail::scope_exit([&] {
  8571. svr.stop();
  8572. t.join();
  8573. ASSERT_FALSE(svr.is_running());
  8574. });
  8575. svr.wait_until_ready();
  8576. Client cli("localhost", port);
  8577. UploadFormDataItems items = {
  8578. {"na\"me", "quoted name", "", ""},
  8579. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8580. "application/octet-stream"},
  8581. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8582. {"typed", "typed content", "",
  8583. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8584. };
  8585. auto res = cli.Post("/post", items);
  8586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8587. EXPECT_EQ(StatusCode::OK_200, res->status);
  8588. }
  8589. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8590. const UploadFormDataItems items = {
  8591. {"name1", "Content 1", "", ""},
  8592. {"name2", "Content 2", "file2.txt", "text/plain"},
  8593. };
  8594. Server svr;
  8595. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8596. const ContentReader &content_reader) {
  8597. ASSERT_TRUE(req.is_multipart_form_data());
  8598. std::vector<FormData> received;
  8599. content_reader(
  8600. [&](const FormData &file) {
  8601. received.push_back(file);
  8602. return true;
  8603. },
  8604. [&](const char *data, size_t data_length) {
  8605. received.back().content.append(data, data_length);
  8606. return true;
  8607. });
  8608. ASSERT_EQ(2U, received.size());
  8609. EXPECT_EQ("name1", received[0].name);
  8610. EXPECT_EQ("Content 1", received[0].content);
  8611. EXPECT_EQ("name2", received[1].name);
  8612. EXPECT_EQ("Content 2", received[1].content);
  8613. EXPECT_EQ("file2.txt", received[1].filename);
  8614. EXPECT_EQ("text/plain", received[1].content_type);
  8615. });
  8616. auto port = svr.bind_to_any_port("localhost");
  8617. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8618. auto se = detail::scope_exit([&] {
  8619. svr.stop();
  8620. t.join();
  8621. ASSERT_FALSE(svr.is_running());
  8622. });
  8623. svr.wait_until_ready();
  8624. Client cli("localhost", port);
  8625. // Whole-body serialization with a generated boundary
  8626. {
  8627. MultipartFormDataWriter writer;
  8628. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8629. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8630. writer.content_type());
  8631. auto body = writer.serialize(items);
  8632. EXPECT_EQ(body.size(), writer.content_length(items));
  8633. auto res = cli.Post("/post", body, writer.content_type());
  8634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8635. EXPECT_EQ(StatusCode::OK_200, res->status);
  8636. }
  8637. // Per-part framing with a custom boundary via a content provider
  8638. {
  8639. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8640. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8641. MultipartFormDataWriter writer("custom-boundary_123");
  8642. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8643. std::string body;
  8644. for (const auto &item : items) {
  8645. body += writer.item_begin(item);
  8646. body += item.content;
  8647. body += MultipartFormDataWriter::item_end();
  8648. }
  8649. body += writer.finish();
  8650. EXPECT_EQ(body.size(), writer.content_length(items));
  8651. auto res = cli.Post(
  8652. "/post", body.size(),
  8653. [&](size_t offset, size_t length, DataSink &sink) {
  8654. sink.write(body.data() + offset, length);
  8655. return true;
  8656. },
  8657. writer.content_type());
  8658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8659. EXPECT_EQ(StatusCode::OK_200, res->status);
  8660. }
  8661. }
  8662. TEST_F(ServerTest, PostContentReceiverGzip) {
  8663. cli_.set_compress(true);
  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, PutContentReceiver) {
  8670. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8672. ASSERT_EQ(StatusCode::OK_200, res->status);
  8673. ASSERT_EQ("content", res->body);
  8674. }
  8675. TEST_F(ServerTest, PatchContentReceiver) {
  8676. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8678. ASSERT_EQ(StatusCode::OK_200, res->status);
  8679. ASSERT_EQ("content", res->body);
  8680. }
  8681. template <typename ClientType>
  8682. void TestWithHeadersAndContentReceiver(
  8683. ClientType &cli,
  8684. std::function<Result(ClientType &, const std::string &, const Headers &,
  8685. const std::string &, const std::string &,
  8686. ContentReceiver, DownloadProgress)>
  8687. request_func) {
  8688. Headers headers;
  8689. headers.emplace("X-Custom-Header", "test-value");
  8690. std::string received_body;
  8691. auto res = request_func(
  8692. cli, "/content_receiver", headers, "content", "application/json",
  8693. [&](const char *data, size_t data_length) {
  8694. received_body.append(data, data_length);
  8695. return true;
  8696. },
  8697. nullptr);
  8698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8699. EXPECT_EQ(StatusCode::OK_200, res->status);
  8700. EXPECT_EQ("content", received_body);
  8701. }
  8702. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8703. #ifdef CPPHTTPLIB_SSL_ENABLED
  8704. using ClientT = SSLClient;
  8705. #else
  8706. using ClientT = Client;
  8707. #endif
  8708. TestWithHeadersAndContentReceiver<ClientT>(
  8709. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8710. const std::string &body, const std::string &content_type,
  8711. ContentReceiver receiver, DownloadProgress progress) {
  8712. return cli.Post(path, headers, body, content_type, receiver, progress);
  8713. });
  8714. }
  8715. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8716. #ifdef CPPHTTPLIB_SSL_ENABLED
  8717. using ClientT = SSLClient;
  8718. #else
  8719. using ClientT = Client;
  8720. #endif
  8721. TestWithHeadersAndContentReceiver<ClientT>(
  8722. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8723. const std::string &body, const std::string &content_type,
  8724. ContentReceiver receiver, DownloadProgress progress) {
  8725. return cli.Put(path, headers, body, content_type, receiver, progress);
  8726. });
  8727. }
  8728. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8729. #ifdef CPPHTTPLIB_SSL_ENABLED
  8730. using ClientT = SSLClient;
  8731. #else
  8732. using ClientT = Client;
  8733. #endif
  8734. TestWithHeadersAndContentReceiver<ClientT>(
  8735. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8736. const std::string &body, const std::string &content_type,
  8737. ContentReceiver receiver, DownloadProgress progress) {
  8738. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8739. });
  8740. }
  8741. template <typename ClientType>
  8742. void TestWithHeadersAndContentReceiverWithProgress(
  8743. ClientType &cli,
  8744. std::function<Result(ClientType &, const std::string &, const Headers &,
  8745. const std::string &, const std::string &,
  8746. ContentReceiver, DownloadProgress)>
  8747. request_func) {
  8748. Headers headers;
  8749. headers.emplace("X-Test-Header", "progress-test");
  8750. std::string received_body;
  8751. auto progress_called = false;
  8752. auto res = request_func(
  8753. cli, "/content_receiver", headers, "content", "text/plain",
  8754. [&](const char *data, size_t data_length) {
  8755. received_body.append(data, data_length);
  8756. return true;
  8757. },
  8758. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8759. progress_called = true;
  8760. return true;
  8761. });
  8762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8763. EXPECT_EQ(StatusCode::OK_200, res->status);
  8764. EXPECT_EQ("content", received_body);
  8765. EXPECT_TRUE(progress_called);
  8766. }
  8767. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8768. #ifdef CPPHTTPLIB_SSL_ENABLED
  8769. using ClientT = SSLClient;
  8770. #else
  8771. using ClientT = Client;
  8772. #endif
  8773. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8774. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8775. const std::string &body, const std::string &content_type,
  8776. ContentReceiver receiver, DownloadProgress progress) {
  8777. return cli.Post(path, headers, body, content_type, receiver, progress);
  8778. });
  8779. }
  8780. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8781. #ifdef CPPHTTPLIB_SSL_ENABLED
  8782. using ClientT = SSLClient;
  8783. #else
  8784. using ClientT = Client;
  8785. #endif
  8786. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8787. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8788. const std::string &body, const std::string &content_type,
  8789. ContentReceiver receiver, DownloadProgress progress) {
  8790. return cli.Put(path, headers, body, content_type, receiver, progress);
  8791. });
  8792. }
  8793. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8794. #ifdef CPPHTTPLIB_SSL_ENABLED
  8795. using ClientT = SSLClient;
  8796. #else
  8797. using ClientT = Client;
  8798. #endif
  8799. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8800. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8801. const std::string &body, const std::string &content_type,
  8802. ContentReceiver receiver, DownloadProgress progress) {
  8803. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8804. });
  8805. }
  8806. template <typename ClientType>
  8807. void TestWithHeadersAndContentReceiverError(
  8808. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8809. const Headers &, const std::string &,
  8810. const std::string &, ContentReceiver)>
  8811. request_func) {
  8812. Headers headers;
  8813. headers.emplace("X-Error-Test", "true");
  8814. std::string received_body;
  8815. auto receiver_failed = false;
  8816. auto res =
  8817. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8818. [&](const char *data, size_t data_length) {
  8819. received_body.append(data, data_length);
  8820. receiver_failed = true;
  8821. return false;
  8822. });
  8823. ASSERT_FALSE(res);
  8824. EXPECT_TRUE(receiver_failed);
  8825. }
  8826. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8827. #ifdef CPPHTTPLIB_SSL_ENABLED
  8828. using ClientT = SSLClient;
  8829. #else
  8830. using ClientT = Client;
  8831. #endif
  8832. TestWithHeadersAndContentReceiverError<ClientT>(
  8833. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8834. const std::string &body, const std::string &content_type,
  8835. ContentReceiver receiver) {
  8836. return cli.Post(path, headers, body, content_type, receiver);
  8837. });
  8838. }
  8839. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8840. #ifdef CPPHTTPLIB_SSL_ENABLED
  8841. using ClientT = SSLClient;
  8842. #else
  8843. using ClientT = Client;
  8844. #endif
  8845. TestWithHeadersAndContentReceiverError<ClientT>(
  8846. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8847. const std::string &body, const std::string &content_type,
  8848. ContentReceiver receiver) {
  8849. return cli.Put(path, headers, body, content_type, receiver);
  8850. });
  8851. }
  8852. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8853. #ifdef CPPHTTPLIB_SSL_ENABLED
  8854. using ClientT = SSLClient;
  8855. #else
  8856. using ClientT = Client;
  8857. #endif
  8858. TestWithHeadersAndContentReceiverError<ClientT>(
  8859. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8860. const std::string &body, const std::string &content_type,
  8861. ContentReceiver receiver) {
  8862. return cli.Patch(path, headers, body, content_type, receiver);
  8863. });
  8864. }
  8865. TEST_F(ServerTest, PostQueryStringAndBody) {
  8866. auto res =
  8867. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8869. ASSERT_EQ(StatusCode::OK_200, res->status);
  8870. }
  8871. TEST_F(ServerTest, HTTP2Magic) {
  8872. Request req;
  8873. req.method = "PRI";
  8874. req.path = "*";
  8875. req.body = "SM";
  8876. auto res = std::make_shared<Response>();
  8877. auto error = Error::Success;
  8878. auto ret = cli_.send(req, *res, error);
  8879. ASSERT_TRUE(ret);
  8880. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8881. }
  8882. TEST_F(ServerTest, KeepAlive) {
  8883. auto res = cli_.Get("/hi");
  8884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8885. EXPECT_EQ(StatusCode::OK_200, res->status);
  8886. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8887. EXPECT_EQ("Hello World!", res->body);
  8888. res = cli_.Get("/hi");
  8889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8890. EXPECT_EQ(StatusCode::OK_200, res->status);
  8891. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8892. EXPECT_EQ("Hello World!", res->body);
  8893. res = cli_.Get("/hi");
  8894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8895. EXPECT_EQ(StatusCode::OK_200, res->status);
  8896. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8897. EXPECT_EQ("Hello World!", res->body);
  8898. res = cli_.Get("/not-exist");
  8899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8900. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8901. res = cli_.Post("/empty", "", "text/plain");
  8902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8903. EXPECT_EQ(StatusCode::OK_200, res->status);
  8904. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8905. EXPECT_EQ("empty", res->body);
  8906. EXPECT_EQ("close", res->get_header_value("Connection"));
  8907. res = cli_.Post(
  8908. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8909. "text/plain");
  8910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8911. EXPECT_EQ(StatusCode::OK_200, res->status);
  8912. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8913. EXPECT_EQ("empty", res->body);
  8914. cli_.set_keep_alive(false);
  8915. res = cli_.Get("/last-request");
  8916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8917. EXPECT_EQ(StatusCode::OK_200, res->status);
  8918. EXPECT_EQ("close", res->get_header_value("Connection"));
  8919. }
  8920. TEST_F(ServerTest, TooManyRedirect) {
  8921. cli_.set_follow_location(true);
  8922. auto res = cli_.Get("/redirect/0");
  8923. ASSERT_TRUE(!res);
  8924. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8925. }
  8926. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8927. Request req;
  8928. req.method = "FOOBAR";
  8929. req.path = "/hi";
  8930. cli_.set_keep_alive(true);
  8931. auto res = cli_.send(req);
  8932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8933. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8934. EXPECT_EQ("close", res->get_header_value("Connection"));
  8935. EXPECT_FALSE(cli_.is_socket_open());
  8936. }
  8937. TEST_F(ServerTest, CustomRouteReadsBody) {
  8938. const std::string xml =
  8939. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8940. Request req;
  8941. req.method = "PROPFIND";
  8942. req.path = "/dav/dir";
  8943. req.set_header("Depth", "1");
  8944. req.body = xml;
  8945. auto res = cli_.send(req);
  8946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8947. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8948. EXPECT_EQ(xml, res->body);
  8949. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8950. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8951. }
  8952. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8953. Request req;
  8954. req.method = "PROPFIND";
  8955. req.path = "/dav/42";
  8956. auto res = cli_.send(req);
  8957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8958. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8959. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8960. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8961. }
  8962. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8963. Request req;
  8964. req.method = "PROPFIND";
  8965. req.path = "/dav-re/123";
  8966. auto res = cli_.send(req);
  8967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8968. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8969. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8970. }
  8971. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8972. Request req;
  8973. req.method = "MKCOL";
  8974. req.path = "/dav-mkcol";
  8975. auto res = cli_.send(req);
  8976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8977. EXPECT_EQ(StatusCode::Created_201, res->status);
  8978. }
  8979. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8980. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8981. Request req;
  8982. req.method = "REPORT";
  8983. req.path = "/dav-report";
  8984. req.body = xml;
  8985. auto res = cli_.send(req);
  8986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8987. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8988. EXPECT_EQ(xml, res->body);
  8989. }
  8990. // A content reader route must fire even when the request carries no body,
  8991. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8992. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8993. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8994. Request req;
  8995. req.method = "REPORT";
  8996. req.path = "/dav-report";
  8997. auto res = cli_.send(req);
  8998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8999. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9000. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  9001. }
  9002. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  9003. Request req;
  9004. req.method = "PROPFIND";
  9005. req.path = "/not-dav";
  9006. auto res = cli_.send(req);
  9007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9008. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9009. }
  9010. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  9011. Request req;
  9012. req.method = "UNLOCK";
  9013. req.path = "/dav/dir";
  9014. cli_.set_keep_alive(true);
  9015. auto res = cli_.send(req);
  9016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9017. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9018. EXPECT_EQ("close", res->get_header_value("Connection"));
  9019. EXPECT_FALSE(cli_.is_socket_open());
  9020. }
  9021. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  9022. // The mount point serves this path, but only for GET and HEAD.
  9023. auto get_res = cli_.Get("/dir/index.html");
  9024. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  9025. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  9026. Request req;
  9027. req.method = "PROPFIND";
  9028. req.path = "/dir/index.html";
  9029. auto res = cli_.send(req);
  9030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9031. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9032. }
  9033. TEST_F(ServerTest, CustomRouteKeepAlive) {
  9034. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9035. cli_.set_keep_alive(true);
  9036. for (auto i = 0; i < 2; i++) {
  9037. Request req;
  9038. req.method = "PROPFIND";
  9039. req.path = "/dav/dir";
  9040. req.body = xml;
  9041. auto res = cli_.send(req);
  9042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9043. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9044. EXPECT_EQ(xml, res->body);
  9045. EXPECT_TRUE(cli_.is_socket_open());
  9046. }
  9047. // A built-in method must still be served on the same connection.
  9048. cli_.set_keep_alive(false);
  9049. auto res = cli_.Get("/hi");
  9050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9051. EXPECT_EQ(StatusCode::OK_200, res->status);
  9052. EXPECT_EQ("close", res->get_header_value("Connection"));
  9053. }
  9054. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  9055. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9056. Request req;
  9057. req.method = "PROPFIND";
  9058. req.path = "/dav/dir";
  9059. req.set_header("Expect", "100-continue");
  9060. req.body = xml;
  9061. auto res = cli_.send(req);
  9062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9063. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9064. EXPECT_EQ(xml, res->body);
  9065. }
  9066. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9067. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9068. TEST_F(ServerTest, Gzip) {
  9069. Headers headers;
  9070. headers.emplace("Accept-Encoding", "gzip, deflate");
  9071. auto res = cli_.Get("/compress", headers);
  9072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9073. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9074. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9075. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9076. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9077. "7890123456789012345678901234567890",
  9078. res->body);
  9079. EXPECT_EQ(StatusCode::OK_200, res->status);
  9080. }
  9081. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9082. Headers headers;
  9083. headers.emplace("Accept-Encoding", "gzip, deflate");
  9084. auto res = cli_.Get("/compress-with-charset", headers);
  9085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9086. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9087. EXPECT_EQ("application/json; charset=utf-8",
  9088. res->get_header_value("Content-Type"));
  9089. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9090. "7890123456789012345678901234567890",
  9091. res->body);
  9092. EXPECT_EQ(StatusCode::OK_200, res->status);
  9093. }
  9094. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9095. Headers headers;
  9096. headers.emplace("Accept-Encoding", "");
  9097. auto res = cli_.Get("/compress", headers);
  9098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9099. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9100. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9101. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9102. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9103. "7890123456789012345678901234567890",
  9104. res->body);
  9105. EXPECT_EQ(StatusCode::OK_200, res->status);
  9106. }
  9107. TEST_F(ServerTest, GzipWithContentReceiver) {
  9108. Headers headers;
  9109. headers.emplace("Accept-Encoding", "gzip, deflate");
  9110. std::string body;
  9111. auto res =
  9112. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9113. EXPECT_EQ(100U, data_length);
  9114. body.append(data, data_length);
  9115. return true;
  9116. });
  9117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9118. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9119. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9120. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9121. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9122. "7890123456789012345678901234567890",
  9123. body);
  9124. EXPECT_EQ(StatusCode::OK_200, res->status);
  9125. }
  9126. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9127. Headers headers;
  9128. headers.emplace("Accept-Encoding", "gzip, deflate");
  9129. cli_.set_decompress(false);
  9130. auto res = cli_.Get("/compress", headers);
  9131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9132. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9133. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9134. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9135. EXPECT_EQ(33U, res->body.size());
  9136. EXPECT_EQ(StatusCode::OK_200, res->status);
  9137. }
  9138. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9139. Headers headers;
  9140. headers.emplace("Accept-Encoding", "");
  9141. std::string body;
  9142. auto res =
  9143. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9144. EXPECT_EQ(100U, data_length);
  9145. body.append(data, data_length);
  9146. return true;
  9147. });
  9148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9149. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9150. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9151. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9152. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9153. "7890123456789012345678901234567890",
  9154. body);
  9155. EXPECT_EQ(StatusCode::OK_200, res->status);
  9156. }
  9157. TEST_F(ServerTest, NoGzip) {
  9158. Headers headers;
  9159. headers.emplace("Accept-Encoding", "gzip, deflate");
  9160. auto res = cli_.Get("/nocompress", headers);
  9161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9162. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9163. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9164. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9165. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9166. "7890123456789012345678901234567890",
  9167. res->body);
  9168. EXPECT_EQ(StatusCode::OK_200, res->status);
  9169. }
  9170. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9171. Headers headers;
  9172. headers.emplace("Accept-Encoding", "gzip, deflate");
  9173. std::string body;
  9174. auto res = cli_.Get("/nocompress", headers,
  9175. [&](const char *data, size_t data_length) {
  9176. EXPECT_EQ(100U, data_length);
  9177. body.append(data, data_length);
  9178. return true;
  9179. });
  9180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9181. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9182. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9183. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9184. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9185. "7890123456789012345678901234567890",
  9186. body);
  9187. EXPECT_EQ(StatusCode::OK_200, res->status);
  9188. }
  9189. TEST_F(ServerTest, MultipartFormDataGzip) {
  9190. UploadFormDataItems items = {
  9191. {"key1", "test", "", ""},
  9192. {"key2", "--abcdefg123", "", ""},
  9193. };
  9194. cli_.set_compress(true);
  9195. auto res = cli_.Post("/compress-multipart", items);
  9196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9197. EXPECT_EQ(StatusCode::OK_200, res->status);
  9198. }
  9199. #endif
  9200. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9201. // Static file compression is opt-in, so these run their own server rather than
  9202. // flipping it on for the shared ServerTest fixture, which would silently
  9203. // rewrite what every other static file test is asserting.
  9204. class StaticFileCompressionTest : public ::testing::Test {
  9205. protected:
  9206. void TearDown() override {
  9207. if (t_.joinable()) {
  9208. svr_.stop();
  9209. t_.join();
  9210. }
  9211. }
  9212. int start(const std::function<void(Server &)> &configure = nullptr) {
  9213. // Serves the same tree as a directory of build-time compressed assets
  9214. // would be served: the mount point names the coding the files are already
  9215. // stored in. Registered before "/" so it is the one that matches.
  9216. svr_.set_mount_point("/pre-encoded", "./www",
  9217. {{"Content-Encoding", "gzip"}});
  9218. svr_.set_mount_point("/", "./www");
  9219. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9220. res.set_file_content("./www/dir/index.html", "text/html");
  9221. });
  9222. svr_.Get("/pre-encoded-file-content",
  9223. [](const Request & /*req*/, Response &res) {
  9224. res.set_header("Content-Encoding", "gzip");
  9225. res.set_file_content("./www/dir/index.html", "text/html");
  9226. });
  9227. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9228. res.set_content_provider(
  9229. 6, "text/plain",
  9230. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9231. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9232. return true;
  9233. });
  9234. });
  9235. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9236. res.set_content_provider(
  9237. 1000, "text/plain",
  9238. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9239. if (offset < 100) {
  9240. std::string data(100, 'A');
  9241. sink.write(data.data(), data.size());
  9242. return true;
  9243. }
  9244. std::this_thread::sleep_for(std::chrono::seconds(2));
  9245. std::string data(900, 'B');
  9246. sink.write(data.data(), data.size());
  9247. return true;
  9248. });
  9249. });
  9250. if (configure) { configure(svr_); }
  9251. auto port = svr_.bind_to_any_port(HOST);
  9252. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9253. svr_.wait_until_ready();
  9254. return port;
  9255. }
  9256. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9257. // Every file under ./www except 1MB.txt is smaller than the default
  9258. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9259. // it out of the way.
  9260. static void enable_without_floor(Server &svr) {
  9261. svr.set_static_file_compression(true);
  9262. svr.set_static_file_compression_min_length(0);
  9263. }
  9264. Server svr_;
  9265. std::thread t_;
  9266. };
  9267. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9268. auto port = start();
  9269. Client cli(HOST, port);
  9270. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9272. EXPECT_EQ(StatusCode::OK_200, res->status);
  9273. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9274. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9275. EXPECT_EQ(1048576U, res->body.size());
  9276. }
  9277. TEST_F(StaticFileCompressionTest, MountPoint) {
  9278. auto port = start(enable);
  9279. Client cli(HOST, port);
  9280. cli.set_decompress(false);
  9281. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9283. EXPECT_EQ(StatusCode::OK_200, res->status);
  9284. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9285. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9286. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9287. // The response stays self-delimiting: a length, not a chunked body.
  9288. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9289. EXPECT_EQ(std::to_string(res->body.size()),
  9290. res->get_header_value("Content-Length"));
  9291. EXPECT_LT(res->body.size(), 1048576U);
  9292. EXPECT_FALSE(res->body.empty());
  9293. }
  9294. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9295. auto port = start(enable);
  9296. Client cli(HOST, port);
  9297. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9299. EXPECT_EQ(StatusCode::OK_200, res->status);
  9300. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9301. EXPECT_EQ(1048576U, res->body.size());
  9302. }
  9303. TEST_F(StaticFileCompressionTest, FileContent) {
  9304. auto port = start(enable_without_floor);
  9305. Client cli(HOST, port);
  9306. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9308. EXPECT_EQ(StatusCode::OK_200, res->status);
  9309. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9310. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9311. EXPECT_EQ(104U, res->body.size());
  9312. }
  9313. // A handler that serves an already-encoded file names the coding itself. The
  9314. // file-backed path decided its coding from Accept-Encoding and the content
  9315. // type alone, so it compressed the stored bytes a second time and appended a
  9316. // second Content-Encoding field line.
  9317. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9318. auto port = start(enable_without_floor);
  9319. Client cli(HOST, port);
  9320. cli.set_decompress(false);
  9321. auto res = cli.Get("/pre-encoded-file-content",
  9322. Headers{{"Accept-Encoding", "gzip"}});
  9323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9324. EXPECT_EQ(StatusCode::OK_200, res->status);
  9325. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9326. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9327. // Vary belongs to a coding the server chose, and it chose none here.
  9328. EXPECT_FALSE(res->has_header("Vary"));
  9329. // The file travels exactly as it is stored on disk.
  9330. EXPECT_EQ(104U, res->body.size());
  9331. }
  9332. // The 1MB file clears the default floor, so this one runs the configuration a
  9333. // deployment would actually have.
  9334. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9335. auto port = start(enable);
  9336. Client cli(HOST, port);
  9337. cli.set_decompress(false);
  9338. auto res =
  9339. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9341. EXPECT_EQ(StatusCode::OK_200, res->status);
  9342. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9343. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9344. EXPECT_FALSE(res->has_header("Vary"));
  9345. EXPECT_EQ(1048576U, res->body.size());
  9346. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9347. }
  9348. TEST_F(StaticFileCompressionTest, Head) {
  9349. auto port = start(enable);
  9350. Client cli(HOST, port);
  9351. cli.set_decompress(false);
  9352. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9353. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9354. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9356. EXPECT_EQ(StatusCode::OK_200, res->status);
  9357. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9358. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9359. // HEAD still reports the size a GET would return.
  9360. EXPECT_EQ(get->get_header_value("Content-Length"),
  9361. res->get_header_value("Content-Length"));
  9362. EXPECT_TRUE(res->body.empty());
  9363. }
  9364. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9365. auto port = start(enable);
  9366. Client cli(HOST, port);
  9367. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9368. {"Accept-Encoding", "gzip"}});
  9369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9370. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9371. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9372. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9373. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9374. EXPECT_EQ("cd", res->body);
  9375. }
  9376. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9377. auto port = start(enable);
  9378. Client cli(HOST, port);
  9379. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9381. EXPECT_EQ(StatusCode::OK_200, res->status);
  9382. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9383. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9384. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9385. }
  9386. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9387. auto port = start(enable);
  9388. Client cli(HOST, port);
  9389. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9391. EXPECT_EQ(StatusCode::OK_200, res->status);
  9392. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9393. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9394. EXPECT_TRUE(res->body.empty());
  9395. }
  9396. TEST_F(StaticFileCompressionTest, MinLength) {
  9397. auto port = start(enable);
  9398. Client cli(HOST, port);
  9399. // 104 bytes, well under the default floor. Compressing it would add the
  9400. // gzip header and trailer to a body that already fits in one packet.
  9401. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9403. EXPECT_EQ(StatusCode::OK_200, res->status);
  9404. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9405. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9406. }
  9407. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9408. auto port = start([](Server &svr) {
  9409. svr.set_static_file_compression(true);
  9410. svr.set_static_file_compression_min_length(1);
  9411. });
  9412. Client cli(HOST, port);
  9413. cli.set_decompress(false);
  9414. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9416. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9417. // A 9-byte file comes back larger than it went in, because gzip's header and
  9418. // trailer outweigh anything deflate can save. That is the end of the range
  9419. // the floor exists to keep out.
  9420. EXPECT_GT(res->body.size(), 9U);
  9421. }
  9422. TEST_F(StaticFileCompressionTest, MaxLength) {
  9423. auto port = start([](Server &svr) {
  9424. svr.set_static_file_compression(true);
  9425. svr.set_static_file_compression_min_length(0);
  9426. svr.set_static_file_compression_max_length(1024);
  9427. });
  9428. Client cli(HOST, port);
  9429. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9430. // defines `small` as a macro on Windows.
  9431. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9432. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9433. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9434. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9435. // Under it: compressed.
  9436. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9437. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9438. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9439. }
  9440. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9441. auto port = start(enable_without_floor);
  9442. Client cli(HOST, port);
  9443. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9444. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9445. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9446. auto identity_etag = identity->get_header_value("ETag");
  9447. ASSERT_FALSE(identity_etag.empty());
  9448. auto gzipped =
  9449. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9450. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9451. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9452. auto gzip_etag = gzipped->get_header_value("ETag");
  9453. ASSERT_FALSE(gzip_etag.empty());
  9454. // Two representations, two validators.
  9455. EXPECT_NE(identity_etag, gzip_etag);
  9456. // Each one revalidates against the request that would produce it...
  9457. auto fresh =
  9458. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9459. {"If-None-Match", gzip_etag}});
  9460. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9461. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9462. auto fresh_identity =
  9463. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9464. {"If-None-Match", identity_etag}});
  9465. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9466. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9467. // ...and not against the other representation.
  9468. auto crossed =
  9469. cli.Get("/dir/index.html",
  9470. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9471. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9472. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9473. }
  9474. // The opt-in covers responses the server reads off disk itself. A caller's own
  9475. // known-length provider keeps its Content-Length and, more importantly, keeps
  9476. // delivering incrementally: routing it through a compressor would hold every
  9477. // write back until zlib's window filled.
  9478. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9479. auto port = start(enable);
  9480. Client cli(HOST, port);
  9481. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9483. EXPECT_EQ(StatusCode::OK_200, res->status);
  9484. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9485. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9486. EXPECT_EQ("aaabbb", res->body);
  9487. }
  9488. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9489. auto port = start(enable);
  9490. Client cli(HOST, port);
  9491. cli.set_read_timeout(1, 0);
  9492. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9493. Headers{{"Accept-Encoding", "gzip"}});
  9494. ASSERT_TRUE(handle.is_valid());
  9495. // The provider writes 100 bytes and then stalls for longer than the read
  9496. // timeout. Those first bytes have to arrive anyway: run the response through
  9497. // a compressor and zlib holds them until its window fills, so the read would
  9498. // come back empty instead.
  9499. char buf[256];
  9500. auto n = handle.read(buf, sizeof(buf));
  9501. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9502. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9503. }
  9504. #endif
  9505. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9506. TEST_F(ServerTest, Brotli) {
  9507. Headers headers;
  9508. headers.emplace("Accept-Encoding", "br");
  9509. auto res = cli_.Get("/compress", headers);
  9510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9511. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9512. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9513. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9514. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9515. "7890123456789012345678901234567890",
  9516. res->body);
  9517. EXPECT_EQ(StatusCode::OK_200, res->status);
  9518. }
  9519. #endif
  9520. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9521. TEST_F(ServerTest, Zstd) {
  9522. Headers headers;
  9523. headers.emplace("Accept-Encoding", "zstd");
  9524. auto res = cli_.Get("/compress", headers);
  9525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9526. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9527. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9528. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9529. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9530. "7890123456789012345678901234567890",
  9531. res->body);
  9532. EXPECT_EQ(StatusCode::OK_200, res->status);
  9533. }
  9534. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9535. Headers headers;
  9536. headers.emplace("Accept-Encoding", "");
  9537. auto res = cli_.Get("/compress", headers);
  9538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9539. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9540. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9541. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9542. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9543. "7890123456789012345678901234567890",
  9544. res->body);
  9545. EXPECT_EQ(StatusCode::OK_200, res->status);
  9546. }
  9547. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9548. Headers headers;
  9549. headers.emplace("Accept-Encoding", "zstd");
  9550. std::string body;
  9551. auto res =
  9552. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9553. EXPECT_EQ(100U, data_length);
  9554. body.append(data, data_length);
  9555. return true;
  9556. });
  9557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9558. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9559. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9560. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9561. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9562. "7890123456789012345678901234567890",
  9563. body);
  9564. EXPECT_EQ(StatusCode::OK_200, res->status);
  9565. }
  9566. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9567. Headers headers;
  9568. headers.emplace("Accept-Encoding", "zstd");
  9569. cli_.set_decompress(false);
  9570. auto res = cli_.Get("/compress", headers);
  9571. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9572. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9573. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9574. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9576. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9577. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9578. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9579. EXPECT_EQ(StatusCode::OK_200, res->status);
  9580. ASSERT_EQ(26U, res->body.size());
  9581. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9582. 0);
  9583. }
  9584. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9585. Headers headers;
  9586. headers.emplace("Accept-Encoding", "");
  9587. std::string body;
  9588. auto res =
  9589. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9590. EXPECT_EQ(100U, data_length);
  9591. body.append(data, data_length);
  9592. return true;
  9593. });
  9594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9595. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9596. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9597. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9598. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9599. "7890123456789012345678901234567890",
  9600. body);
  9601. EXPECT_EQ(StatusCode::OK_200, res->status);
  9602. }
  9603. TEST_F(ServerTest, NoZstd) {
  9604. Headers headers;
  9605. headers.emplace("Accept-Encoding", "zstd");
  9606. auto res = cli_.Get("/nocompress", headers);
  9607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9608. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9609. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9610. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9611. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9612. "7890123456789012345678901234567890",
  9613. res->body);
  9614. EXPECT_EQ(StatusCode::OK_200, res->status);
  9615. }
  9616. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9617. Headers headers;
  9618. headers.emplace("Accept-Encoding", "zstd");
  9619. std::string body;
  9620. auto res = cli_.Get("/nocompress", headers,
  9621. [&](const char *data, size_t data_length) {
  9622. EXPECT_EQ(100U, data_length);
  9623. body.append(data, data_length);
  9624. return true;
  9625. });
  9626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9627. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9628. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9629. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9630. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9631. "7890123456789012345678901234567890",
  9632. body);
  9633. EXPECT_EQ(StatusCode::OK_200, res->status);
  9634. }
  9635. // TODO: How to enable zstd ??
  9636. TEST_F(ServerTest, MultipartFormDataZstd) {
  9637. UploadFormDataItems items = {
  9638. {"key1", "test", "", ""},
  9639. {"key2", "--abcdefg123", "", ""},
  9640. };
  9641. Headers headers;
  9642. headers.emplace("Accept-Encoding", "zstd");
  9643. cli_.set_compress(true);
  9644. auto res = cli_.Post("/compress-multipart", headers, items);
  9645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9646. EXPECT_EQ(StatusCode::OK_200, res->status);
  9647. }
  9648. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9649. Headers headers;
  9650. headers.emplace("Accept-Encoding", "zstd");
  9651. cli_.set_compress(true);
  9652. auto res = cli_.Put(
  9653. "/put", headers, 3,
  9654. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9655. sink.os << "PUT";
  9656. return true;
  9657. },
  9658. "text/plain");
  9659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9660. EXPECT_EQ(StatusCode::OK_200, res->status);
  9661. EXPECT_EQ("PUT", res->body);
  9662. }
  9663. // Pre-compression logging tests
  9664. TEST_F(ServerTest, PreCompressionLogging) {
  9665. // Test data for compression (matches the actual /compress endpoint content)
  9666. const std::string test_content =
  9667. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9668. "3456789012345678901234567890";
  9669. // Variables to capture logging data
  9670. std::string pre_compression_body;
  9671. std::string pre_compression_content_type;
  9672. std::string pre_compression_content_encoding;
  9673. std::string post_compression_body;
  9674. std::string post_compression_content_type;
  9675. std::string post_compression_content_encoding;
  9676. // Set up pre-compression logger
  9677. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9678. const Response &res) {
  9679. pre_compression_body = res.body;
  9680. pre_compression_content_type = res.get_header_value("Content-Type");
  9681. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9682. });
  9683. // Set up post-compression logger
  9684. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9685. post_compression_body = res.body;
  9686. post_compression_content_type = res.get_header_value("Content-Type");
  9687. post_compression_content_encoding =
  9688. res.get_header_value("Content-Encoding");
  9689. });
  9690. // Test with gzip compression
  9691. Headers headers;
  9692. headers.emplace("Accept-Encoding", "gzip");
  9693. auto res = cli_.Get("/compress", headers);
  9694. // Verify response was compressed
  9695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9696. EXPECT_EQ(StatusCode::OK_200, res->status);
  9697. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9698. // Verify pre-compression logger captured uncompressed content
  9699. EXPECT_EQ(test_content, pre_compression_body);
  9700. EXPECT_EQ("text/plain", pre_compression_content_type);
  9701. EXPECT_TRUE(pre_compression_content_encoding
  9702. .empty()); // No encoding header before compression
  9703. // Verify post-compression logger captured compressed content
  9704. EXPECT_NE(test_content,
  9705. post_compression_body); // Should be different after compression
  9706. EXPECT_EQ("text/plain", post_compression_content_type);
  9707. EXPECT_EQ("gzip", post_compression_content_encoding);
  9708. // Verify compressed content is smaller
  9709. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9710. }
  9711. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9712. const std::string test_content =
  9713. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9714. "3456789012345678901234567890";
  9715. std::string pre_compression_body;
  9716. std::string post_compression_body;
  9717. svr_.set_pre_compression_logger(
  9718. [&](const Request & /*req*/, const Response &res) {
  9719. pre_compression_body = res.body;
  9720. });
  9721. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9722. post_compression_body = res.body;
  9723. });
  9724. Headers headers;
  9725. headers.emplace("Accept-Encoding", "br");
  9726. auto res = cli_.Get("/compress", headers);
  9727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9728. EXPECT_EQ(StatusCode::OK_200, res->status);
  9729. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9730. // Verify pre-compression content is uncompressed
  9731. EXPECT_EQ(test_content, pre_compression_body);
  9732. // Verify post-compression content is compressed
  9733. EXPECT_NE(test_content, post_compression_body);
  9734. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9735. }
  9736. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9737. const std::string test_content =
  9738. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9739. "3456789012345678901234567890";
  9740. std::string pre_compression_body;
  9741. std::string post_compression_body;
  9742. svr_.set_pre_compression_logger(
  9743. [&](const Request & /*req*/, const Response &res) {
  9744. pre_compression_body = res.body;
  9745. });
  9746. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9747. post_compression_body = res.body;
  9748. });
  9749. // Request without compression (use /nocompress endpoint)
  9750. Headers headers;
  9751. auto res = cli_.Get("/nocompress", headers);
  9752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9753. EXPECT_EQ(StatusCode::OK_200, res->status);
  9754. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9755. // Pre-compression logger should not be called when no compression is applied
  9756. EXPECT_TRUE(
  9757. pre_compression_body.empty()); // Pre-compression logger not called
  9758. EXPECT_EQ(
  9759. test_content,
  9760. post_compression_body); // Post-compression logger captures final content
  9761. }
  9762. TEST_F(ServerTest, LoggerSeesContentLength) {
  9763. size_t logged_content_length = 0;
  9764. std::string logged_content_length_header;
  9765. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9766. logged_content_length = res.content_length_;
  9767. logged_content_length_header = res.get_header_value("Content-Length");
  9768. });
  9769. auto res = cli_.Get("/nocompress");
  9770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9771. EXPECT_EQ(StatusCode::OK_200, res->status);
  9772. EXPECT_EQ(res->body.size(), logged_content_length);
  9773. EXPECT_EQ(std::to_string(logged_content_length),
  9774. logged_content_length_header);
  9775. }
  9776. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9777. const std::string test_content =
  9778. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9779. "3456789012345678901234567890";
  9780. std::string pre_compression_body;
  9781. bool pre_logger_called = false;
  9782. // Set only pre-compression logger
  9783. svr_.set_pre_compression_logger(
  9784. [&](const Request & /*req*/, const Response &res) {
  9785. pre_compression_body = res.body;
  9786. pre_logger_called = true;
  9787. });
  9788. Headers headers;
  9789. headers.emplace("Accept-Encoding", "gzip");
  9790. auto res = cli_.Get("/compress", headers);
  9791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9792. EXPECT_EQ(StatusCode::OK_200, res->status);
  9793. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9794. // Verify pre-compression logger was called
  9795. EXPECT_TRUE(pre_logger_called);
  9796. EXPECT_EQ(test_content, pre_compression_body);
  9797. }
  9798. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9799. {
  9800. // Test with Expect: 100-continue header - success case
  9801. // Server returns 100 Continue, client sends body, server returns 200 OK
  9802. Request req;
  9803. req.method = "POST";
  9804. req.path = "/post-large";
  9805. req.set_header("Expect", "100-continue");
  9806. req.body = LARGE_DATA;
  9807. Response res;
  9808. auto error = Error::Success;
  9809. cli_.set_keep_alive(true);
  9810. auto ret = cli_.send(req, res, error);
  9811. EXPECT_TRUE(ret);
  9812. EXPECT_EQ(StatusCode::OK_200, res.status);
  9813. EXPECT_EQ(LARGE_DATA, res.body);
  9814. }
  9815. {
  9816. // Test with Expect: 100-continue header - error case
  9817. // Client should not send the body when server returns an error
  9818. Request req;
  9819. req.method = "POST";
  9820. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9821. req.set_header("Expect", "100-continue");
  9822. req.body = LARGE_DATA;
  9823. Response res;
  9824. auto error = Error::Success;
  9825. auto start = std::chrono::high_resolution_clock::now();
  9826. cli_.set_keep_alive(true);
  9827. auto ret = cli_.send(req, res, error);
  9828. auto end = std::chrono::high_resolution_clock::now();
  9829. auto elapsed =
  9830. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9831. .count();
  9832. // With Expect: 100-continue, request completes successfully but with error
  9833. EXPECT_TRUE(ret);
  9834. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9835. EXPECT_EQ("close", res.get_header_value("Connection"));
  9836. EXPECT_FALSE(cli_.is_socket_open());
  9837. EXPECT_LE(elapsed, 2000);
  9838. }
  9839. {
  9840. // Send an extra GET request to ensure error recovery without hanging
  9841. Request req;
  9842. req.method = "GET";
  9843. req.path = "/hi";
  9844. auto start = std::chrono::high_resolution_clock::now();
  9845. auto res = cli_.send(req);
  9846. auto end = std::chrono::high_resolution_clock::now();
  9847. auto elapsed =
  9848. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9849. .count();
  9850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9851. EXPECT_EQ(StatusCode::OK_200, res->status);
  9852. EXPECT_EQ("Hello World!", res->body);
  9853. EXPECT_LE(elapsed, 500);
  9854. }
  9855. }
  9856. TEST(ZstdDecompressor, ChunkedDecompression) {
  9857. std::string data;
  9858. for (size_t i = 0; i < 32 * 1024; ++i) {
  9859. data.push_back(static_cast<char>('a' + i % 26));
  9860. }
  9861. std::string compressed_data;
  9862. {
  9863. httplib::detail::zstd_compressor compressor;
  9864. bool result = compressor.compress(
  9865. data.data(), data.size(),
  9866. /*last=*/true,
  9867. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9868. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9869. compressed_data_size);
  9870. return true;
  9871. });
  9872. ASSERT_TRUE(result);
  9873. }
  9874. std::string decompressed_data;
  9875. {
  9876. httplib::detail::zstd_decompressor decompressor;
  9877. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9878. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9879. size_t chunk_size = 130;
  9880. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9881. chunk_begin += chunk_size) {
  9882. size_t current_chunk_size =
  9883. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9884. bool result = decompressor.decompress(
  9885. compressed_data.data() + chunk_begin, current_chunk_size,
  9886. [&](const char *decompressed_data_chunk,
  9887. size_t decompressed_data_chunk_size) {
  9888. decompressed_data.insert(decompressed_data.size(),
  9889. decompressed_data_chunk,
  9890. decompressed_data_chunk_size);
  9891. return true;
  9892. });
  9893. ASSERT_TRUE(result);
  9894. }
  9895. }
  9896. ASSERT_EQ(data, decompressed_data);
  9897. }
  9898. TEST(ZstdDecompressor, Decompress) {
  9899. std::string original_text = "Compressed with ZSTD";
  9900. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9901. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9902. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9903. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9904. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9905. std::string decompressed_data;
  9906. {
  9907. httplib::detail::zstd_decompressor decompressor;
  9908. bool result = decompressor.decompress(
  9909. compressed_data.data(), compressed_data.size(),
  9910. [&](const char *decompressed_data_chunk,
  9911. size_t decompressed_data_chunk_size) {
  9912. decompressed_data.insert(decompressed_data.size(),
  9913. decompressed_data_chunk,
  9914. decompressed_data_chunk_size);
  9915. return true;
  9916. });
  9917. ASSERT_TRUE(result);
  9918. }
  9919. ASSERT_EQ(original_text, decompressed_data);
  9920. }
  9921. #endif
  9922. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9923. // separate chunks so that the server sees each part in its own read(). Used to
  9924. // place a read boundary at a specific offset of a request body.
  9925. static bool send_request_in_parts(time_t read_timeout_sec,
  9926. const std::vector<std::string> &parts,
  9927. std::string *resp = nullptr,
  9928. int port = PORT) {
  9929. auto error = Error::Success;
  9930. auto client_sock = detail::create_client_socket(
  9931. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9932. /*connection_timeout_sec=*/5, 0,
  9933. /*read_timeout_sec=*/5, 0,
  9934. /*write_timeout_sec=*/5, 0, std::string(), error);
  9935. if (client_sock == INVALID_SOCKET) { return false; }
  9936. auto ret = detail::process_client_socket(
  9937. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9938. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9939. for (size_t i = 0; i < parts.size(); i++) {
  9940. const auto &part = parts[i];
  9941. if (part.size() !=
  9942. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9943. return false;
  9944. }
  9945. if (i + 1 < parts.size()) {
  9946. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9947. }
  9948. }
  9949. char buf[512];
  9950. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9951. while (line_reader.getline()) {
  9952. if (resp) { *resp += line_reader.ptr(); }
  9953. }
  9954. return true;
  9955. });
  9956. detail::close_socket(client_sock);
  9957. return ret;
  9958. }
  9959. // Sends a raw request to a server listening at HOST:PORT.
  9960. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9961. std::string *resp = nullptr, int port = PORT) {
  9962. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9963. }
  9964. #ifdef CPPHTTPLIB_SSL_ENABLED
  9965. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9966. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9967. ASSERT_TRUE(svr.is_valid());
  9968. svr.set_read_timeout(1, 0);
  9969. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9970. auto se = detail::scope_exit([&] {
  9971. svr.stop();
  9972. t.join();
  9973. ASSERT_FALSE(svr.is_running());
  9974. });
  9975. svr.wait_until_ready();
  9976. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9977. // keeps each wait well within the read timeout. The server gives up a
  9978. // second in, so the bytes sent after that fail.
  9979. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9980. parts.resize(26, std::string(1, '\0'));
  9981. EXPECT_FALSE(send_request_in_parts(5, parts));
  9982. }
  9983. #endif
  9984. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9985. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9986. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9987. const std::vector<std::string> &parts,
  9988. std::string *resp = nullptr,
  9989. int port = PORT) {
  9990. auto error = Error::Success;
  9991. auto sock = detail::create_client_socket(
  9992. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9993. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9994. /*write_timeout_sec=*/5, 0, std::string(), error);
  9995. if (sock == INVALID_SOCKET) { return false; }
  9996. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9997. auto ctx = SSL_CTX_new(TLS_client_method());
  9998. auto ssl = SSL_new(ctx);
  9999. auto ssl_se = detail::scope_exit([&] {
  10000. SSL_free(ssl);
  10001. SSL_CTX_free(ctx);
  10002. });
  10003. SSL_set_fd(ssl, static_cast<int>(sock));
  10004. if (SSL_connect(ssl) != 1) { return false; }
  10005. for (size_t i = 0; i < parts.size(); i++) {
  10006. const auto &part = parts[i];
  10007. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  10008. static_cast<int>(part.size())) {
  10009. return false;
  10010. }
  10011. if (i + 1 < parts.size()) {
  10012. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10013. }
  10014. }
  10015. char buf[512];
  10016. int n;
  10017. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10018. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  10019. }
  10020. return true;
  10021. }
  10022. #endif
  10023. // The request line, then a header value a byte at a time.
  10024. static std::vector<std::string> slow_request_head_parts() {
  10025. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  10026. parts.resize(26, "a");
  10027. parts.emplace_back("\r\n\r\n");
  10028. return parts;
  10029. }
  10030. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  10031. // within the one-second read timeout. The server gives up a second in, before
  10032. // the head is complete.
  10033. static void
  10034. expect_slow_request_head_dropped(Server &svr,
  10035. const std::function<std::string()> &send) {
  10036. std::atomic<bool> handled(false);
  10037. svr.Get("/", [&](const Request &, Response &res) {
  10038. handled = true;
  10039. res.set_content("ok", "text/plain");
  10040. });
  10041. svr.set_read_timeout(1, 0);
  10042. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10043. auto se = detail::scope_exit([&] {
  10044. svr.stop();
  10045. t.join();
  10046. ASSERT_FALSE(svr.is_running());
  10047. });
  10048. svr.wait_until_ready();
  10049. auto resp = send();
  10050. EXPECT_FALSE(handled);
  10051. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  10052. }
  10053. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10054. Server svr;
  10055. expect_slow_request_head_dropped(svr, [] {
  10056. std::string resp;
  10057. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10058. return resp;
  10059. });
  10060. }
  10061. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10062. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10063. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10064. ASSERT_TRUE(svr.is_valid());
  10065. expect_slow_request_head_dropped(svr, [] {
  10066. std::string resp;
  10067. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10068. return resp;
  10069. });
  10070. }
  10071. #endif
  10072. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10073. Server svr;
  10074. std::string header_value;
  10075. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10076. header_value = req.get_header_value("foo");
  10077. res.set_content("ok", "text/plain");
  10078. });
  10079. thread t = thread([&] { svr.listen(HOST, PORT); });
  10080. auto se = detail::scope_exit([&] {
  10081. svr.stop();
  10082. t.join();
  10083. ASSERT_FALSE(svr.is_running());
  10084. });
  10085. svr.wait_until_ready();
  10086. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10087. // like characters are not treated the same - use vertical tab and escape.
  10088. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10089. "foo: \t \v bar \x1B\t \r\n"
  10090. "Connection: close\r\n"
  10091. "\r\n";
  10092. std::string res;
  10093. ASSERT_TRUE(send_request(5, req, &res));
  10094. EXPECT_EQ(header_value, "");
  10095. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10096. }
  10097. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10098. Server svr;
  10099. std::string received;
  10100. svr.Get("/order", [&](const Request &req, Response &res) {
  10101. received = entries_to_string(req.headers);
  10102. res.set_content("ok", "text/plain");
  10103. });
  10104. auto port = svr.bind_to_any_port(HOST);
  10105. thread t = thread([&] { svr.listen_after_bind(); });
  10106. auto se = detail::scope_exit([&] {
  10107. svr.stop();
  10108. t.join();
  10109. ASSERT_FALSE(svr.is_running());
  10110. });
  10111. svr.wait_until_ready();
  10112. const std::string req = "GET /order HTTP/1.1\r\n"
  10113. "Host: localhost\r\n"
  10114. "X-First: 1\r\n"
  10115. "X-Dup: a\r\n"
  10116. "X-Second: 2\r\n"
  10117. "X-Dup: b\r\n"
  10118. "Connection: close\r\n"
  10119. "\r\n";
  10120. std::string res;
  10121. ASSERT_TRUE(send_request(5, req, &res, port));
  10122. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10123. EXPECT_EQ(
  10124. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10125. received);
  10126. }
  10127. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10128. Server svr;
  10129. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10130. res.set_header("Set-Cookie", "first=1");
  10131. res.set_header("X-Between", "y");
  10132. res.set_header("Set-Cookie", "second=2");
  10133. res.set_content("ok", "text/plain");
  10134. });
  10135. auto port = svr.bind_to_any_port(HOST);
  10136. thread t = thread([&] { svr.listen_after_bind(); });
  10137. auto se = detail::scope_exit([&] {
  10138. svr.stop();
  10139. t.join();
  10140. ASSERT_FALSE(svr.is_running());
  10141. });
  10142. svr.wait_until_ready();
  10143. Client cli(HOST, port);
  10144. auto res = cli.Get("/cookies");
  10145. ASSERT_TRUE(res);
  10146. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10147. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10148. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10149. }
  10150. // A stream may send a byte at a time with a small extension on each chunk,
  10151. // however long it runs
  10152. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10153. Server svr;
  10154. svr.Post("/count", [](const Request &req, Response &res) {
  10155. res.set_content(std::to_string(req.body.size()), "text/plain");
  10156. });
  10157. auto port = svr.bind_to_any_port(HOST);
  10158. ASSERT_LT(0, port);
  10159. thread t = thread([&] { svr.listen_after_bind(); });
  10160. auto se = detail::scope_exit([&] {
  10161. svr.stop();
  10162. t.join();
  10163. ASSERT_FALSE(svr.is_running());
  10164. });
  10165. svr.wait_until_ready();
  10166. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10167. "\r\nTransfer-Encoding: chunked\r\n"
  10168. "Connection: close\r\n\r\n";
  10169. for (auto i = 0; i < 4096; i++) {
  10170. req += "1;a=b\r\nx\r\n";
  10171. }
  10172. req += "0\r\n\r\n";
  10173. std::string res;
  10174. ASSERT_TRUE(send_request(5, req, &res, port));
  10175. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10176. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10177. }
  10178. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10179. Server svr;
  10180. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10181. auto i = new int(0);
  10182. res.set_header("Trailer", "X-Safe, X-Reflected");
  10183. res.set_chunked_content_provider(
  10184. "text/plain",
  10185. [i](size_t /*offset*/, DataSink &sink) {
  10186. if (*i == 0) {
  10187. sink.os << "body";
  10188. } else {
  10189. Headers trailer;
  10190. // A valid trailer that must survive.
  10191. trailer.emplace("X-Safe", "safe");
  10192. // Attacker-controlled value carrying CR/LF (response splitting).
  10193. trailer.emplace("X-Reflected",
  10194. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10195. // Attacker-controlled name carrying CR/LF.
  10196. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10197. sink.done_with_trailer(trailer);
  10198. }
  10199. (*i)++;
  10200. return true;
  10201. },
  10202. [i](bool /*success*/) { delete i; });
  10203. });
  10204. thread t = thread([&] { svr.listen(HOST, PORT); });
  10205. auto se = detail::scope_exit([&] {
  10206. svr.stop();
  10207. t.join();
  10208. ASSERT_FALSE(svr.is_running());
  10209. });
  10210. svr.wait_until_ready();
  10211. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10212. "Host: " + HOST +
  10213. "\r\n"
  10214. "Connection: close\r\n"
  10215. "\r\n";
  10216. std::string res;
  10217. ASSERT_TRUE(send_request(5, req, &res));
  10218. // The injected fields must not appear anywhere in the raw response.
  10219. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10220. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10221. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10222. // Invalid trailers are dropped entirely, matching set_header().
  10223. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10224. // The valid trailer still passes through.
  10225. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10226. }
  10227. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10228. // A custom header writer gets only the fields the default one writes
  10229. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10230. std::string s;
  10231. for (const auto &h : hdrs) {
  10232. s += h.first + ": " + h.second + "\r\n";
  10233. }
  10234. s += "\r\n";
  10235. return strm.write(s.data(), s.size());
  10236. };
  10237. for (auto custom_writer : {false, true}) {
  10238. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10239. Server svr;
  10240. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10241. svr.set_post_routing_handler([](const Request &, Response &res) {
  10242. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10243. });
  10244. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10245. // res.headers is a public field an application can populate directly,
  10246. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10247. // A valid header that must survive.
  10248. res.headers.emplace("X-Safe", "safe");
  10249. // Attacker-controlled value carrying CR/LF (response splitting).
  10250. res.headers.emplace("X-Reflected",
  10251. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10252. // Attacker-controlled name carrying CR/LF.
  10253. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10254. res.set_content("body", "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. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10264. "Host: " + HOST +
  10265. "\r\n"
  10266. "Connection: close\r\n"
  10267. "\r\n";
  10268. std::string res;
  10269. ASSERT_TRUE(send_request(5, req, &res));
  10270. // The injected fields must not appear anywhere in the raw response.
  10271. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10272. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10273. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10274. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10275. // Invalid headers are dropped entirely, matching set_header().
  10276. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10277. // The valid header still passes through.
  10278. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10279. }
  10280. }
  10281. // Forward declaration: in split builds split.py strips `inline` and moves the
  10282. // definition into httplib.cc, so detail::write_request_line is not visible from
  10283. // the public httplib.h. Re-declaring it here lets the tests link against the
  10284. // symbol in both header-only and split builds.
  10285. namespace httplib {
  10286. namespace detail {
  10287. ssize_t write_request_line(Stream &strm, const std::string &method,
  10288. const std::string &path);
  10289. } // namespace detail
  10290. } // namespace httplib
  10291. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10292. // A well-formed target is written verbatim.
  10293. {
  10294. detail::BufferStream strm;
  10295. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10296. EXPECT_GT(n, 0);
  10297. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10298. }
  10299. // A target carrying CR/LF, SP or other control octets must be rejected
  10300. // before anything reaches the wire, otherwise it splits the request line and
  10301. // injects a header or a whole request.
  10302. const std::string evil_targets[] = {
  10303. "/a\r\nInjected: pwned",
  10304. "/a\rInjected",
  10305. "/a\nInjected",
  10306. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10307. "/a b",
  10308. "/a\tb",
  10309. "/a\x7f",
  10310. };
  10311. for (const auto &evil : evil_targets) {
  10312. detail::BufferStream strm;
  10313. auto n = detail::write_request_line(strm, "GET", evil);
  10314. EXPECT_LT(n, 0);
  10315. EXPECT_TRUE(strm.get_buffer().empty());
  10316. }
  10317. }
  10318. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10319. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10320. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10321. // target reaches write_request. The client must fail cleanly with
  10322. // Error::Write instead of putting a request-line-less, header-injecting
  10323. // request on the wire.
  10324. Server svr;
  10325. svr.Get("/a", [](const Request &, Response &res) {
  10326. res.set_content("ok", "text/plain");
  10327. });
  10328. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10329. auto se = detail::scope_exit([&] {
  10330. svr.stop();
  10331. thread.join();
  10332. ASSERT_FALSE(svr.is_running());
  10333. });
  10334. svr.wait_until_ready();
  10335. {
  10336. Client cli(HOST, PORT);
  10337. cli.set_path_encode(false);
  10338. // The request is rejected before anything is written, so the connection
  10339. // stays silent and the subsequent response read would otherwise block for
  10340. // the full default read timeout. Shorten it -- the assertion is on the
  10341. // error, not the timeout.
  10342. cli.set_read_timeout(1, 0);
  10343. auto res = cli.Get("/a\r\nInjected: pwned");
  10344. EXPECT_FALSE(res);
  10345. EXPECT_EQ(Error::Write, res.error());
  10346. }
  10347. }
  10348. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10349. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10350. // including extension methods.
  10351. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10352. for (const auto &method : good_methods) {
  10353. detail::BufferStream strm;
  10354. auto n = detail::write_request_line(strm, method, "/");
  10355. EXPECT_GT(n, 0);
  10356. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10357. }
  10358. // A method carrying CR/LF would split the request line and smuggle a whole
  10359. // request ahead of the real one. A space or an empty method corrupts the
  10360. // request line. All must be rejected before anything reaches the wire.
  10361. const std::string evil_methods[] = {
  10362. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10363. "GET\r\nInjected: pwned",
  10364. "GET\r",
  10365. "GET\n",
  10366. "GE T",
  10367. "",
  10368. };
  10369. for (const auto &evil : evil_methods) {
  10370. detail::BufferStream strm;
  10371. auto n = detail::write_request_line(strm, evil, "/");
  10372. EXPECT_LT(n, 0);
  10373. EXPECT_TRUE(strm.get_buffer().empty());
  10374. }
  10375. }
  10376. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10377. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10378. // through Client::send must fail with Error::Write and no request, neither
  10379. // the smuggled one nor the real one, may reach the server.
  10380. Server svr;
  10381. std::atomic<int> request_count(0);
  10382. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10383. request_count++;
  10384. res.status = StatusCode::OK_200;
  10385. return Server::HandlerResponse::Handled;
  10386. });
  10387. auto port = svr.bind_to_any_port(HOST);
  10388. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10389. auto se = detail::scope_exit([&] {
  10390. svr.stop();
  10391. thread.join();
  10392. ASSERT_FALSE(svr.is_running());
  10393. });
  10394. svr.wait_until_ready();
  10395. {
  10396. Client cli(HOST, port);
  10397. const std::string evil_methods[] = {
  10398. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10399. "GE T",
  10400. "",
  10401. };
  10402. for (const auto &evil : evil_methods) {
  10403. Request req;
  10404. req.method = evil;
  10405. req.path = "/";
  10406. auto res = cli.send(req);
  10407. EXPECT_FALSE(res);
  10408. EXPECT_EQ(Error::Write, res.error());
  10409. }
  10410. auto handle =
  10411. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10412. EXPECT_FALSE(handle.is_valid());
  10413. EXPECT_EQ(Error::Write, handle.error);
  10414. // A valid request on the same client still goes through.
  10415. auto res = cli.Get("/");
  10416. ASSERT_TRUE(res);
  10417. EXPECT_EQ(StatusCode::OK_200, res->status);
  10418. }
  10419. EXPECT_EQ(1, request_count.load());
  10420. }
  10421. // Sends a raw request and verifies that there isn't a crash or exception.
  10422. static void test_raw_request(const std::string &req,
  10423. std::string *out = nullptr) {
  10424. Server svr;
  10425. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10426. res.set_content("ok", "text/plain");
  10427. });
  10428. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10429. res.set_content("ok", "text/plain");
  10430. });
  10431. svr.Get("/header_field_value_check",
  10432. [&](const Request & /*req*/, Response &res) {
  10433. res.set_content("ok", "text/plain");
  10434. });
  10435. svr.CustomRoute("PROPFIND", "/dav",
  10436. [&](const Request & /*req*/, Response &res) {
  10437. res.status = StatusCode::MultiStatus_207;
  10438. });
  10439. // Server read timeout must be longer than the client read timeout for the
  10440. // bug to reproduce, probably to force the server to process a request
  10441. // without a trailing blank line.
  10442. const time_t client_read_timeout_sec = 1;
  10443. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10444. bool listen_thread_ok = false;
  10445. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10446. auto se = detail::scope_exit([&] {
  10447. svr.stop();
  10448. t.join();
  10449. ASSERT_FALSE(svr.is_running());
  10450. EXPECT_TRUE(listen_thread_ok);
  10451. });
  10452. svr.wait_until_ready();
  10453. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10454. }
  10455. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10456. // A certain header line causes an exception if the header property is parsed
  10457. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10458. test_raw_request(
  10459. "GET /hi HTTP/1.1\r\n"
  10460. " : "
  10461. " "
  10462. " ");
  10463. }
  10464. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10465. // A certain header line causes an exception if the header property *name* is
  10466. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10467. // greedy matcher and requires backtracking when there are a lot of ":"
  10468. // characters.
  10469. // This occurs with libc++ but not libstdc++.
  10470. test_raw_request(
  10471. "GET /hi HTTP/1.1\r\n"
  10472. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10473. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10474. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10475. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10476. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10477. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10478. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10479. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10480. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10481. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10482. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10483. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10484. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10485. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10486. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10487. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10488. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10489. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10490. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10491. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10492. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10493. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10494. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10495. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10496. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10497. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10498. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10499. "&&&%%%");
  10500. }
  10501. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10502. // Make sure this doesn't crash the server.
  10503. // In a previous version of the header line regex, the "\r" rendered the line
  10504. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10505. // a new position where the leading white space ended and the field value
  10506. // began.
  10507. // The crash occurs with libc++ but not libstdc++.
  10508. test_raw_request("GET /hi HTTP/1.1\r\n"
  10509. "a:" +
  10510. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10511. "\r\n"
  10512. "\r\n");
  10513. }
  10514. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10515. const char *rejected[] = {
  10516. // RFC 9112 §3: one SP between the parts, and nothing else
  10517. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10518. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10519. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10520. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10521. // A request-target has no fragment
  10522. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10523. // An HTTP/1.1 request needs a Host
  10524. "GET /hi HTTP/1.1\r\n\r\n",
  10525. };
  10526. for (auto request : rejected) {
  10527. std::string out;
  10528. test_raw_request(request, &out);
  10529. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10530. }
  10531. std::string out;
  10532. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10533. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10534. }
  10535. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10536. // RFC 9112 §6.1
  10537. const char *requests[] = {
  10538. "PUT /put_hi HTTP/1.1\r\n"
  10539. "Host: localhost\r\n"
  10540. "Content-Length: 0\r\n"
  10541. "Transfer-Encoding: chunked\r\n"
  10542. "\r\n"
  10543. "0\r\n\r\n",
  10544. "PUT /put_hi HTTP/1.0\r\n"
  10545. "Connection: keep-alive\r\n"
  10546. "Transfer-Encoding: chunked\r\n"
  10547. "\r\n"
  10548. "0\r\n\r\n",
  10549. };
  10550. for (auto request : requests) {
  10551. std::string out;
  10552. test_raw_request(request, &out);
  10553. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10554. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10555. }
  10556. }
  10557. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10558. std::string out;
  10559. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10560. "Content-Type: text/plain\r\n"
  10561. "Transfer-Encoding: chunked\r\n"
  10562. "\r\n"
  10563. "nothex\r\n",
  10564. &out);
  10565. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10566. }
  10567. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10568. std::string out;
  10569. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10570. "Content-Type: text/plain\r\n"
  10571. "Transfer-Encoding: chunked\r\n"
  10572. "\r\n"
  10573. "3\r\n"
  10574. "xyz\r\n"
  10575. "NaN\r\n",
  10576. &out);
  10577. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10578. }
  10579. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10580. std::string out;
  10581. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10582. "Content-Type: text/plain\r\n"
  10583. "Transfer-Encoding: chunked\r\n"
  10584. "\r\n"
  10585. // Length is too large for 64 bits.
  10586. "1ffffffffffffffff\r\n"
  10587. "xyz\r\n",
  10588. &out);
  10589. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10590. }
  10591. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10592. test_raw_request("GET /hi HTTP/1.1\r\n"
  10593. "Content-Type: text/plain\r\n\r");
  10594. }
  10595. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10596. std::string out;
  10597. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10598. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10599. }
  10600. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10601. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10602. std::string out;
  10603. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10604. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10605. }
  10606. }
  10607. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10608. std::string out;
  10609. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10610. "Host: localhost\r\n"
  10611. "Connection: close\r\n\r\n",
  10612. &out);
  10613. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10614. }
  10615. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10616. Server svr;
  10617. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10618. EXPECT_TRUE(!req.remote_addr.empty());
  10619. });
  10620. thread t = thread([&] { svr.listen(HOST, PORT); });
  10621. auto se = detail::scope_exit([&] {
  10622. svr.stop();
  10623. t.join();
  10624. ASSERT_FALSE(svr.is_running());
  10625. });
  10626. svr.wait_until_ready();
  10627. // Send an invalid request line to trigger Bad Request
  10628. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10629. std::string out;
  10630. ASSERT_TRUE(send_request(5, bad_req, &out));
  10631. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10632. }
  10633. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10634. // answered right away rather than blocking on a read that waits for EOF.
  10635. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10636. std::string out;
  10637. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10638. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10639. }
  10640. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10641. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10642. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10643. for (const auto *method : methods) {
  10644. Server svr;
  10645. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10646. EXPECT_FALSE(svr.is_valid()) << method;
  10647. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10648. }
  10649. }
  10650. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10651. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10652. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10653. for (const auto *method : methods) {
  10654. Server svr;
  10655. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10656. EXPECT_FALSE(svr.is_valid()) << method;
  10657. }
  10658. }
  10659. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10660. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10661. "COPY", "MOVE", "LOCK",
  10662. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10663. Server svr;
  10664. for (const auto *method : methods) {
  10665. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10666. }
  10667. EXPECT_TRUE(svr.is_valid());
  10668. }
  10669. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10670. Server svr;
  10671. svr.CustomRoute("POST", "/x",
  10672. [](const Request &, Response &, const ContentReader &) {});
  10673. EXPECT_FALSE(svr.is_valid());
  10674. }
  10675. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10676. Server svr;
  10677. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10678. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10679. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10680. EXPECT_FALSE(svr.is_valid());
  10681. }
  10682. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10683. Server svr;
  10684. auto captured = Error::Success;
  10685. svr.set_error_logger(
  10686. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10687. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10688. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10689. }
  10690. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10691. std::string out;
  10692. std::string request(
  10693. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10694. test_raw_request(request, &out);
  10695. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10696. }
  10697. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10698. std::string out;
  10699. std::string request(
  10700. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10701. test_raw_request(request, &out);
  10702. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10703. }
  10704. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10705. std::string out;
  10706. std::string request(
  10707. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10708. test_raw_request(request, &out);
  10709. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10710. }
  10711. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10712. std::string out;
  10713. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10714. "Host: localhost\r\n"
  10715. "Test: \r\n\r\n",
  10716. &out);
  10717. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10718. }
  10719. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10720. Server svr;
  10721. std::string x_custom;
  10722. std::string cookie;
  10723. std::string xff;
  10724. std::string x_unicode;
  10725. std::string x_iis;
  10726. svr.Get("/check", [&](const Request &req, Response &res) {
  10727. x_custom = req.get_header_value("X-Custom");
  10728. cookie = req.get_header_value("Cookie");
  10729. xff = req.get_header_value("X-Forwarded-For");
  10730. x_unicode = req.get_header_value("X-Unicode");
  10731. x_iis = req.get_header_value("X-IIS");
  10732. res.set_content("ok", "text/plain");
  10733. });
  10734. thread t = thread([&] { svr.listen(HOST, PORT); });
  10735. auto se = detail::scope_exit([&] {
  10736. svr.stop();
  10737. t.join();
  10738. ASSERT_FALSE(svr.is_running());
  10739. });
  10740. svr.wait_until_ready();
  10741. const std::string req = "GET /check HTTP/1.1\r\n"
  10742. "Host: localhost\r\n"
  10743. "X-Custom: a%0D%0AInjected: b\r\n"
  10744. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10745. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10746. "X-Unicode: %E3%81%82\r\n"
  10747. "X-IIS: %u00E9\r\n"
  10748. "Connection: close\r\n"
  10749. "\r\n";
  10750. std::string res;
  10751. ASSERT_TRUE(send_request(5, req, &res));
  10752. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10753. // Every value must be returned verbatim (wire form), with no decoding.
  10754. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10755. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10756. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10757. EXPECT_EQ("%E3%81%82", x_unicode);
  10758. EXPECT_EQ("%u00E9", x_iis);
  10759. }
  10760. // Applications that previously relied on automatic percent-decoding can
  10761. // reproduce the old behavior by explicitly calling decode_path_component()
  10762. // or, for RFC 3986 conformance, decode_uri_component().
  10763. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10764. Server svr;
  10765. std::string decoded;
  10766. svr.Get("/check", [&](const Request &req, Response &res) {
  10767. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10768. res.set_content("ok", "text/plain");
  10769. });
  10770. thread t = thread([&] { svr.listen(HOST, PORT); });
  10771. auto se = detail::scope_exit([&] {
  10772. svr.stop();
  10773. t.join();
  10774. ASSERT_FALSE(svr.is_running());
  10775. });
  10776. svr.wait_until_ready();
  10777. const std::string req = "GET /check HTTP/1.1\r\n"
  10778. "Host: localhost\r\n"
  10779. "X-Custom: hello%20world\r\n"
  10780. "Connection: close\r\n"
  10781. "\r\n";
  10782. std::string res;
  10783. ASSERT_TRUE(send_request(5, req, &res));
  10784. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10785. EXPECT_EQ("hello world", decoded);
  10786. }
  10787. // Regression test for #2033. Browsers send Referer values that include
  10788. // percent-encoded characters such as %0A inside the URL. Decoding the
  10789. // header value would either trip the post-decode CR/LF/NUL guard (the
  10790. // original bug, returning 400) or, after that guard was relaxed, silently
  10791. // store a literal LF — both unacceptable. The wire form must round-trip.
  10792. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10793. Server svr;
  10794. std::string referer;
  10795. svr.Get("/check", [&](const Request &req, Response &res) {
  10796. referer = req.get_header_value("Referer");
  10797. res.set_content("ok", "text/plain");
  10798. });
  10799. thread t = thread([&] { svr.listen(HOST, PORT); });
  10800. auto se = detail::scope_exit([&] {
  10801. svr.stop();
  10802. t.join();
  10803. ASSERT_FALSE(svr.is_running());
  10804. });
  10805. svr.wait_until_ready();
  10806. const std::string req = "GET /check HTTP/1.1\r\n"
  10807. "Host: localhost\r\n"
  10808. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10809. "Connection: close\r\n"
  10810. "\r\n";
  10811. std::string res;
  10812. ASSERT_TRUE(send_request(5, req, &res));
  10813. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10814. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10815. }
  10816. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10817. Server svr;
  10818. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10819. res.set_header("Cache-Control", "no-cache");
  10820. res.set_chunked_content_provider(
  10821. "text/event-stream", [](size_t offset, DataSink &sink) {
  10822. std::string s = "data:";
  10823. s += std::to_string(offset);
  10824. s += "\n\n";
  10825. auto ret = sink.write(s.data(), s.size());
  10826. EXPECT_TRUE(ret);
  10827. std::this_thread::sleep_for(std::chrono::seconds(1));
  10828. return true;
  10829. });
  10830. });
  10831. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10832. svr.wait_until_ready();
  10833. Client client(HOST, PORT);
  10834. const Headers headers = {{"Accept", "text/event-stream"}};
  10835. auto get_thread = std::thread([&client, &headers]() {
  10836. auto res = client.Get(
  10837. "/events", headers,
  10838. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10839. });
  10840. auto se = detail::scope_exit([&] {
  10841. svr.stop();
  10842. get_thread.join();
  10843. listen_thread.join();
  10844. ASSERT_FALSE(svr.is_running());
  10845. });
  10846. // Give GET time to get a few messages.
  10847. std::this_thread::sleep_for(std::chrono::seconds(2));
  10848. }
  10849. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10850. httplib::Server svr;
  10851. svr.Post("/hi",
  10852. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10853. res.status = StatusCode::OK_200;
  10854. });
  10855. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10856. svr.wait_until_ready();
  10857. Client cli(HOST, PORT);
  10858. auto res = cli.Post("/hi", "data", "text/plain");
  10859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10860. EXPECT_EQ(StatusCode::OK_200, res->status);
  10861. svr.stop();
  10862. thread.join();
  10863. ASSERT_FALSE(svr.is_running());
  10864. res = cli.Post("/hi", "data", "text/plain");
  10865. ASSERT_FALSE(res);
  10866. }
  10867. TEST(ServerStopTest, ListenFailure) {
  10868. Server svr;
  10869. auto t = thread([&]() {
  10870. auto ret = svr.listen("????", PORT);
  10871. EXPECT_FALSE(ret);
  10872. });
  10873. svr.wait_until_ready();
  10874. svr.stop();
  10875. t.join();
  10876. }
  10877. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10878. TEST(ServerStopTest, Decommision) {
  10879. Server svr;
  10880. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10881. for (int i = 0; i < 4; i++) {
  10882. auto is_even = !(i % 2);
  10883. std::thread t{[&] {
  10884. try {
  10885. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10886. if (is_even) {
  10887. throw std::runtime_error("Some thing that happens to go wrong.");
  10888. }
  10889. svr.listen(HOST, PORT);
  10890. } catch (...) { svr.decommission(); }
  10891. }};
  10892. svr.wait_until_ready();
  10893. // Server is up
  10894. {
  10895. Client cli(HOST, PORT);
  10896. auto res = cli.Get("/hi");
  10897. if (is_even) {
  10898. EXPECT_FALSE(res);
  10899. } else {
  10900. EXPECT_TRUE(res);
  10901. EXPECT_EQ("hi...", res->body);
  10902. }
  10903. }
  10904. svr.stop();
  10905. t.join();
  10906. // Server is down...
  10907. {
  10908. Client cli(HOST, PORT);
  10909. auto res = cli.Get("/hi");
  10910. EXPECT_FALSE(res);
  10911. }
  10912. }
  10913. }
  10914. #endif
  10915. // Helper function for string body upload progress tests
  10916. template <typename SetupHandler, typename ClientCall>
  10917. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10918. ClientCall &&client_call,
  10919. const string &body) {
  10920. Server svr;
  10921. setup_handler(svr);
  10922. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10923. auto se = detail::scope_exit([&] {
  10924. svr.stop();
  10925. t.join();
  10926. });
  10927. svr.wait_until_ready();
  10928. Client cli(HOST, PORT);
  10929. vector<uint64_t> progress_values;
  10930. bool progress_called = false;
  10931. auto res =
  10932. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10933. progress_values.push_back(current);
  10934. progress_called = true;
  10935. return true;
  10936. });
  10937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10938. EXPECT_EQ(200, res->status);
  10939. EXPECT_TRUE(progress_called);
  10940. }
  10941. TEST(UploadProgressTest, PostStringBodyBasic) {
  10942. TestStringBodyUploadProgress(
  10943. [](Server &svr) {
  10944. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10945. res.set_content("received", "text/plain");
  10946. });
  10947. },
  10948. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10949. return cli.Post("/test", body, "text/plain", progress_callback);
  10950. },
  10951. "test data for upload progress");
  10952. }
  10953. TEST(UploadProgressTest, PutStringBodyBasic) {
  10954. TestStringBodyUploadProgress(
  10955. [](Server &svr) {
  10956. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10957. res.set_content("put received", "text/plain");
  10958. });
  10959. },
  10960. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10961. return cli.Put("/test", body, "text/plain", progress_callback);
  10962. },
  10963. "put test data for upload progress");
  10964. }
  10965. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10966. TestStringBodyUploadProgress(
  10967. [](Server &svr) {
  10968. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10969. res.set_content("patch received", "text/plain");
  10970. });
  10971. },
  10972. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10973. return cli.Patch("/test", body, "text/plain", progress_callback);
  10974. },
  10975. "patch test data for upload progress");
  10976. }
  10977. // Helper function for content provider upload progress tests
  10978. template <typename SetupHandler, typename ClientCall>
  10979. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10980. ClientCall &&client_call) {
  10981. Server svr;
  10982. setup_handler(svr);
  10983. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10984. auto se = detail::scope_exit([&] {
  10985. svr.stop();
  10986. t.join();
  10987. });
  10988. svr.wait_until_ready();
  10989. Client cli(HOST, PORT);
  10990. vector<uint64_t> progress_values;
  10991. auto res =
  10992. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10993. progress_values.push_back(current);
  10994. return true;
  10995. });
  10996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10997. EXPECT_EQ(200, res->status);
  10998. EXPECT_FALSE(progress_values.empty());
  10999. }
  11000. TEST(UploadProgressTest, PostContentProviderProgress) {
  11001. TestContentProviderUploadProgress(
  11002. [](Server &svr) {
  11003. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11004. res.set_content("provider received", "text/plain");
  11005. });
  11006. },
  11007. [](Client &cli, UploadProgress progress_callback) {
  11008. return cli.Post(
  11009. "/test", 9,
  11010. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  11011. sink.os << "test data";
  11012. return true;
  11013. },
  11014. "text/plain", progress_callback);
  11015. });
  11016. }
  11017. // Helper function for multipart upload progress tests
  11018. template <typename SetupHandler, typename ClientCall>
  11019. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  11020. ClientCall &&client_call,
  11021. const string &endpoint) {
  11022. Server svr;
  11023. setup_handler(svr);
  11024. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11025. auto se = detail::scope_exit([&] {
  11026. svr.stop();
  11027. t.join();
  11028. });
  11029. svr.wait_until_ready();
  11030. Client cli(HOST, PORT);
  11031. vector<uint64_t> progress_values;
  11032. UploadFormDataItems items = {
  11033. {"field1", "value1", "", ""},
  11034. {"field2", "longer value for progress tracking test", "", ""},
  11035. {"file1", "file content data for upload progress", "test.txt",
  11036. "text/plain"}};
  11037. auto res = client_call(cli, endpoint, items,
  11038. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11039. progress_values.push_back(current);
  11040. return true;
  11041. });
  11042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11043. EXPECT_EQ(200, res->status);
  11044. EXPECT_FALSE(progress_values.empty());
  11045. }
  11046. TEST(UploadProgressTest, PostMultipartProgress) {
  11047. TestMultipartUploadProgress(
  11048. [](Server &svr) {
  11049. svr.Post("/multipart", [](const Request &req, Response &res) {
  11050. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  11051. res.set_content("multipart received", "text/plain");
  11052. });
  11053. },
  11054. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  11055. UploadProgress progress_callback) {
  11056. return cli.Post(endpoint, items, progress_callback);
  11057. },
  11058. "/multipart");
  11059. }
  11060. // Helper function for basic download progress tests
  11061. template <typename SetupHandler, typename ClientCall>
  11062. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11063. ClientCall &&client_call, const string &endpoint,
  11064. size_t expected_content_size) {
  11065. Server svr;
  11066. setup_handler(svr);
  11067. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11068. auto se = detail::scope_exit([&] {
  11069. svr.stop();
  11070. t.join();
  11071. });
  11072. svr.wait_until_ready();
  11073. Client cli(HOST, PORT);
  11074. vector<uint64_t> progress_values;
  11075. auto res = client_call(cli, endpoint,
  11076. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11077. progress_values.push_back(current);
  11078. return true;
  11079. });
  11080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11081. EXPECT_EQ(200, res->status);
  11082. EXPECT_FALSE(progress_values.empty());
  11083. EXPECT_EQ(expected_content_size, res->body.size());
  11084. }
  11085. TEST(DownloadProgressTest, GetBasic) {
  11086. TestBasicDownloadProgress(
  11087. [](Server &svr) {
  11088. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11089. string content(1000, 'D');
  11090. res.set_content(content, "text/plain");
  11091. });
  11092. },
  11093. [](Client &cli, const string &endpoint,
  11094. DownloadProgress progress_callback) {
  11095. return cli.Get(endpoint, progress_callback);
  11096. },
  11097. "/download", 1000u);
  11098. }
  11099. // Helper function for content receiver download progress tests
  11100. template <typename SetupHandler, typename ClientCall>
  11101. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11102. ClientCall &&client_call,
  11103. const string &endpoint,
  11104. size_t expected_content_size) {
  11105. Server svr;
  11106. setup_handler(svr);
  11107. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11108. auto se = detail::scope_exit([&] {
  11109. svr.stop();
  11110. t.join();
  11111. });
  11112. svr.wait_until_ready();
  11113. Client cli(HOST, PORT);
  11114. vector<uint64_t> progress_values;
  11115. string received_body;
  11116. auto res = client_call(
  11117. cli, endpoint,
  11118. [&](const char *data, size_t data_length) -> bool {
  11119. received_body.append(data, data_length);
  11120. return true;
  11121. },
  11122. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11123. progress_values.push_back(current);
  11124. return true;
  11125. });
  11126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11127. EXPECT_EQ(200, res->status);
  11128. EXPECT_FALSE(progress_values.empty());
  11129. EXPECT_EQ(expected_content_size, received_body.size());
  11130. EXPECT_TRUE(res->body.empty());
  11131. }
  11132. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11133. TestContentReceiverDownloadProgress(
  11134. [](Server &svr) {
  11135. svr.Get("/download-receiver",
  11136. [](const Request & /*req*/, Response &res) {
  11137. string content(2000, 'R');
  11138. res.set_content(content, "text/plain");
  11139. });
  11140. },
  11141. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11142. DownloadProgress progress_callback) {
  11143. return cli.Get(endpoint, content_receiver, progress_callback);
  11144. },
  11145. "/download-receiver", 2000u);
  11146. }
  11147. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11148. // A provider reaching a pass with nothing to hand over - an empty buffer
  11149. // popped off a queue, say - must not be taken to mean the body is finished.
  11150. // It used to end the loop with the terminating chunk unwritten while the
  11151. // server still considered the response complete, so the peer waited for an
  11152. // end that never arrived.
  11153. Server svr;
  11154. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11155. auto step = std::make_shared<int>(0);
  11156. res.set_chunked_content_provider("text/plain",
  11157. [step](size_t /*offset*/, DataSink &sink) {
  11158. switch ((*step)++) {
  11159. case 0: sink.write("", 0); break;
  11160. case 1: sink.write("hello", 5); break;
  11161. default: sink.done(); break;
  11162. }
  11163. return true;
  11164. });
  11165. });
  11166. auto port = svr.bind_to_any_port(HOST);
  11167. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11168. auto listen_se = detail::scope_exit([&] {
  11169. svr.stop();
  11170. listen_thread.join();
  11171. ASSERT_FALSE(svr.is_running());
  11172. });
  11173. svr.wait_until_ready();
  11174. Client cli(HOST, port);
  11175. // Without the fix the body is never terminated, so bound the wait rather
  11176. // than letting the test hang on the default read timeout.
  11177. cli.set_read_timeout(5, 0);
  11178. auto res = cli.Get("/stream");
  11179. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11180. EXPECT_EQ(StatusCode::OK_200, res->status);
  11181. EXPECT_EQ("hello", res->body);
  11182. }
  11183. TEST(StreamingTest, NoContentLengthStreaming) {
  11184. Server svr;
  11185. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11186. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11187. if (offset < 6) {
  11188. sink.os << (offset < 3 ? "a" : "b");
  11189. } else {
  11190. sink.done();
  11191. }
  11192. return true;
  11193. });
  11194. });
  11195. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11196. auto listen_se = detail::scope_exit([&] {
  11197. svr.stop();
  11198. listen_thread.join();
  11199. ASSERT_FALSE(svr.is_running());
  11200. });
  11201. svr.wait_until_ready();
  11202. Client client(HOST, PORT);
  11203. auto get_thread = std::thread([&client]() {
  11204. std::string s;
  11205. auto res =
  11206. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11207. s += std::string(data, len);
  11208. return true;
  11209. });
  11210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11211. EXPECT_EQ(StatusCode::OK_200, res->status);
  11212. EXPECT_EQ("aaabbb", s);
  11213. });
  11214. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11215. // Give GET time to get a few messages.
  11216. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11217. }
  11218. TEST(MountTest, Unmount) {
  11219. Server svr;
  11220. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11221. auto se = detail::scope_exit([&] {
  11222. svr.stop();
  11223. listen_thread.join();
  11224. ASSERT_FALSE(svr.is_running());
  11225. });
  11226. svr.wait_until_ready();
  11227. Client cli("localhost", PORT);
  11228. svr.set_mount_point("/mount2", "./www2");
  11229. auto res = cli.Get("/");
  11230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11231. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11232. res = cli.Get("/mount2/dir/test.html");
  11233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11234. EXPECT_EQ(StatusCode::OK_200, res->status);
  11235. svr.set_mount_point("/", "./www");
  11236. res = cli.Get("/dir/");
  11237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11238. EXPECT_EQ(StatusCode::OK_200, res->status);
  11239. svr.remove_mount_point("/");
  11240. res = cli.Get("/dir/");
  11241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11242. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11243. svr.remove_mount_point("/mount2");
  11244. res = cli.Get("/mount2/dir/test.html");
  11245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11246. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11247. }
  11248. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11249. Server svr;
  11250. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11251. svr.Get("/api/hello", [](const Request &, Response &res) {
  11252. res.set_content("api", "text/plain");
  11253. });
  11254. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11255. auto se = detail::scope_exit([&] {
  11256. svr.stop();
  11257. listen_thread.join();
  11258. ASSERT_FALSE(svr.is_running());
  11259. });
  11260. svr.wait_until_ready();
  11261. Client cli(HOST, PORT);
  11262. auto res = cli.Get("/dir/test.html");
  11263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11264. EXPECT_EQ(StatusCode::OK_200, res->status);
  11265. res = cli.Get("/api/hello");
  11266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11267. EXPECT_EQ(StatusCode::OK_200, res->status);
  11268. EXPECT_EQ("api", res->body);
  11269. }
  11270. TEST(MountTest, PathSegmentBoundary) {
  11271. Server svr;
  11272. svr.set_mount_point("/mount2", "./www2");
  11273. svr.set_mount_point("/", "./www");
  11274. auto port = svr.bind_to_any_port(HOST);
  11275. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11276. auto se = detail::scope_exit([&] {
  11277. svr.stop();
  11278. listen_thread.join();
  11279. ASSERT_FALSE(svr.is_running());
  11280. });
  11281. svr.wait_until_ready();
  11282. Client cli(HOST, port);
  11283. auto res = cli.Get("/mount2/dir/test.html");
  11284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11285. EXPECT_EQ(StatusCode::OK_200, res->status);
  11286. // "/mount2" must not match part-way through a path segment.
  11287. res = cli.Get("/mount2dir/test.html");
  11288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11289. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11290. // A mount point ending in '/' keeps matching every path below it.
  11291. res = cli.Get("/dir/test.html");
  11292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11293. EXPECT_EQ(StatusCode::OK_200, res->status);
  11294. }
  11295. TEST(MountTest, Redicect) {
  11296. Server svr;
  11297. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11298. auto se = detail::scope_exit([&] {
  11299. svr.stop();
  11300. listen_thread.join();
  11301. ASSERT_FALSE(svr.is_running());
  11302. });
  11303. svr.set_mount_point("/", "./www");
  11304. svr.wait_until_ready();
  11305. Client cli("localhost", PORT);
  11306. auto res = cli.Get("/dir/");
  11307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11308. EXPECT_EQ(StatusCode::OK_200, res->status);
  11309. res = cli.Get("/dir");
  11310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11311. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11312. res = cli.Get("/file");
  11313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11314. EXPECT_EQ(StatusCode::OK_200, res->status);
  11315. res = cli.Get("/file/");
  11316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11317. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11318. cli.set_follow_location(true);
  11319. res = cli.Get("/dir");
  11320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11321. EXPECT_EQ(StatusCode::OK_200, res->status);
  11322. }
  11323. TEST(MountTest, MultibytesPathName) {
  11324. Server svr;
  11325. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11326. auto se = detail::scope_exit([&] {
  11327. svr.stop();
  11328. listen_thread.join();
  11329. ASSERT_FALSE(svr.is_running());
  11330. });
  11331. svr.set_mount_point("/", "./www");
  11332. svr.wait_until_ready();
  11333. Client cli("localhost", PORT);
  11334. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11336. EXPECT_EQ(StatusCode::OK_200, res->status);
  11337. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11338. }
  11339. // A mount point serves no path with an empty segment or one ending in '.' or
  11340. // a space, so a guard in the pre-routing handler sees the path of every file
  11341. // that is served
  11342. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11343. Server svr;
  11344. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11345. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11346. if (req.path == "/dir/test.html") {
  11347. res.status = StatusCode::Unauthorized_401;
  11348. return Server::HandlerResponse::Handled;
  11349. }
  11350. return Server::HandlerResponse::Unhandled;
  11351. });
  11352. auto port = svr.bind_to_any_port(HOST);
  11353. ASSERT_LT(0, port);
  11354. thread t = thread([&] { svr.listen_after_bind(); });
  11355. auto se = detail::scope_exit([&] {
  11356. svr.stop();
  11357. t.join();
  11358. ASSERT_FALSE(svr.is_running());
  11359. });
  11360. svr.wait_until_ready();
  11361. Client cli(HOST, port);
  11362. for (auto path :
  11363. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11364. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11365. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11366. "/dir/test.html%3A%3A$DATA"}) {
  11367. SCOPED_TRACE(path);
  11368. auto res = cli.Get(path);
  11369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11370. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11371. }
  11372. }
  11373. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11374. Server svr;
  11375. svr.set_mount_point("/", "./www");
  11376. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11377. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11378. auto port = svr.bind_to_any_port(HOST);
  11379. ASSERT_GT(port, 0);
  11380. thread t = thread([&] { svr.listen_after_bind(); });
  11381. auto se = detail::scope_exit([&] {
  11382. svr.stop();
  11383. t.join();
  11384. ASSERT_FALSE(svr.is_running());
  11385. });
  11386. svr.wait_until_ready();
  11387. Client cli(HOST, port);
  11388. auto res = cli.Get("/dir/test.abcde");
  11389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11390. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11391. res = cli.Get("/dir/test.html");
  11392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11393. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11394. }
  11395. #ifdef _WIN32
  11396. // Issue #2435: mmap::open() must succeed even when another handle holds
  11397. // the file open for writing (e.g. an active log file).
  11398. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11399. const char *path = "mmap_concurrent_writer_test.txt";
  11400. const char *content = "hello";
  11401. {
  11402. std::ofstream f(path, std::ios::binary);
  11403. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11404. }
  11405. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11406. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11407. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11408. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11409. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11410. detail::mmap m(path);
  11411. ASSERT_TRUE(m.is_open());
  11412. EXPECT_EQ(strlen(content), m.size());
  11413. char buf[8];
  11414. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11415. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11416. }
  11417. #endif
  11418. #ifndef _WIN32
  11419. // A directory or a device has no size to serve.
  11420. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11421. const char *path = "./mmap_not_regular_test_dir";
  11422. ASSERT_EQ(0, ::mkdir(path, 0755));
  11423. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11424. for (auto p : {path, "/dev/null"}) {
  11425. detail::mmap m(p);
  11426. EXPECT_FALSE(m.is_open()) << p;
  11427. EXPECT_EQ(0U, m.size()) << p;
  11428. }
  11429. Server svr;
  11430. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11431. res.set_file_content("/dev/null");
  11432. });
  11433. auto port = svr.bind_to_any_port(HOST);
  11434. thread t = thread([&] { svr.listen_after_bind(); });
  11435. auto se = detail::scope_exit([&] {
  11436. svr.stop();
  11437. t.join();
  11438. });
  11439. svr.wait_until_ready();
  11440. auto res = Client(HOST, port).Get("/null");
  11441. ASSERT_TRUE(res);
  11442. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11443. }
  11444. #endif
  11445. #ifdef __linux__
  11446. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11447. TEST(MmapTest, FileIsNotMapped) {
  11448. const char *path = "mmap_not_mapped_test.txt";
  11449. {
  11450. std::ofstream f(path, std::ios::binary);
  11451. f << "hello";
  11452. }
  11453. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11454. detail::mmap m(path);
  11455. ASSERT_TRUE(m.is_open());
  11456. std::ifstream maps("/proc/self/maps");
  11457. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11458. std::istreambuf_iterator<char>());
  11459. EXPECT_EQ(std::string::npos, mappings.find(path));
  11460. }
  11461. #endif
  11462. TEST(KeepAliveTest, ReadTimeout) {
  11463. Server svr;
  11464. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11465. std::this_thread::sleep_for(std::chrono::seconds(2));
  11466. res.set_content("a", "text/plain");
  11467. });
  11468. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11469. res.set_content("b", "text/plain");
  11470. });
  11471. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11472. auto se = detail::scope_exit([&] {
  11473. svr.stop();
  11474. listen_thread.join();
  11475. ASSERT_FALSE(svr.is_running());
  11476. });
  11477. svr.wait_until_ready();
  11478. Client cli("localhost", PORT);
  11479. cli.set_keep_alive(true);
  11480. cli.set_read_timeout(std::chrono::seconds(1));
  11481. auto resa = cli.Get("/a");
  11482. ASSERT_FALSE(resa);
  11483. EXPECT_EQ(Error::Read, resa.error());
  11484. auto resb = cli.Get("/b");
  11485. ASSERT_TRUE(resb);
  11486. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11487. EXPECT_EQ("b", resb->body);
  11488. }
  11489. TEST(KeepAliveTest, MaxCount) {
  11490. size_t keep_alive_max_count = 3;
  11491. Server svr;
  11492. svr.set_keep_alive_max_count(keep_alive_max_count);
  11493. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11494. res.set_content("Hello World!", "text/plain");
  11495. });
  11496. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11497. auto se = detail::scope_exit([&] {
  11498. svr.stop();
  11499. listen_thread.join();
  11500. ASSERT_FALSE(svr.is_running());
  11501. });
  11502. svr.wait_until_ready();
  11503. Client cli(HOST, PORT);
  11504. cli.set_keep_alive(true);
  11505. for (size_t i = 0; i < 5; i++) {
  11506. auto result = cli.Get("/hi");
  11507. ASSERT_TRUE(result);
  11508. EXPECT_EQ(StatusCode::OK_200, result->status);
  11509. if (i == keep_alive_max_count - 1) {
  11510. EXPECT_EQ("close", result->get_header_value("Connection"));
  11511. } else {
  11512. EXPECT_FALSE(result->has_header("Connection"));
  11513. }
  11514. }
  11515. }
  11516. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11517. // can pull the next one into the server's buffer. The server must serve it
  11518. // without waiting for the socket to become readable again. The keep-alive
  11519. // timeout outlasts the client's read timeout, so a request left waiting for it
  11520. // shows up as a missing response.
  11521. static void serve_pipelining_routes(Server &svr,
  11522. const std::function<void(int)> &client) {
  11523. svr.set_keep_alive_timeout(5);
  11524. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11525. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11526. });
  11527. svr.Post("/echo", [](const Request &req, Response &res) {
  11528. res.set_content("echo " + req.body, "text/plain");
  11529. });
  11530. auto port = svr.bind_to_any_port(HOST);
  11531. thread t = thread([&] { svr.listen_after_bind(); });
  11532. auto se = detail::scope_exit([&] {
  11533. svr.stop();
  11534. t.join();
  11535. });
  11536. svr.wait_until_ready();
  11537. client(port);
  11538. }
  11539. static std::string
  11540. send_pipelined_requests(const std::vector<std::string> &parts) {
  11541. Server svr;
  11542. std::string res;
  11543. serve_pipelining_routes(svr, [&](int port) {
  11544. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11545. });
  11546. return res;
  11547. }
  11548. static void expect_in_order(const std::string &res,
  11549. const std::vector<std::string> &bodies) {
  11550. size_t pos = 0;
  11551. for (const auto &body : bodies) {
  11552. pos = res.find(body, pos);
  11553. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11554. pos += body.size();
  11555. }
  11556. }
  11557. TEST(KeepAliveTest, PipelinedRequests) {
  11558. auto res = send_pipelined_requests(
  11559. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11560. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11561. "Content-Length: 4\r\n\r\nbody"
  11562. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11563. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11564. }
  11565. // The second request starts in the server's buffer and ends on the socket.
  11566. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11567. auto res =
  11568. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11569. "GET /hi/2 HTTP/1.1\r\nHo",
  11570. "st: localhost\r\nConnection: close\r\n\r\n"});
  11571. expect_in_order(res, {"hi 1", "hi 2"});
  11572. }
  11573. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11574. // CRLF after a body does not turn into a 400 for the next request.
  11575. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11576. auto res = send_pipelined_requests(
  11577. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11578. "Content-Length: 4\r\n\r\nbody\r\n"
  11579. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11580. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11581. expect_in_order(res, {"echo body", "hi 2"});
  11582. }
  11583. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11584. // must not be served as the next request.
  11585. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11586. auto res = send_pipelined_requests(
  11587. {"INVALID REQUEST LINE\r\n\r\n"
  11588. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11589. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11590. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11591. }
  11592. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11593. // Over TLS, the next request is held by the TLS library as already decrypted
  11594. // data rather than on the socket.
  11595. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11596. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11597. std::string res;
  11598. serve_pipelining_routes(svr, [&](int port) {
  11599. // One part, so all three requests arrive in one TLS record
  11600. EXPECT_TRUE(send_ssl_request_in_parts(
  11601. 2,
  11602. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11603. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11604. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11605. &res, port));
  11606. });
  11607. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11608. }
  11609. #endif
  11610. TEST(KeepAliveTest, Issue1041) {
  11611. Server svr;
  11612. svr.set_keep_alive_timeout(3);
  11613. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11614. res.set_content("Hello World!", "text/plain");
  11615. });
  11616. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11617. auto se = detail::scope_exit([&] {
  11618. svr.stop();
  11619. listen_thread.join();
  11620. ASSERT_FALSE(svr.is_running());
  11621. });
  11622. svr.wait_until_ready();
  11623. Client cli(HOST, PORT);
  11624. cli.set_keep_alive(true);
  11625. auto result = cli.Get("/hi");
  11626. ASSERT_TRUE(result);
  11627. EXPECT_EQ(StatusCode::OK_200, result->status);
  11628. std::this_thread::sleep_for(std::chrono::seconds(5));
  11629. result = cli.Get("/hi");
  11630. ASSERT_TRUE(result);
  11631. EXPECT_EQ(StatusCode::OK_200, result->status);
  11632. }
  11633. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11634. Server svr;
  11635. svr.set_keep_alive_max_count(0);
  11636. std::set<int> remote_ports;
  11637. svr.Get("/hi", [&](const Request &req, Response &res) {
  11638. remote_ports.insert(req.remote_port);
  11639. res.set_content("hi", "text/plain");
  11640. });
  11641. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11642. auto se = detail::scope_exit([&] {
  11643. svr.stop();
  11644. listen_thread.join();
  11645. ASSERT_FALSE(svr.is_running());
  11646. });
  11647. svr.wait_until_ready();
  11648. Client cli(HOST, PORT);
  11649. cli.set_keep_alive(true);
  11650. for (int i = 0; i < 3; i++) {
  11651. auto res = cli.Get("/hi");
  11652. ASSERT_TRUE(res);
  11653. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11654. }
  11655. // All three over one connection
  11656. EXPECT_EQ(1u, remote_ports.size());
  11657. }
  11658. // Forward declaration (see the base64_encode note).
  11659. namespace httplib {
  11660. namespace detail {
  11661. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11662. } // namespace detail
  11663. } // namespace httplib
  11664. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11665. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11666. #ifndef _WIN32
  11667. signal(SIGPIPE, SIG_IGN);
  11668. #endif
  11669. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11670. ASSERT_NE(INVALID_SOCKET, srv);
  11671. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11672. default_socket_options(srv);
  11673. sockaddr_in addr{};
  11674. addr.sin_family = AF_INET;
  11675. addr.sin_port = 0;
  11676. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11677. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11678. ASSERT_EQ(0, ::listen(srv, 2));
  11679. socklen_t addr_len = sizeof(addr);
  11680. ASSERT_EQ(0,
  11681. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11682. auto port = ntohs(addr.sin_port);
  11683. struct Peer {
  11684. socket_t sock = INVALID_SOCKET;
  11685. #ifdef CPPHTTPLIB_SSL_ENABLED
  11686. tls::session_t session = nullptr;
  11687. #endif
  11688. };
  11689. #ifdef CPPHTTPLIB_SSL_ENABLED
  11690. tls::ctx_t ctx = nullptr;
  11691. if (use_tls) {
  11692. ctx = tls::create_server_context();
  11693. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11694. nullptr);
  11695. }
  11696. auto ctx_se = detail::scope_exit([&] {
  11697. if (ctx) { tls::free_context(ctx); }
  11698. });
  11699. #endif
  11700. auto close_peer = [](Peer &peer) {
  11701. #ifdef CPPHTTPLIB_SSL_ENABLED
  11702. if (peer.session) { tls::free_session(peer.session); }
  11703. #endif
  11704. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11705. };
  11706. auto accept_peer = [&]() {
  11707. Peer peer;
  11708. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11709. peer.sock = ::accept(srv, nullptr, nullptr);
  11710. if (peer.sock == INVALID_SOCKET) { return peer; }
  11711. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11712. #ifdef CPPHTTPLIB_SSL_ENABLED
  11713. if (use_tls) {
  11714. peer.session = tls::create_session(ctx, peer.sock);
  11715. tls::TlsError err;
  11716. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err)) {
  11717. close_peer(peer);
  11718. return Peer();
  11719. }
  11720. }
  11721. #endif
  11722. return peer;
  11723. };
  11724. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11725. #ifdef CPPHTTPLIB_SSL_ENABLED
  11726. tls::TlsError err;
  11727. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11728. #endif
  11729. return detail::read_socket(peer.sock, buf, len, 0);
  11730. };
  11731. auto read_head = [&](const Peer &peer) {
  11732. std::string head;
  11733. char buf[1024];
  11734. while (head.find("\r\n\r\n") == std::string::npos) {
  11735. auto n = read_some(peer, buf, sizeof(buf));
  11736. if (n <= 0) { break; }
  11737. head.append(buf, static_cast<size_t>(n));
  11738. }
  11739. };
  11740. auto send_text = [](const Peer &peer, const std::string &text) {
  11741. #ifdef CPPHTTPLIB_SSL_ENABLED
  11742. tls::TlsError err;
  11743. if (peer.session) {
  11744. tls::write(peer.session, text.data(), text.size(), err);
  11745. return;
  11746. }
  11747. #endif
  11748. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11749. };
  11750. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11751. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11752. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11753. // Sent once the first response is read, so that it lands on an idle socket
  11754. std::promise<void> first_response_read;
  11755. auto first_response_read_future = first_response_read.get_future();
  11756. auto server_thread = std::thread([&] {
  11757. auto peer1 = accept_peer();
  11758. if (peer1.sock == INVALID_SOCKET) { return; }
  11759. read_head(peer1);
  11760. if (same_write) {
  11761. send_text(peer1, first + stray);
  11762. } else {
  11763. send_text(peer1, first);
  11764. first_response_read_future.wait_for(std::chrono::seconds(5));
  11765. send_text(peer1, stray);
  11766. }
  11767. // peer1 stays open, so only the unread data can tell the client
  11768. auto peer2 = accept_peer();
  11769. if (peer2.sock != INVALID_SOCKET) {
  11770. read_head(peer2);
  11771. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11772. "Connection: close\r\n\r\nsecond");
  11773. close_peer(peer2);
  11774. }
  11775. close_peer(peer1);
  11776. });
  11777. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11778. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11779. std::to_string(port));
  11780. #ifdef CPPHTTPLIB_SSL_ENABLED
  11781. cli.enable_server_certificate_verification(false);
  11782. #endif
  11783. cli.set_keep_alive(true);
  11784. cli.set_read_timeout(5, 0);
  11785. auto res = cli.Get("/1");
  11786. first_response_read.set_value();
  11787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11788. EXPECT_EQ("first", res->body);
  11789. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11790. res = cli.Get("/2");
  11791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11792. EXPECT_EQ(StatusCode::OK_200, res->status);
  11793. EXPECT_EQ("second", res->body);
  11794. }
  11795. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11796. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11797. }
  11798. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11799. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11800. }
  11801. #ifdef CPPHTTPLIB_SSL_ENABLED
  11802. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11803. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11804. }
  11805. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11806. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11807. }
  11808. #endif
  11809. TEST(KeepAliveTest, Issue1959) {
  11810. Server svr;
  11811. svr.set_keep_alive_timeout(5);
  11812. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11813. res.set_content("a", "text/plain");
  11814. });
  11815. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11816. auto se = detail::scope_exit([&] {
  11817. if (!svr.is_running()) return;
  11818. svr.stop();
  11819. listen_thread.join();
  11820. ASSERT_FALSE(svr.is_running());
  11821. });
  11822. svr.wait_until_ready();
  11823. Client cli("localhost", PORT);
  11824. cli.set_keep_alive(true);
  11825. using namespace std::chrono;
  11826. auto start = steady_clock::now();
  11827. cli.Get("/a");
  11828. svr.stop();
  11829. listen_thread.join();
  11830. auto end = steady_clock::now();
  11831. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11832. EXPECT_LT(elapsed, 5000);
  11833. }
  11834. #ifdef CPPHTTPLIB_SSL_ENABLED
  11835. TEST(KeepAliveTest, SSLClientReconnection) {
  11836. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11837. ASSERT_TRUE(svr.is_valid());
  11838. svr.set_keep_alive_timeout(1);
  11839. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11840. res.set_content("Hello World!", "text/plain");
  11841. });
  11842. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11843. auto se = detail::scope_exit([&] {
  11844. svr.stop();
  11845. listen_thread.join();
  11846. ASSERT_FALSE(svr.is_running());
  11847. });
  11848. svr.wait_until_ready();
  11849. SSLClient cli(HOST, PORT);
  11850. cli.enable_server_certificate_verification(false);
  11851. cli.set_keep_alive(true);
  11852. auto result = cli.Get("/hi");
  11853. ASSERT_TRUE(result);
  11854. EXPECT_EQ(StatusCode::OK_200, result->status);
  11855. result = cli.Get("/hi");
  11856. ASSERT_TRUE(result);
  11857. EXPECT_EQ(StatusCode::OK_200, result->status);
  11858. std::this_thread::sleep_for(std::chrono::seconds(2));
  11859. // Recoonect
  11860. result = cli.Get("/hi");
  11861. ASSERT_TRUE(result);
  11862. EXPECT_EQ(StatusCode::OK_200, result->status);
  11863. result = cli.Get("/hi");
  11864. ASSERT_TRUE(result);
  11865. EXPECT_EQ(StatusCode::OK_200, result->status);
  11866. }
  11867. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11868. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11869. ASSERT_TRUE(svr.is_valid());
  11870. svr.set_keep_alive_timeout(1);
  11871. std::string content = "reconnect";
  11872. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11873. res.set_content("Hello World!", "text/plain");
  11874. });
  11875. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11876. auto se = detail::scope_exit([&] {
  11877. svr.stop();
  11878. listen_thread.join();
  11879. ASSERT_FALSE(svr.is_running());
  11880. });
  11881. svr.wait_until_ready();
  11882. SSLClient cli(HOST, PORT);
  11883. cli.enable_server_certificate_verification(false);
  11884. cli.set_keep_alive(true);
  11885. auto result = cli.Post(
  11886. "/hi", content.size(),
  11887. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11888. sink.write(content.c_str(), content.size());
  11889. return true;
  11890. },
  11891. "text/plain");
  11892. ASSERT_TRUE(result);
  11893. EXPECT_EQ(200, result->status);
  11894. std::this_thread::sleep_for(std::chrono::seconds(2));
  11895. // Recoonect
  11896. result = cli.Post(
  11897. "/hi", content.size(),
  11898. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11899. sink.write(content.c_str(), content.size());
  11900. return true;
  11901. },
  11902. "text/plain");
  11903. ASSERT_TRUE(result);
  11904. EXPECT_EQ(200, result->status);
  11905. result = cli.Post(
  11906. "/hi", content.size(),
  11907. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11908. sink.write(content.c_str(), content.size());
  11909. return true;
  11910. },
  11911. "text/plain");
  11912. ASSERT_TRUE(result);
  11913. EXPECT_EQ(200, result->status);
  11914. }
  11915. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11916. using namespace httplib::tls;
  11917. {
  11918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11919. ASSERT_TRUE(svr.is_valid());
  11920. svr.Get("/sni", [&](const Request &req, Response &res) {
  11921. std::string expected = req.sni();
  11922. EXPECT_EQ(expected, req.get_param_value("expected"));
  11923. res.set_content("ok", "text/plain");
  11924. });
  11925. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11926. auto se = detail::scope_exit([&] {
  11927. svr.stop();
  11928. listen_thread.join();
  11929. ASSERT_FALSE(svr.is_running());
  11930. });
  11931. svr.wait_until_ready();
  11932. {
  11933. SSLClient cli("localhost", PORT);
  11934. cli.enable_server_certificate_verification(false);
  11935. auto res = cli.Get("/sni?expected=localhost");
  11936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11937. }
  11938. {
  11939. SSLClient cli("::1", PORT);
  11940. cli.enable_server_certificate_verification(false);
  11941. auto res = cli.Get("/sni?expected=");
  11942. // NOTE: This may fail if the server is listening on IPv4 only
  11943. // (e.g., when localhost resolves to 127.0.0.1 only)
  11944. if (res) {
  11945. EXPECT_EQ(StatusCode::OK_200, res->status);
  11946. } else {
  11947. EXPECT_EQ(Error::Connection, res.error());
  11948. }
  11949. }
  11950. }
  11951. }
  11952. // The SNI of a failed handshake does not reach the next connection that the
  11953. // same worker thread serves
  11954. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11956. ASSERT_TRUE(svr.is_valid());
  11957. svr.new_task_queue = [] { return new ThreadPool(1); };
  11958. svr.Get("/sni", [](const Request &req, Response &res) {
  11959. res.set_content(req.sni(), "text/plain");
  11960. });
  11961. auto port = svr.bind_to_any_port("127.0.0.1");
  11962. ASSERT_LT(0, port);
  11963. thread t = thread([&] { svr.listen_after_bind(); });
  11964. auto se = detail::scope_exit([&] {
  11965. svr.stop();
  11966. t.join();
  11967. ASSERT_FALSE(svr.is_running());
  11968. });
  11969. svr.wait_until_ready();
  11970. {
  11971. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11972. SSLClient cli("localhost", port);
  11973. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11974. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11975. auto res = cli.Get("/sni");
  11976. ASSERT_FALSE(res);
  11977. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11978. }
  11979. // An IP host sends no SNI (RFC 6066)
  11980. SSLClient cli("127.0.0.1", port);
  11981. cli.enable_server_certificate_verification(false);
  11982. auto res = cli.Get("/sni");
  11983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11984. EXPECT_EQ("", res->body);
  11985. }
  11986. #endif
  11987. TEST(ClientProblemDetectionTest, ContentProvider) {
  11988. Server svr;
  11989. size_t content_length = 1024 * 1024;
  11990. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11991. res.set_content_provider(
  11992. content_length, "text/plain",
  11993. [&](size_t offset, size_t length, DataSink &sink) {
  11994. auto out_len = std::min(length, static_cast<size_t>(1024));
  11995. std::string out(out_len, '@');
  11996. sink.write(out.data(), out_len);
  11997. return offset < 4096;
  11998. },
  11999. [](bool success) { ASSERT_FALSE(success); });
  12000. });
  12001. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  12002. res.set_content_provider(
  12003. 0, "text/plain",
  12004. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  12005. EXPECT_TRUE(false);
  12006. return true;
  12007. },
  12008. [](bool success) { ASSERT_FALSE(success); });
  12009. });
  12010. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12011. auto se = detail::scope_exit([&] {
  12012. svr.stop();
  12013. listen_thread.join();
  12014. ASSERT_FALSE(svr.is_running());
  12015. });
  12016. svr.wait_until_ready();
  12017. Client cli("localhost", PORT);
  12018. {
  12019. auto res = cli.Get("/hi", [&](const char * /*data*/,
  12020. size_t /*data_length*/) { return false; });
  12021. ASSERT_FALSE(res);
  12022. }
  12023. {
  12024. auto res = cli.Get("/empty", [&](const char * /*data*/,
  12025. size_t /*data_length*/) { return false; });
  12026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12027. }
  12028. }
  12029. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  12030. // A provider that reports success without writing anything and without
  12031. // calling done() used to be handed the same offset and length again on every
  12032. // pass, so it spun for as long as the peer stayed connected.
  12033. Server svr;
  12034. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12035. res.set_content("ok", "text/plain");
  12036. });
  12037. auto port = svr.bind_to_any_port(HOST);
  12038. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  12039. auto se = detail::scope_exit([&] {
  12040. svr.stop();
  12041. listen_thread.join();
  12042. ASSERT_FALSE(svr.is_running());
  12043. });
  12044. svr.wait_until_ready();
  12045. std::atomic<int> call_count{0};
  12046. Client cli(HOST, port);
  12047. auto res = cli.Post(
  12048. "/", 1024,
  12049. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  12050. // Give up after enough passes to show the spin, so that losing the
  12051. // check below fails this test instead of hanging it.
  12052. return ++call_count < 100;
  12053. },
  12054. "text/plain");
  12055. ASSERT_FALSE(res);
  12056. EXPECT_EQ(Error::Write, res.error());
  12057. EXPECT_EQ(1, call_count.load());
  12058. }
  12059. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12060. // A writer only has to assign `write`. The other three used to be left as
  12061. // empty std::functions, so a provider calling one threw
  12062. // std::bad_function_call out of the thread running it and took the whole
  12063. // process down.
  12064. DataSink sink;
  12065. std::string written;
  12066. sink.write = [&](const char *data, size_t data_len) {
  12067. written.append(data, data_len);
  12068. return true;
  12069. };
  12070. EXPECT_TRUE(sink.is_writable());
  12071. sink.done();
  12072. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12073. EXPECT_TRUE(written.empty());
  12074. }
  12075. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12076. // A sink that cannot carry trailers still has to finish.
  12077. DataSink sink;
  12078. auto done_count = 0;
  12079. sink.done = [&]() { done_count++; };
  12080. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12081. EXPECT_EQ(1, done_count);
  12082. }
  12083. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12084. Server svr;
  12085. const std::string body(4096, 'x');
  12086. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12087. res.set_content_provider(body.size(), "text/plain",
  12088. [&](size_t offset, size_t length, DataSink &sink) {
  12089. sink.write(body.data() + offset, length);
  12090. sink.done();
  12091. return true;
  12092. });
  12093. });
  12094. auto port = svr.bind_to_any_port(HOST);
  12095. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12096. auto se = detail::scope_exit([&] {
  12097. svr.stop();
  12098. listen_thread.join();
  12099. ASSERT_FALSE(svr.is_running());
  12100. });
  12101. svr.wait_until_ready();
  12102. Client cli(HOST, port);
  12103. auto res = cli.Get("/");
  12104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12105. EXPECT_EQ(StatusCode::OK_200, res->status);
  12106. EXPECT_EQ(body, res->body);
  12107. }
  12108. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12109. Server svr;
  12110. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12111. res.set_content_provider(
  12112. 1024, "text/plain",
  12113. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12114. sink.write("hello", 5);
  12115. sink.done(); // short of the 1024 bytes the response promised
  12116. return true;
  12117. });
  12118. });
  12119. auto port = svr.bind_to_any_port(HOST);
  12120. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12121. auto se = detail::scope_exit([&] {
  12122. svr.stop();
  12123. listen_thread.join();
  12124. ASSERT_FALSE(svr.is_running());
  12125. });
  12126. svr.wait_until_ready();
  12127. Client cli(HOST, port);
  12128. cli.set_read_timeout(5, 0);
  12129. // The response is short of its Content-Length, so the client cannot read a
  12130. // complete body. What matters is that this returns at all: a no-op done()
  12131. // would leave the writer looping over a provider that never makes progress.
  12132. auto res = cli.Get("/");
  12133. EXPECT_FALSE(res);
  12134. }
  12135. // Read as the next response by a peer that sees it after a framed body.
  12136. static const std::string smuggled_response =
  12137. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12138. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12139. Server svr;
  12140. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12141. res.set_content_provider(
  12142. 5, "text/plain",
  12143. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12144. auto data = "AAAAA" + smuggled_response;
  12145. sink.write(data.data(), data.size());
  12146. return true;
  12147. });
  12148. });
  12149. thread t = thread([&] { svr.listen(HOST, PORT); });
  12150. auto se = detail::scope_exit([&] {
  12151. svr.stop();
  12152. t.join();
  12153. ASSERT_FALSE(svr.is_running());
  12154. });
  12155. svr.wait_until_ready();
  12156. std::string resp;
  12157. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12158. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12159. resp.clear();
  12160. ASSERT_TRUE(send_request(
  12161. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12162. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12163. }
  12164. TEST(NoContentTest, BodyIsNotSent) {
  12165. Server svr;
  12166. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12167. res.status = StatusCode::NoContent_204;
  12168. res.set_content(smuggled_response, "text/plain");
  12169. });
  12170. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12171. res.status = StatusCode::NotModified_304;
  12172. res.set_chunked_content_provider(
  12173. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12174. sink.write(smuggled_response.data(), smuggled_response.size());
  12175. sink.done();
  12176. return true;
  12177. });
  12178. });
  12179. thread t = thread([&] { svr.listen(HOST, PORT); });
  12180. auto se = detail::scope_exit([&] {
  12181. svr.stop();
  12182. t.join();
  12183. ASSERT_FALSE(svr.is_running());
  12184. });
  12185. svr.wait_until_ready();
  12186. for (auto path : {"/204", "/304"}) {
  12187. std::string resp;
  12188. ASSERT_TRUE(send_request(
  12189. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12190. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12191. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12192. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12193. }
  12194. }
  12195. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12196. Server svr;
  12197. std::atomic<bool> smuggled(false);
  12198. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12199. res.set_content("ok", "text/plain");
  12200. });
  12201. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12202. smuggled = true;
  12203. });
  12204. auto port = svr.bind_to_any_port(HOST);
  12205. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12206. auto se = detail::scope_exit([&] {
  12207. svr.stop();
  12208. listen_thread.join();
  12209. ASSERT_FALSE(svr.is_running());
  12210. });
  12211. svr.wait_until_ready();
  12212. // What follows the body would be read as the next request.
  12213. Client cli(HOST, port);
  12214. auto res = cli.Post(
  12215. "/", 5,
  12216. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12217. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12218. sink.write(data.data(), data.size());
  12219. return true;
  12220. },
  12221. "text/plain");
  12222. ASSERT_FALSE(res);
  12223. EXPECT_EQ(Error::Write, res.error());
  12224. EXPECT_FALSE(smuggled);
  12225. }
  12226. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12227. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12228. // The compressed path builds the whole body before connecting, so this
  12229. // fails client-side and never reaches a server.
  12230. Client cli(HOST, PORT);
  12231. cli.set_compress(true);
  12232. auto res = cli.Post(
  12233. "/", 1024,
  12234. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12235. sink.write("hello", 5);
  12236. sink.done(); // short of the 1024 bytes the request announced
  12237. return true;
  12238. },
  12239. "text/plain");
  12240. ASSERT_FALSE(res);
  12241. EXPECT_EQ(Error::Write, res.error());
  12242. }
  12243. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12244. Server svr;
  12245. std::string received;
  12246. size_t content_length_count = 0;
  12247. bool has_transfer_encoding = true;
  12248. svr.Post("/echo", [&](const Request &req, Response &res) {
  12249. received = req.body;
  12250. content_length_count = req.get_header_value_count("Content-Length");
  12251. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12252. res.set_content("ok", "text/plain");
  12253. });
  12254. svr.Get("/next", [](const Request &, Response &res) {
  12255. res.set_content("next", "text/plain");
  12256. });
  12257. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12258. auto se = detail::scope_exit([&] {
  12259. svr.stop();
  12260. listen_thread.join();
  12261. ASSERT_FALSE(svr.is_running());
  12262. });
  12263. svr.wait_until_ready();
  12264. Client cli(HOST, PORT);
  12265. cli.set_keep_alive(true);
  12266. cli.set_compress(true);
  12267. const std::string body = "hello world";
  12268. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12269. auto res = cli.Post("/echo", headers, body, "text/plain");
  12270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12271. EXPECT_EQ(StatusCode::OK_200, res->status);
  12272. EXPECT_EQ(body, received);
  12273. EXPECT_EQ(1u, content_length_count);
  12274. EXPECT_FALSE(has_transfer_encoding);
  12275. // The rest of a truncated body would be read as this request
  12276. auto res2 = cli.Get("/next");
  12277. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12278. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12279. EXPECT_EQ("next", res2->body);
  12280. }
  12281. #endif
  12282. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12283. Server svr;
  12284. std::string received;
  12285. size_t content_length_count = 1;
  12286. bool has_transfer_encoding = false;
  12287. svr.Post("/echo", [&](const Request &req, Response &res) {
  12288. received = req.body;
  12289. content_length_count = req.get_header_value_count("Content-Length");
  12290. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12291. res.set_content("ok", "text/plain");
  12292. });
  12293. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12294. auto se = detail::scope_exit([&] {
  12295. svr.stop();
  12296. listen_thread.join();
  12297. ASSERT_FALSE(svr.is_running());
  12298. });
  12299. svr.wait_until_ready();
  12300. Client cli(HOST, PORT);
  12301. cli.set_keep_alive(true);
  12302. const std::string body = "hello world";
  12303. Headers headers = {{"Content-Length", "5"}};
  12304. auto res = cli.Post(
  12305. "/echo", headers,
  12306. [&](size_t /*offset*/, DataSink &sink) {
  12307. sink.write(body.data(), body.size());
  12308. sink.done();
  12309. return true;
  12310. },
  12311. "text/plain");
  12312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12313. EXPECT_EQ(StatusCode::OK_200, res->status);
  12314. EXPECT_EQ(body, received);
  12315. EXPECT_EQ(0u, content_length_count);
  12316. EXPECT_TRUE(has_transfer_encoding);
  12317. }
  12318. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12319. Server svr;
  12320. svr.set_error_handler([](Request const &, Response &res) -> void {
  12321. res.set_chunked_content_provider(
  12322. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12323. sink.os << "hello";
  12324. sink.os << "world";
  12325. sink.done();
  12326. return true;
  12327. });
  12328. });
  12329. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12330. auto se = detail::scope_exit([&] {
  12331. svr.stop();
  12332. listen_thread.join();
  12333. ASSERT_FALSE(svr.is_running());
  12334. });
  12335. svr.wait_until_ready();
  12336. Client cli("localhost", PORT);
  12337. auto res = cli.Get("/");
  12338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12339. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12340. EXPECT_EQ("helloworld", res->body);
  12341. }
  12342. // A body set after a content provider must replace it, not be sent through it.
  12343. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12344. Server svr;
  12345. svr.set_mount_point("/", "./www");
  12346. svr.set_file_request_handler([](const Request &req, Response &res) {
  12347. if (req.path == "/dir/test.html") {
  12348. res.status = StatusCode::Forbidden_403;
  12349. res.set_content(std::string(5000, 'D'), "text/plain");
  12350. } else if (req.path == "/file") {
  12351. res.status = StatusCode::Forbidden_403;
  12352. res.body = "Denied";
  12353. }
  12354. });
  12355. auto port = svr.bind_to_any_port(HOST);
  12356. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12357. auto se = detail::scope_exit([&] {
  12358. svr.stop();
  12359. t.join();
  12360. ASSERT_FALSE(svr.is_running());
  12361. });
  12362. svr.wait_until_ready();
  12363. Client cli(HOST, port);
  12364. {
  12365. auto res = cli.Get("/dir/test.html");
  12366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12367. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12368. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12369. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12370. }
  12371. {
  12372. auto res = cli.Get("/file");
  12373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12374. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12375. EXPECT_EQ("Denied", res->body);
  12376. }
  12377. {
  12378. auto res = cli.Get("/dir/index.html");
  12379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12380. EXPECT_EQ(StatusCode::OK_200, res->status);
  12381. EXPECT_EQ(0U, res->body.find("<html>"));
  12382. }
  12383. }
  12384. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12385. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12386. Server svr;
  12387. std::vector<bool> released;
  12388. std::mutex released_mutex;
  12389. auto releaser = [&](bool success) {
  12390. std::lock_guard<std::mutex> guard(released_mutex);
  12391. released.push_back(success);
  12392. };
  12393. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12394. return sink.write(&"hello"[offset], length);
  12395. };
  12396. svr.Get("/sized", [&](const Request &, Response &res) {
  12397. res.status = StatusCode::NotFound_404;
  12398. res.set_content_provider(5, "text/plain", provider, releaser);
  12399. });
  12400. svr.Get("/chunked", [&](const Request &, Response &res) {
  12401. res.status = StatusCode::ServiceUnavailable_503;
  12402. res.set_chunked_content_provider(
  12403. "text/plain",
  12404. [](size_t, DataSink &sink) {
  12405. sink.os << "chunk";
  12406. sink.done();
  12407. return true;
  12408. },
  12409. releaser);
  12410. });
  12411. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12412. res.set_content_provider(5, "text/plain", provider, releaser);
  12413. throw std::runtime_error("after the provider");
  12414. });
  12415. svr.set_error_handler([](const Request &req, Response &res) {
  12416. // Leave the exception handler's content to it.
  12417. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12418. res.set_content(std::string(1000, 'E'), "text/html");
  12419. return Server::HandlerResponse::Handled;
  12420. });
  12421. svr.set_exception_handler(
  12422. [](const Request &, Response &res, std::exception_ptr) {
  12423. res.status = StatusCode::InternalServerError_500;
  12424. res.set_content(std::string(1000, 'X'), "text/html");
  12425. });
  12426. auto port = svr.bind_to_any_port(HOST);
  12427. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12428. auto se = detail::scope_exit([&] {
  12429. svr.stop();
  12430. t.join();
  12431. ASSERT_FALSE(svr.is_running());
  12432. });
  12433. svr.wait_until_ready();
  12434. Client cli(HOST, port);
  12435. {
  12436. auto res = cli.Get("/sized");
  12437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12438. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12439. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12440. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12441. }
  12442. {
  12443. auto res = cli.Get("/chunked");
  12444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12445. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12446. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12447. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12448. }
  12449. {
  12450. auto res = cli.Get("/throw");
  12451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12452. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12453. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12454. }
  12455. std::lock_guard<std::mutex> guard(released_mutex);
  12456. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12457. }
  12458. #endif
  12459. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12460. Server svr;
  12461. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12462. return sink.write(&"abc"[offset], length);
  12463. };
  12464. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12465. res.set_file_content("./www/dir/test.html");
  12466. res.set_content("body", "text/plain");
  12467. });
  12468. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12469. res.set_content(std::string(100, 'B'), "text/plain");
  12470. res.set_file_content("./www/dir/test.html");
  12471. });
  12472. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12473. res.set_content(std::string(100, 'B'), "text/plain");
  12474. res.set_content_provider(3, "text/x-provider", abc);
  12475. });
  12476. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12477. res.set_content_provider(3, "text/x-provider", abc);
  12478. res.set_content(std::string(100, 'B'), "text/plain");
  12479. });
  12480. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12481. res.set_content_provider(3, "text/x-provider", abc);
  12482. res.set_file_content("./www/dir/test.html", "text/x-file");
  12483. });
  12484. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12485. res.set_file_content("./www/dir/test.html");
  12486. res.set_header("Content-Type", "text/x-handler");
  12487. });
  12488. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12489. res.set_content_provider(3, "text/plain", abc);
  12490. res.body = "direct";
  12491. });
  12492. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12493. res.set_file_content("./www/dir/test.html");
  12494. res.body = "direct";
  12495. });
  12496. auto port = svr.bind_to_any_port(HOST);
  12497. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12498. auto se = detail::scope_exit([&] {
  12499. svr.stop();
  12500. t.join();
  12501. ASSERT_FALSE(svr.is_running());
  12502. });
  12503. svr.wait_until_ready();
  12504. Client cli(HOST, port);
  12505. auto expect_body = [&](const char *path, const std::string &body,
  12506. const std::string &type) {
  12507. // Uncompressed, so Content-Length can be compared with the body.
  12508. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12509. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12510. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12511. EXPECT_EQ(body, res->body) << path;
  12512. EXPECT_EQ(std::to_string(body.size()),
  12513. res->get_header_value("Content-Length"))
  12514. << path;
  12515. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12516. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12517. };
  12518. expect_body("/file-then-body", "body", "text/plain");
  12519. expect_body("/body-then-file", "test.html", "text/html");
  12520. expect_body("/body-then-provider", "abc", "text/x-provider");
  12521. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12522. expect_body("/provider-then-file", "test.html", "text/x-file");
  12523. expect_body("/file-then-header", "test.html", "text/x-handler");
  12524. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12525. expect_body("/file-then-direct-body", "direct", "text/plain");
  12526. // Ranges are checked against the body, not the dropped provider.
  12527. {
  12528. auto res = cli.Get("/provider-then-direct-body",
  12529. Headers{{make_range_header({{1, 2}})}});
  12530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12531. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12532. EXPECT_EQ("ir", res->body);
  12533. }
  12534. {
  12535. auto res = cli.Get("/file-then-direct-body",
  12536. Headers{{make_range_header({{7, 8}})}});
  12537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12538. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12539. }
  12540. }
  12541. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12542. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12543. const char *path = "./truncated_while_served.txt";
  12544. const size_t size = 32 * 1024 * 1024;
  12545. {
  12546. std::ofstream f(path, std::ios::binary);
  12547. f << std::string(size, 'x');
  12548. }
  12549. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12550. // Over TLS, where the bytes are encrypted in this process rather than
  12551. // copied by send().
  12552. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12553. svr.Get("/file", [&](const Request &, Response &res) {
  12554. res.set_file_content(path, "text/plain");
  12555. });
  12556. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12557. auto se = detail::scope_exit([&] {
  12558. svr.stop();
  12559. thread.join();
  12560. ASSERT_FALSE(svr.is_running());
  12561. });
  12562. svr.wait_until_ready();
  12563. // The file shrinks once the first bytes are in, as a rewrite in place
  12564. // would, and reading the mapping past its new end used to raise SIGBUS.
  12565. SSLClient cli(HOST, PORT);
  12566. cli.enable_server_certificate_verification(false);
  12567. size_t received = 0;
  12568. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12569. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12570. received += len;
  12571. return true;
  12572. });
  12573. EXPECT_FALSE(res);
  12574. EXPECT_LT(received, size);
  12575. }
  12576. #endif
  12577. // Forward declaration (see the base64_encode note).
  12578. namespace httplib {
  12579. namespace detail {
  12580. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12581. const std::string &content_type,
  12582. EncodingType encoding);
  12583. } // namespace detail
  12584. } // namespace httplib
  12585. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12586. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12587. ASSERT_TRUE(mm->is_open());
  12588. Response res;
  12589. detail::set_file_content_provider(res, mm, "text/html",
  12590. detail::EncodingType::None);
  12591. std::string out;
  12592. DataSink sink;
  12593. sink.write = [&](const char *d, size_t l) {
  12594. out.append(d, l);
  12595. return true;
  12596. };
  12597. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12598. EXPECT_EQ("test.html", out);
  12599. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12600. EXPECT_EQ("test.html", out);
  12601. }
  12602. TEST(LongPollingTest, ClientCloseDetection) {
  12603. Server svr;
  12604. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12605. res.set_chunked_content_provider(
  12606. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12607. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12608. sink.os << "hello";
  12609. auto count = 10;
  12610. while (count > 0 && sink.is_writable()) {
  12611. this_thread::sleep_for(chrono::milliseconds(10));
  12612. count--;
  12613. }
  12614. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12615. return true;
  12616. });
  12617. });
  12618. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12619. auto se = detail::scope_exit([&] {
  12620. svr.stop();
  12621. listen_thread.join();
  12622. ASSERT_FALSE(svr.is_running());
  12623. });
  12624. svr.wait_until_ready();
  12625. Client cli("localhost", PORT);
  12626. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12627. EXPECT_EQ("hello", string(data, data_length));
  12628. return false; // close the socket immediately.
  12629. });
  12630. ASSERT_FALSE(res);
  12631. }
  12632. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12633. Server svr;
  12634. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12635. res.set_chunked_content_provider(
  12636. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12637. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12638. sink.os << "hello";
  12639. EXPECT_TRUE(sink.os.good());
  12640. // Wait for the client to close the connection
  12641. auto count = 10;
  12642. while (count > 0 && sink.is_writable()) {
  12643. this_thread::sleep_for(chrono::milliseconds(10));
  12644. count--;
  12645. }
  12646. // After client disconnect, write repeatedly until the socket
  12647. // write actually fails (small writes may be absorbed by the
  12648. // kernel buffer)
  12649. std::string chunk(1024, 'x');
  12650. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12651. sink.os << chunk;
  12652. }
  12653. EXPECT_TRUE(sink.os.fail());
  12654. return true;
  12655. });
  12656. });
  12657. auto port = svr.bind_to_any_port("localhost");
  12658. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12659. auto se = detail::scope_exit([&] {
  12660. svr.stop();
  12661. listen_thread.join();
  12662. ASSERT_FALSE(svr.is_running());
  12663. });
  12664. svr.wait_until_ready();
  12665. Client cli("localhost", port);
  12666. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12667. EXPECT_EQ("hello", string(data, data_length));
  12668. return false; // close the socket immediately.
  12669. });
  12670. ASSERT_FALSE(res);
  12671. }
  12672. TEST(GetWithParametersTest, GetWithParameters) {
  12673. Server svr;
  12674. svr.Get("/", [&](const Request &req, Response &) {
  12675. EXPECT_EQ("world", req.get_param_value("hello"));
  12676. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12677. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12678. });
  12679. svr.Get("/params", [&](const Request &req, Response &) {
  12680. EXPECT_EQ("world", req.get_param_value("hello"));
  12681. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12682. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12683. });
  12684. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12685. EXPECT_EQ("resource-id", req.matches[1]);
  12686. EXPECT_EQ("foo", req.get_param_value("param1"));
  12687. EXPECT_EQ("bar", req.get_param_value("param2"));
  12688. });
  12689. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12690. EXPECT_EQ("user-id", req.path_params.at("id"));
  12691. EXPECT_EQ("foo", req.get_param_value("param1"));
  12692. EXPECT_EQ("bar", req.get_param_value("param2"));
  12693. });
  12694. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12695. auto se = detail::scope_exit([&] {
  12696. svr.stop();
  12697. listen_thread.join();
  12698. ASSERT_FALSE(svr.is_running());
  12699. });
  12700. svr.wait_until_ready();
  12701. {
  12702. Client cli(HOST, PORT);
  12703. Params params;
  12704. params.emplace("hello", "world");
  12705. params.emplace("hello2", "world2");
  12706. params.emplace("hello3", "world3");
  12707. auto res = cli.Get("/", params, Headers{});
  12708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12709. EXPECT_EQ(StatusCode::OK_200, res->status);
  12710. }
  12711. {
  12712. Client cli(HOST, PORT);
  12713. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12715. EXPECT_EQ(StatusCode::OK_200, res->status);
  12716. }
  12717. {
  12718. Client cli(HOST, PORT);
  12719. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12721. EXPECT_EQ(StatusCode::OK_200, res->status);
  12722. }
  12723. {
  12724. Client cli(HOST, PORT);
  12725. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12727. EXPECT_EQ(StatusCode::OK_200, res->status);
  12728. }
  12729. }
  12730. TEST(GetWithParametersTest, GetWithParameters2) {
  12731. Server svr;
  12732. svr.Get("/", [&](const Request &req, Response &res) {
  12733. auto text = req.get_param_value("hello");
  12734. res.set_content(text, "text/plain");
  12735. });
  12736. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12737. auto se = detail::scope_exit([&] {
  12738. svr.stop();
  12739. listen_thread.join();
  12740. ASSERT_FALSE(svr.is_running());
  12741. });
  12742. svr.wait_until_ready();
  12743. Client cli("localhost", PORT);
  12744. Params params;
  12745. params.emplace("hello", "world");
  12746. std::string body;
  12747. auto res = cli.Get("/", params, Headers{},
  12748. [&](const char *data, size_t data_length) {
  12749. body.append(data, data_length);
  12750. return true;
  12751. });
  12752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12753. EXPECT_EQ(StatusCode::OK_200, res->status);
  12754. EXPECT_EQ("world", body);
  12755. }
  12756. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12757. Server svr;
  12758. svr.Get("/search", [&](const Request &req, Response &res) {
  12759. auto q = req.get_param_value("q");
  12760. res.set_content(q, "text/plain");
  12761. });
  12762. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12763. auto se = detail::scope_exit([&] {
  12764. svr.stop();
  12765. listen_thread.join();
  12766. ASSERT_FALSE(svr.is_running());
  12767. });
  12768. svr.wait_until_ready();
  12769. Client cli("localhost", PORT);
  12770. // Verify that Get(path, params) works without requiring Headers argument
  12771. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12773. EXPECT_EQ(StatusCode::OK_200, res->status);
  12774. EXPECT_EQ("cpp-httplib", res->body);
  12775. }
  12776. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12777. auto host = "httpbingo.org";
  12778. auto path = std::string{"/range/32"};
  12779. #ifdef CPPHTTPLIB_SSL_ENABLED
  12780. SSLClient cli(host);
  12781. #else
  12782. Client cli(host);
  12783. #endif
  12784. cli.set_default_headers({make_range_header({{1, 10}})});
  12785. cli.set_connection_timeout(5);
  12786. {
  12787. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  12788. SKIP_ON_GATEWAY_ERROR(res);
  12789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12790. EXPECT_EQ("bcdefghijk", res->body);
  12791. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12792. }
  12793. {
  12794. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  12795. SKIP_ON_GATEWAY_ERROR(res);
  12796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12797. EXPECT_EQ("bcdefghijk", res->body);
  12798. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12799. }
  12800. }
  12801. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12802. Server svr;
  12803. svr.set_default_headers({{"Hello", "World"}});
  12804. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12805. res.set_content("ok", "text/plain");
  12806. });
  12807. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12808. auto se = detail::scope_exit([&] {
  12809. svr.stop();
  12810. listen_thread.join();
  12811. ASSERT_FALSE(svr.is_running());
  12812. });
  12813. svr.wait_until_ready();
  12814. Client cli("localhost", PORT);
  12815. auto res = cli.Get("/");
  12816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12817. EXPECT_EQ(StatusCode::OK_200, res->status);
  12818. EXPECT_EQ("ok", res->body);
  12819. EXPECT_EQ("World", res->get_header_value("Hello"));
  12820. }
  12821. #ifdef CPPHTTPLIB_SSL_ENABLED
  12822. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12823. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12824. ASSERT_TRUE(svr.is_valid());
  12825. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12826. std::this_thread::sleep_for(std::chrono::seconds(2));
  12827. res.set_content("a", "text/plain");
  12828. });
  12829. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12830. res.set_content("b", "text/plain");
  12831. });
  12832. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12833. auto se = detail::scope_exit([&] {
  12834. svr.stop();
  12835. listen_thread.join();
  12836. ASSERT_FALSE(svr.is_running());
  12837. });
  12838. svr.wait_until_ready();
  12839. SSLClient cli("localhost", PORT);
  12840. cli.enable_server_certificate_verification(false);
  12841. cli.set_keep_alive(true);
  12842. cli.set_read_timeout(std::chrono::seconds(1));
  12843. auto resa = cli.Get("/a");
  12844. ASSERT_TRUE(!resa);
  12845. EXPECT_EQ(Error::Read, resa.error());
  12846. auto resb = cli.Get("/b");
  12847. ASSERT_TRUE(resb);
  12848. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12849. EXPECT_EQ("b", resb->body);
  12850. }
  12851. // Closing an idle keep-alive connection sends close_notify and returns. The
  12852. // server must not wait for the client's close_notify: an idle client never
  12853. // sends one, so the worker would be held until the read timeout expires, and
  12854. // stop() would wait for it.
  12855. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12856. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12857. ASSERT_TRUE(svr.is_valid());
  12858. svr.set_keep_alive_timeout(1);
  12859. svr.set_read_timeout(10, 0);
  12860. svr.Get("/", [](const Request &, Response &res) {
  12861. res.set_content("ok", "text/plain");
  12862. });
  12863. auto port = svr.bind_to_any_port(HOST);
  12864. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12865. auto se = detail::scope_exit([&] {
  12866. if (listen_thread.joinable()) {
  12867. svr.stop();
  12868. listen_thread.join();
  12869. }
  12870. });
  12871. svr.wait_until_ready();
  12872. SSLClient cli(HOST, port);
  12873. cli.enable_server_certificate_verification(false);
  12874. cli.set_keep_alive(true);
  12875. auto res = cli.Get("/");
  12876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12877. EXPECT_EQ(StatusCode::OK_200, res->status);
  12878. // Stay idle past the keep-alive timeout so the server closes the connection.
  12879. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12880. auto start = std::chrono::steady_clock::now();
  12881. svr.stop();
  12882. listen_thread.join();
  12883. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12884. std::chrono::steady_clock::now() - start)
  12885. .count();
  12886. EXPECT_LT(elapsed, 3000);
  12887. }
  12888. #endif
  12889. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12890. protected:
  12891. ServerTestWithAI_PASSIVE()
  12892. : cli_(HOST, PORT)
  12893. #ifdef CPPHTTPLIB_SSL_ENABLED
  12894. ,
  12895. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12896. #endif
  12897. {
  12898. #ifdef CPPHTTPLIB_SSL_ENABLED
  12899. cli_.enable_server_certificate_verification(false);
  12900. #endif
  12901. }
  12902. virtual void SetUp() {
  12903. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12904. res.set_content("Hello World!", "text/plain");
  12905. });
  12906. t_ = thread(
  12907. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12908. svr_.wait_until_ready();
  12909. }
  12910. virtual void TearDown() {
  12911. svr_.stop();
  12912. t_.join();
  12913. }
  12914. #ifdef CPPHTTPLIB_SSL_ENABLED
  12915. SSLClient cli_;
  12916. SSLServer svr_;
  12917. #else
  12918. Client cli_;
  12919. Server svr_;
  12920. #endif
  12921. thread t_;
  12922. };
  12923. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12924. auto res = cli_.Get("/hi");
  12925. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12926. EXPECT_EQ(StatusCode::OK_200, res->status);
  12927. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12928. EXPECT_EQ("Hello World!", res->body);
  12929. }
  12930. class ServerUpDownTest : public ::testing::Test {
  12931. protected:
  12932. ServerUpDownTest() : cli_(HOST, PORT) {}
  12933. virtual void SetUp() {
  12934. t_ = thread([&]() {
  12935. svr_.bind_to_any_port(HOST);
  12936. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12937. ASSERT_TRUE(svr_.listen_after_bind());
  12938. });
  12939. svr_.wait_until_ready();
  12940. }
  12941. virtual void TearDown() {
  12942. svr_.stop();
  12943. t_.join();
  12944. }
  12945. Client cli_;
  12946. Server svr_;
  12947. thread t_;
  12948. };
  12949. TEST_F(ServerUpDownTest, QuickStartStop) {
  12950. // Should not crash, especially when run with
  12951. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12952. }
  12953. class PayloadMaxLengthTest : public ::testing::Test {
  12954. protected:
  12955. PayloadMaxLengthTest()
  12956. : cli_(HOST, PORT)
  12957. #ifdef CPPHTTPLIB_SSL_ENABLED
  12958. ,
  12959. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12960. #endif
  12961. {
  12962. #ifdef CPPHTTPLIB_SSL_ENABLED
  12963. cli_.enable_server_certificate_verification(false);
  12964. #endif
  12965. }
  12966. virtual void SetUp() {
  12967. svr_.set_payload_max_length(8);
  12968. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12969. res.set_content("test", "text/plain");
  12970. });
  12971. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12972. svr_.wait_until_ready();
  12973. }
  12974. virtual void TearDown() {
  12975. svr_.stop();
  12976. t_.join();
  12977. }
  12978. #ifdef CPPHTTPLIB_SSL_ENABLED
  12979. SSLClient cli_;
  12980. SSLServer svr_;
  12981. #else
  12982. Client cli_;
  12983. Server svr_;
  12984. #endif
  12985. thread t_;
  12986. };
  12987. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12988. auto res = cli_.Post("/test", "123456789", "text/plain");
  12989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12990. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12991. res = cli_.Post("/test", "12345678", "text/plain");
  12992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12993. EXPECT_EQ(StatusCode::OK_200, res->status);
  12994. }
  12995. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12996. // Test chunked encoding with payload exceeding the 8-byte limit
  12997. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12998. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13000. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13001. }
  13002. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  13003. // Test chunked encoding with payload within the 8-byte limit
  13004. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  13005. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  13006. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13007. EXPECT_EQ(StatusCode::OK_200, res->status);
  13008. }
  13009. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  13010. // Test using send_request to send chunked data exceeding payload limit
  13011. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  13012. "Host: " +
  13013. std::string(HOST) + ":" + std::to_string(PORT) +
  13014. "\r\n"
  13015. "Transfer-Encoding: chunked\r\n"
  13016. "Connection: close\r\n"
  13017. "\r\n"
  13018. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  13019. "0123456789\r\n"
  13020. "0\r\n" // End chunk
  13021. "\r\n";
  13022. std::string response;
  13023. bool result = send_request(1, chunked_request, &response);
  13024. if (!result) {
  13025. // If send_request fails, it might be because the server closed the
  13026. // connection due to payload limit enforcement, which is acceptable
  13027. SUCCEED()
  13028. << "Server rejected oversized chunked request (connection closed)";
  13029. } else {
  13030. // If we got a response, check if it's an error response or connection was
  13031. // closed early Short response length indicates connection was closed due to
  13032. // payload limit
  13033. if (response.length() <= 10) {
  13034. SUCCEED() << "Server closed connection for oversized chunked request";
  13035. } else {
  13036. // Check for error status codes
  13037. EXPECT_TRUE(response.find("413") != std::string::npos ||
  13038. response.find("Payload Too Large") != std::string::npos ||
  13039. response.find("400") != std::string::npos);
  13040. }
  13041. }
  13042. }
  13043. class LargePayloadMaxLengthTest : public ::testing::Test {
  13044. protected:
  13045. LargePayloadMaxLengthTest()
  13046. : cli_(HOST, PORT)
  13047. #ifdef CPPHTTPLIB_SSL_ENABLED
  13048. ,
  13049. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13050. #endif
  13051. {
  13052. #ifdef CPPHTTPLIB_SSL_ENABLED
  13053. cli_.enable_server_certificate_verification(false);
  13054. #endif
  13055. }
  13056. virtual void SetUp() {
  13057. // Set 10MB payload limit
  13058. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13059. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13060. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13061. res.set_content("Large payload test", "text/plain");
  13062. });
  13063. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13064. svr_.wait_until_ready();
  13065. }
  13066. virtual void TearDown() {
  13067. svr_.stop();
  13068. t_.join();
  13069. }
  13070. #ifdef CPPHTTPLIB_SSL_ENABLED
  13071. SSLClient cli_;
  13072. SSLServer svr_;
  13073. #else
  13074. Client cli_;
  13075. Server svr_;
  13076. #endif
  13077. thread t_;
  13078. };
  13079. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13080. // Test chunked encoding with payload within 10MB limit
  13081. std::string medium_payload(5 * 1024 * 1024,
  13082. 'A'); // 5MB payload, within 10MB limit
  13083. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13085. EXPECT_EQ(StatusCode::OK_200, res->status);
  13086. }
  13087. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13088. // Test chunked encoding with payload exceeding 10MB limit
  13089. std::string large_payload(12 * 1024 * 1024,
  13090. 'B'); // 12MB payload, exceeds 10MB limit
  13091. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13092. // Server may either return 413 or close the connection
  13093. if (res) {
  13094. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13095. } else {
  13096. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13097. }
  13098. }
  13099. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13100. Server svr;
  13101. svr.Get("/", [](const Request &, Response &res) {
  13102. // Claims the most the client accepts, far more than it sends, then drops
  13103. // the connection.
  13104. res.set_content_provider(std::string().max_size(), "text/plain",
  13105. [](size_t, size_t, DataSink &sink) {
  13106. sink.write("abc", 3);
  13107. return false;
  13108. });
  13109. });
  13110. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13111. auto se = detail::scope_exit([&] {
  13112. svr.stop();
  13113. thread.join();
  13114. ASSERT_FALSE(svr.is_running());
  13115. });
  13116. svr.wait_until_ready();
  13117. Client cli(HOST, PORT);
  13118. cli.set_payload_max_length(0);
  13119. EXPECT_FALSE(cli.Get("/"));
  13120. }
  13121. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13122. // Stream API does, not as a plain read failure
  13123. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13124. Server svr;
  13125. svr.Get("/big", [](const Request &, Response &res) {
  13126. res.set_content(std::string(100000, 'b'), "text/plain");
  13127. });
  13128. auto port = svr.bind_to_any_port(HOST);
  13129. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13130. auto se = detail::scope_exit([&] {
  13131. svr.stop();
  13132. thread.join();
  13133. });
  13134. svr.wait_until_ready();
  13135. Client cli(HOST, port);
  13136. cli.set_payload_max_length(1000);
  13137. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13138. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13139. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13140. [](const char *, size_t) { return true; });
  13141. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13142. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13143. // Small on the wire, over the limit once decompressed
  13144. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13145. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13146. #endif
  13147. }
  13148. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13149. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13150. // path.
  13151. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13152. Server svr;
  13153. const size_t LIMIT = 64 * 1024; // 64KB
  13154. svr.set_payload_max_length(LIMIT);
  13155. size_t total = 0;
  13156. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13157. const ContentReader &content_reader) {
  13158. content_reader([&](const char * /*data*/, size_t len) {
  13159. total += len;
  13160. return true;
  13161. });
  13162. res.status = 200;
  13163. res.set_content("stream_ok", "text/plain");
  13164. });
  13165. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13166. auto se = detail::scope_exit([&] {
  13167. svr.stop();
  13168. thread.join();
  13169. ASSERT_FALSE(svr.is_running());
  13170. });
  13171. svr.wait_until_ready();
  13172. // Prepare 256KB raw data and gzip-compress it
  13173. std::string raw(256 * 1024, 'A');
  13174. std::string gz;
  13175. {
  13176. z_stream zs{};
  13177. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13178. Z_DEFAULT_STRATEGY);
  13179. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13180. zs.avail_in = static_cast<uInt>(raw.size());
  13181. char outbuf[4096];
  13182. int ret;
  13183. do {
  13184. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13185. zs.avail_out = sizeof(outbuf);
  13186. ret = deflate(&zs, Z_FINISH);
  13187. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13188. } while (ret != Z_STREAM_END);
  13189. deflateEnd(&zs);
  13190. }
  13191. Client cli(HOST, PORT);
  13192. cli.set_connection_timeout(std::chrono::seconds(5));
  13193. Headers headers = {{"Content-Encoding", "gzip"}};
  13194. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13195. "application/octet-stream");
  13196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13197. // Server must reject oversized decompressed payloads with 413.
  13198. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13199. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13200. EXPECT_LE(total, LIMIT);
  13201. }
  13202. #endif
  13203. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13204. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13205. // the payload must be passed through untouched instead of being rejected.
  13206. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13207. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13208. Server svr;
  13209. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13210. res.set_content(body, "image/jpeg");
  13211. res.set_header("Content-Encoding", "UTF-8");
  13212. });
  13213. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13214. res.set_content(body, "image/jpeg");
  13215. res.set_header("Content-Encoding", "identity");
  13216. });
  13217. svr.Post("/echo", [](const Request &req, Response &res) {
  13218. res.set_content(req.body, "image/jpeg");
  13219. });
  13220. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13221. auto se = detail::scope_exit([&] {
  13222. svr.stop();
  13223. t.join();
  13224. ASSERT_FALSE(svr.is_running());
  13225. });
  13226. svr.wait_until_ready();
  13227. Client cli(HOST, PORT);
  13228. {
  13229. auto res = cli.Get("/image");
  13230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13231. EXPECT_EQ(StatusCode::OK_200, res->status);
  13232. EXPECT_EQ(body, res->body);
  13233. }
  13234. {
  13235. auto res = cli.Get("/identity");
  13236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13237. EXPECT_EQ(StatusCode::OK_200, res->status);
  13238. EXPECT_EQ(body, res->body);
  13239. }
  13240. {
  13241. // The same applies to a request body reaching the server.
  13242. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13243. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13245. EXPECT_EQ(StatusCode::OK_200, res->status);
  13246. EXPECT_EQ(body, res->body);
  13247. }
  13248. }
  13249. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13250. // gzip-encoded response even when the build has no zlib support.
  13251. static const char GZIPPED_HELLO_WORLD[] = {
  13252. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13253. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13254. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13255. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13256. // A content coding is a whole token, not something the field value merely
  13257. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13258. // as "fibre" look like Brotli, and turned a multi-coding value like
  13259. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13260. // it was never meant to see.
  13261. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13262. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13263. Server svr;
  13264. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13265. res.set_content(body, "image/jpeg");
  13266. res.set_header("Content-Encoding", "fibre");
  13267. });
  13268. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13269. res.set_content(body, "image/jpeg");
  13270. res.set_header("Content-Encoding", "gzip, br");
  13271. });
  13272. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13273. res.set_content(body, "image/jpeg");
  13274. res.set_header("Content-Encoding", "x-zstd-ish");
  13275. });
  13276. auto port = svr.bind_to_any_port(HOST);
  13277. thread t = thread([&]() { svr.listen_after_bind(); });
  13278. auto se = detail::scope_exit([&] {
  13279. svr.stop();
  13280. t.join();
  13281. ASSERT_FALSE(svr.is_running());
  13282. });
  13283. svr.wait_until_ready();
  13284. Client cli(HOST, port);
  13285. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13286. auto res = cli.Get(path);
  13287. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13288. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13289. // Not a coding we recognize, so the payload comes back untouched
  13290. EXPECT_EQ(body, res->body) << path;
  13291. }
  13292. }
  13293. // A content coding cpp-httplib recognizes but was not built with must be
  13294. // reported as such. Handing the still-compressed payload back to the caller
  13295. // would silently corrupt it.
  13296. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13297. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13298. Server svr;
  13299. // "image/jpeg" keeps the server from applying a content coding of its own,
  13300. // so the hand-crafted Content-Encoding below survives.
  13301. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13302. res.set_content(gzipped, "image/jpeg");
  13303. res.set_header("Content-Encoding", "gzip");
  13304. });
  13305. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13306. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13307. res.set_content(gzipped, "image/jpeg");
  13308. res.set_header("Content-Encoding", "GZIP");
  13309. });
  13310. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13311. auto se = detail::scope_exit([&] {
  13312. svr.stop();
  13313. t.join();
  13314. ASSERT_FALSE(svr.is_running());
  13315. });
  13316. svr.wait_until_ready();
  13317. Client cli(HOST, PORT);
  13318. {
  13319. auto res = cli.Get("/gzipped");
  13320. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13322. EXPECT_EQ("Hello World!", res->body);
  13323. #else
  13324. ASSERT_FALSE(res);
  13325. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13326. #endif
  13327. }
  13328. {
  13329. // open_stream() must behave the same way.
  13330. auto handle = cli.open_stream("GET", "/gzipped");
  13331. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13332. ASSERT_TRUE(handle.is_valid());
  13333. std::string received;
  13334. char buf[256];
  13335. ssize_t n;
  13336. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13337. received.append(buf, static_cast<size_t>(n));
  13338. }
  13339. EXPECT_EQ("Hello World!", received);
  13340. #else
  13341. EXPECT_FALSE(handle.is_valid());
  13342. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13343. #endif
  13344. }
  13345. {
  13346. // A differently-cased coding must not be mistaken for an unknown one, or
  13347. // the body would be handed back still compressed.
  13348. auto res = cli.Get("/gzipped-uppercase");
  13349. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13351. EXPECT_EQ("Hello World!", res->body);
  13352. #else
  13353. ASSERT_FALSE(res);
  13354. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13355. #endif
  13356. }
  13357. }
  13358. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13359. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13360. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13361. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13362. // body a second time and appending a second Content-Encoding field line, so
  13363. // clients that decode one coding per listed value handed back raw gzip bytes.
  13364. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13365. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13366. Server svr;
  13367. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13368. // keeps the server from applying a coding of its own.
  13369. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13370. res.set_content(gzipped, "text/plain");
  13371. res.set_header("Content-Encoding", "gzip");
  13372. });
  13373. auto port = svr.bind_to_any_port(HOST);
  13374. thread t = thread([&]() { svr.listen_after_bind(); });
  13375. auto se = detail::scope_exit([&] {
  13376. svr.stop();
  13377. t.join();
  13378. ASSERT_FALSE(svr.is_running());
  13379. });
  13380. svr.wait_until_ready();
  13381. Client cli(HOST, port);
  13382. Headers headers = {{"Accept-Encoding", "gzip"}};
  13383. auto res = cli.Get("/pre-gzipped", headers);
  13384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13385. EXPECT_EQ(StatusCode::OK_200, res->status);
  13386. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13387. EXPECT_EQ("Hello World!", res->body);
  13388. }
  13389. // set_compress(false) sends every handler response as it is, buffered or
  13390. // streamed
  13391. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13392. const std::string text(1000, 'a');
  13393. Server svr;
  13394. svr.set_compress(false);
  13395. svr.Get("/buffered", [&](const Request &, Response &res) {
  13396. res.set_content(text, "text/plain");
  13397. });
  13398. svr.Get("/streamed", [&](const Request &, Response &res) {
  13399. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13400. sink.write(text.data(), text.size());
  13401. sink.done();
  13402. return true;
  13403. });
  13404. });
  13405. auto port = svr.bind_to_any_port(HOST);
  13406. ASSERT_LT(0, port);
  13407. thread t = thread([&] { svr.listen_after_bind(); });
  13408. auto se = detail::scope_exit([&] {
  13409. svr.stop();
  13410. t.join();
  13411. ASSERT_FALSE(svr.is_running());
  13412. });
  13413. svr.wait_until_ready();
  13414. Client cli(HOST, port);
  13415. cli.set_decompress(false);
  13416. for (auto path : {"/buffered", "/streamed"}) {
  13417. SCOPED_TRACE(path);
  13418. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13420. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13421. EXPECT_EQ(text, res->body);
  13422. }
  13423. }
  13424. // A chunked provider settles its coding where the headers are written and
  13425. // reuses it at write time. Both ends of that have to hold: a handler's own
  13426. // Content-Encoding suppresses the coding, and a response without one is still
  13427. // compressed as it always was.
  13428. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13429. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13430. const std::string plain = "Hello World! Hello World! Hello World!";
  13431. Server svr;
  13432. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13433. res.set_header("Content-Encoding", "gzip");
  13434. res.set_chunked_content_provider(
  13435. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13436. sink.write(gzipped.data(), gzipped.size());
  13437. sink.done();
  13438. return true;
  13439. });
  13440. });
  13441. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13442. res.set_chunked_content_provider(
  13443. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13444. sink.write(plain.data(), plain.size());
  13445. sink.done();
  13446. return true;
  13447. });
  13448. });
  13449. auto port = svr.bind_to_any_port(HOST);
  13450. thread t = thread([&]() { svr.listen_after_bind(); });
  13451. auto se = detail::scope_exit([&] {
  13452. svr.stop();
  13453. t.join();
  13454. ASSERT_FALSE(svr.is_running());
  13455. });
  13456. svr.wait_until_ready();
  13457. Client cli(HOST, port);
  13458. Headers headers = {{"Accept-Encoding", "gzip"}};
  13459. {
  13460. auto res = cli.Get("/pre-gzipped", headers);
  13461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13462. EXPECT_EQ(StatusCode::OK_200, res->status);
  13463. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13464. EXPECT_EQ("Hello World!", res->body);
  13465. }
  13466. {
  13467. auto res = cli.Get("/negotiated", headers);
  13468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13469. EXPECT_EQ(StatusCode::OK_200, res->status);
  13470. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13471. EXPECT_EQ(plain, res->body);
  13472. }
  13473. }
  13474. #endif
  13475. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13476. // the same message as the comma-joined one, so both have to be read the same
  13477. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13478. // single gzip coding, and a body the sender says was encoded twice was handed
  13479. // back after one pass, still compressed but presented as decoded.
  13480. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13481. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13482. Server svr;
  13483. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13484. res.set_content(body, "image/jpeg");
  13485. res.headers.emplace("Content-Encoding", "gzip");
  13486. res.headers.emplace("Content-Encoding", "gzip");
  13487. });
  13488. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13489. res.set_content(body, "image/jpeg");
  13490. res.set_header("Content-Encoding", "gzip, gzip");
  13491. });
  13492. auto port = svr.bind_to_any_port(HOST);
  13493. thread t = thread([&]() { svr.listen_after_bind(); });
  13494. auto se = detail::scope_exit([&] {
  13495. svr.stop();
  13496. t.join();
  13497. ASSERT_FALSE(svr.is_running());
  13498. });
  13499. svr.wait_until_ready();
  13500. Client cli(HOST, port);
  13501. // Two codings is not something cpp-httplib decodes, so both representations
  13502. // take the pass-through path rather than one of them being gunzipped once.
  13503. for (const char *path : {"/split", "/joined"}) {
  13504. auto res = cli.Get(path);
  13505. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13506. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13507. EXPECT_EQ(body, res->body) << path;
  13508. }
  13509. }
  13510. // Regression test for DoS vulnerability: a malicious server sending a response
  13511. // without Content-Length header must not cause unbounded memory consumption on
  13512. // the client side. The client should stop reading after a reasonable limit,
  13513. // similar to the server-side set_payload_max_length protection.
  13514. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13515. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13516. #ifndef _WIN32
  13517. signal(SIGPIPE, SIG_IGN);
  13518. #endif
  13519. auto server_thread = std::thread([] {
  13520. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13521. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13522. default_socket_options(srv);
  13523. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13524. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13525. sockaddr_in addr{};
  13526. addr.sin_family = AF_INET;
  13527. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13528. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13529. int opt = 1;
  13530. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13531. #ifdef _WIN32
  13532. reinterpret_cast<const char *>(&opt),
  13533. #else
  13534. &opt,
  13535. #endif
  13536. sizeof(opt));
  13537. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13538. ::listen(srv, 1);
  13539. sockaddr_in cli_addr{};
  13540. socklen_t cli_len = sizeof(cli_addr);
  13541. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13542. if (cli != INVALID_SOCKET) {
  13543. char buf[4096];
  13544. ::recv(cli, buf, sizeof(buf), 0);
  13545. // Malicious response: no Content-Length, no chunked encoding
  13546. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13547. "Connection: close\r\n"
  13548. "\r\n";
  13549. ::send(cli,
  13550. #ifdef _WIN32
  13551. static_cast<const char *>(response_header.c_str()),
  13552. static_cast<int>(response_header.size()),
  13553. #else
  13554. response_header.c_str(), response_header.size(),
  13555. #endif
  13556. 0);
  13557. // Send 10MB of data
  13558. std::string chunk(64 * 1024, 'A');
  13559. size_t total_sent = 0;
  13560. while (total_sent < MALICIOUS_DATA_SIZE) {
  13561. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13562. auto sent = ::send(cli,
  13563. #ifdef _WIN32
  13564. static_cast<const char *>(chunk.c_str()),
  13565. static_cast<int>(to_send),
  13566. #else
  13567. chunk.c_str(), to_send,
  13568. #endif
  13569. 0);
  13570. if (sent <= 0) break;
  13571. total_sent += static_cast<size_t>(sent);
  13572. }
  13573. detail::close_socket(cli);
  13574. }
  13575. detail::close_socket(srv);
  13576. });
  13577. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13578. size_t total_read = 0;
  13579. {
  13580. Client cli("127.0.0.1", PORT + 2);
  13581. cli.set_read_timeout(5, 0);
  13582. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13583. auto stream = cli.open_stream("GET", "/malicious");
  13584. ASSERT_TRUE(stream.is_valid());
  13585. char buffer[64 * 1024];
  13586. ssize_t n;
  13587. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13588. total_read += static_cast<size_t>(n);
  13589. }
  13590. } // StreamHandle and Client destroyed here, closing the socket
  13591. server_thread.join();
  13592. // With set_payload_max_length, the client must stop reading before consuming
  13593. // all 10MB. The read loop should be cut off at or near the configured limit.
  13594. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13595. << "Client read " << total_read << " bytes, exceeding the configured "
  13596. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13597. }
  13598. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13599. // the entire response body without truncation.
  13600. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13601. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13602. #ifndef _WIN32
  13603. signal(SIGPIPE, SIG_IGN);
  13604. #endif
  13605. auto server_thread = std::thread([] {
  13606. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13607. default_socket_options(srv);
  13608. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13609. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13610. sockaddr_in addr{};
  13611. addr.sin_family = AF_INET;
  13612. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13613. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13614. int opt = 1;
  13615. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13616. #ifdef _WIN32
  13617. reinterpret_cast<const char *>(&opt),
  13618. #else
  13619. &opt,
  13620. #endif
  13621. sizeof(opt));
  13622. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13623. ::listen(srv, 1);
  13624. sockaddr_in cli_addr{};
  13625. socklen_t cli_len = sizeof(cli_addr);
  13626. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13627. if (cli != INVALID_SOCKET) {
  13628. char buf[4096];
  13629. ::recv(cli, buf, sizeof(buf), 0);
  13630. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13631. "Connection: close\r\n"
  13632. "\r\n";
  13633. ::send(cli,
  13634. #ifdef _WIN32
  13635. static_cast<const char *>(response_header.c_str()),
  13636. static_cast<int>(response_header.size()),
  13637. #else
  13638. response_header.c_str(), response_header.size(),
  13639. #endif
  13640. 0);
  13641. std::string chunk(64 * 1024, 'A');
  13642. size_t total_sent = 0;
  13643. while (total_sent < DATA_SIZE) {
  13644. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13645. auto sent = ::send(cli,
  13646. #ifdef _WIN32
  13647. static_cast<const char *>(chunk.c_str()),
  13648. static_cast<int>(to_send),
  13649. #else
  13650. chunk.c_str(), to_send,
  13651. #endif
  13652. 0);
  13653. if (sent <= 0) break;
  13654. total_sent += static_cast<size_t>(sent);
  13655. }
  13656. #ifdef _WIN32
  13657. ::shutdown(cli, SD_SEND);
  13658. #else
  13659. ::shutdown(cli, SHUT_WR);
  13660. #endif
  13661. // Drain until the client closes its end, ensuring all data is delivered
  13662. char drain[1024];
  13663. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13664. detail::close_socket(cli);
  13665. }
  13666. detail::close_socket(srv);
  13667. });
  13668. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13669. size_t total_read = 0;
  13670. {
  13671. Client cli("127.0.0.1", PORT + 2);
  13672. cli.set_read_timeout(5, 0);
  13673. cli.set_payload_max_length(0); // 0 means no limit
  13674. auto stream = cli.open_stream("GET", "/data");
  13675. ASSERT_TRUE(stream.is_valid());
  13676. char buffer[64 * 1024];
  13677. ssize_t n;
  13678. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13679. total_read += static_cast<size_t>(n);
  13680. }
  13681. }
  13682. server_thread.join();
  13683. EXPECT_EQ(total_read, DATA_SIZE)
  13684. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13685. << " bytes without truncation, but only read " << total_read << " bytes.";
  13686. }
  13687. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13688. // enormous Content-Length must not cause the client to pre-allocate a huge
  13689. // response body buffer. The reservation is capped at payload_max_length_, and
  13690. // the read itself fails when the body exceeds the limit.
  13691. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13692. #ifndef _WIN32
  13693. signal(SIGPIPE, SIG_IGN);
  13694. #endif
  13695. auto server_thread = std::thread([] {
  13696. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13697. default_socket_options(srv);
  13698. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13699. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13700. sockaddr_in addr{};
  13701. addr.sin_family = AF_INET;
  13702. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13703. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13704. int opt = 1;
  13705. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13706. #ifdef _WIN32
  13707. reinterpret_cast<const char *>(&opt),
  13708. #else
  13709. &opt,
  13710. #endif
  13711. sizeof(opt));
  13712. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13713. ::listen(srv, 1);
  13714. sockaddr_in cli_addr{};
  13715. socklen_t cli_len = sizeof(cli_addr);
  13716. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13717. if (cli != INVALID_SOCKET) {
  13718. char buf[4096];
  13719. ::recv(cli, buf, sizeof(buf), 0);
  13720. // Malicious response: claim a 20GB body but send only a tiny payload.
  13721. std::string response = "HTTP/1.1 200 OK\r\n"
  13722. "Content-Length: 20000000000\r\n"
  13723. "\r\n"
  13724. "abc";
  13725. ::send(cli,
  13726. #ifdef _WIN32
  13727. static_cast<const char *>(response.c_str()),
  13728. static_cast<int>(response.size()),
  13729. #else
  13730. response.c_str(), response.size(),
  13731. #endif
  13732. 0);
  13733. detail::close_socket(cli);
  13734. }
  13735. detail::close_socket(srv);
  13736. });
  13737. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13738. {
  13739. Client cli("127.0.0.1", PORT + 2);
  13740. cli.set_read_timeout(5, 0);
  13741. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13742. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13743. // (server claims more bytes than payload_max_length permits), but it must
  13744. // not exhaust memory before getting there.
  13745. auto res = cli.Get("/malicious");
  13746. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13747. }
  13748. server_thread.join();
  13749. }
  13750. // Verify that content_receiver bypasses the default payload_max_length,
  13751. // allowing streaming downloads larger than 100MB without requiring an explicit
  13752. // set_payload_max_length call.
  13753. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13754. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13755. #ifndef _WIN32
  13756. signal(SIGPIPE, SIG_IGN);
  13757. #endif
  13758. auto server_thread = std::thread([] {
  13759. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13760. default_socket_options(srv);
  13761. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13762. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13763. sockaddr_in addr{};
  13764. addr.sin_family = AF_INET;
  13765. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13766. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13767. int opt = 1;
  13768. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13769. #ifdef _WIN32
  13770. reinterpret_cast<const char *>(&opt),
  13771. #else
  13772. &opt,
  13773. #endif
  13774. sizeof(opt));
  13775. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13776. ::listen(srv, 1);
  13777. sockaddr_in cli_addr{};
  13778. socklen_t cli_len = sizeof(cli_addr);
  13779. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13780. if (cli != INVALID_SOCKET) {
  13781. char buf[4096];
  13782. ::recv(cli, buf, sizeof(buf), 0);
  13783. // Response with Content-Length larger than default 100MB limit
  13784. auto content_length = std::to_string(DATA_SIZE);
  13785. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13786. "Content-Length: " +
  13787. content_length +
  13788. "\r\n"
  13789. "Connection: close\r\n"
  13790. "\r\n";
  13791. ::send(cli,
  13792. #ifdef _WIN32
  13793. static_cast<const char *>(response_header.c_str()),
  13794. static_cast<int>(response_header.size()),
  13795. #else
  13796. response_header.c_str(), response_header.size(),
  13797. #endif
  13798. 0);
  13799. std::string chunk(64 * 1024, 'A');
  13800. size_t total_sent = 0;
  13801. while (total_sent < DATA_SIZE) {
  13802. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13803. auto sent = ::send(cli,
  13804. #ifdef _WIN32
  13805. static_cast<const char *>(chunk.c_str()),
  13806. static_cast<int>(to_send),
  13807. #else
  13808. chunk.c_str(), to_send,
  13809. #endif
  13810. 0);
  13811. if (sent <= 0) break;
  13812. total_sent += static_cast<size_t>(sent);
  13813. }
  13814. detail::close_socket(cli);
  13815. }
  13816. detail::close_socket(srv);
  13817. });
  13818. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13819. size_t total_received = 0;
  13820. {
  13821. Client cli("127.0.0.1", PORT + 2);
  13822. cli.set_read_timeout(10, 0);
  13823. // Do NOT call set_payload_max_length — use the default 100MB limit
  13824. auto res =
  13825. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13826. total_received += data_length;
  13827. return true;
  13828. });
  13829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13830. EXPECT_EQ(StatusCode::OK_200, res->status);
  13831. }
  13832. server_thread.join();
  13833. EXPECT_EQ(total_received, DATA_SIZE)
  13834. << "With content_receiver, the client should read all " << DATA_SIZE
  13835. << " bytes despite the default 100MB payload_max_length, but only read "
  13836. << total_received << " bytes.";
  13837. }
  13838. // Verify that an explicit set_payload_max_length smaller than the response is
  13839. // enforced even when a content_receiver is used.
  13840. TEST(ClientVulnerabilityTest,
  13841. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13842. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13843. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13844. #ifndef _WIN32
  13845. signal(SIGPIPE, SIG_IGN);
  13846. #endif
  13847. auto server_thread = std::thread([] {
  13848. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13849. default_socket_options(srv);
  13850. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13851. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13852. sockaddr_in addr{};
  13853. addr.sin_family = AF_INET;
  13854. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13855. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13856. int opt = 1;
  13857. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13858. #ifdef _WIN32
  13859. reinterpret_cast<const char *>(&opt),
  13860. #else
  13861. &opt,
  13862. #endif
  13863. sizeof(opt));
  13864. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13865. ::listen(srv, 1);
  13866. sockaddr_in cli_addr{};
  13867. socklen_t cli_len = sizeof(cli_addr);
  13868. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13869. if (cli != INVALID_SOCKET) {
  13870. char buf[4096];
  13871. ::recv(cli, buf, sizeof(buf), 0);
  13872. auto content_length = std::to_string(DATA_SIZE);
  13873. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13874. "Content-Length: " +
  13875. content_length +
  13876. "\r\n"
  13877. "Connection: close\r\n"
  13878. "\r\n";
  13879. ::send(cli,
  13880. #ifdef _WIN32
  13881. static_cast<const char *>(response_header.c_str()),
  13882. static_cast<int>(response_header.size()),
  13883. #else
  13884. response_header.c_str(), response_header.size(),
  13885. #endif
  13886. 0);
  13887. std::string chunk(64 * 1024, 'A');
  13888. size_t total_sent = 0;
  13889. while (total_sent < DATA_SIZE) {
  13890. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13891. auto sent = ::send(cli,
  13892. #ifdef _WIN32
  13893. static_cast<const char *>(chunk.c_str()),
  13894. static_cast<int>(to_send),
  13895. #else
  13896. chunk.c_str(), to_send,
  13897. #endif
  13898. 0);
  13899. if (sent <= 0) break;
  13900. total_sent += static_cast<size_t>(sent);
  13901. }
  13902. detail::close_socket(cli);
  13903. }
  13904. detail::close_socket(srv);
  13905. });
  13906. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13907. size_t total_received = 0;
  13908. {
  13909. Client cli("127.0.0.1", PORT + 2);
  13910. cli.set_read_timeout(10, 0);
  13911. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13912. auto res =
  13913. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13914. total_received += data_length;
  13915. return true;
  13916. });
  13917. // Should fail because 200MB exceeds the explicit 150MB limit
  13918. EXPECT_FALSE(res);
  13919. }
  13920. server_thread.join();
  13921. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13922. << "Client with content_receiver should respect the explicit "
  13923. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13924. << total_received << " bytes.";
  13925. }
  13926. // Verify that an explicit set_payload_max_length larger than the response
  13927. // allows the content_receiver to read all data successfully.
  13928. TEST(ClientVulnerabilityTest,
  13929. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13930. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13931. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13932. #ifndef _WIN32
  13933. signal(SIGPIPE, SIG_IGN);
  13934. #endif
  13935. auto server_thread = std::thread([] {
  13936. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13937. default_socket_options(srv);
  13938. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13939. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13940. sockaddr_in addr{};
  13941. addr.sin_family = AF_INET;
  13942. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13943. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13944. int opt = 1;
  13945. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13946. #ifdef _WIN32
  13947. reinterpret_cast<const char *>(&opt),
  13948. #else
  13949. &opt,
  13950. #endif
  13951. sizeof(opt));
  13952. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13953. ::listen(srv, 1);
  13954. sockaddr_in cli_addr{};
  13955. socklen_t cli_len = sizeof(cli_addr);
  13956. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13957. if (cli != INVALID_SOCKET) {
  13958. char buf[4096];
  13959. ::recv(cli, buf, sizeof(buf), 0);
  13960. auto content_length = std::to_string(DATA_SIZE);
  13961. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13962. "Content-Length: " +
  13963. content_length +
  13964. "\r\n"
  13965. "Connection: close\r\n"
  13966. "\r\n";
  13967. ::send(cli,
  13968. #ifdef _WIN32
  13969. static_cast<const char *>(response_header.c_str()),
  13970. static_cast<int>(response_header.size()),
  13971. #else
  13972. response_header.c_str(), response_header.size(),
  13973. #endif
  13974. 0);
  13975. std::string chunk(64 * 1024, 'A');
  13976. size_t total_sent = 0;
  13977. while (total_sent < DATA_SIZE) {
  13978. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13979. auto sent = ::send(cli,
  13980. #ifdef _WIN32
  13981. static_cast<const char *>(chunk.c_str()),
  13982. static_cast<int>(to_send),
  13983. #else
  13984. chunk.c_str(), to_send,
  13985. #endif
  13986. 0);
  13987. if (sent <= 0) break;
  13988. total_sent += static_cast<size_t>(sent);
  13989. }
  13990. #ifdef _WIN32
  13991. ::shutdown(cli, SD_SEND);
  13992. #else
  13993. ::shutdown(cli, SHUT_WR);
  13994. #endif
  13995. char drain[1024];
  13996. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13997. detail::close_socket(cli);
  13998. }
  13999. detail::close_socket(srv);
  14000. });
  14001. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14002. size_t total_received = 0;
  14003. {
  14004. Client cli("127.0.0.1", PORT + 2);
  14005. cli.set_read_timeout(10, 0);
  14006. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  14007. auto res =
  14008. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14009. total_received += data_length;
  14010. return true;
  14011. });
  14012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14013. EXPECT_EQ(StatusCode::OK_200, res->status);
  14014. }
  14015. server_thread.join();
  14016. EXPECT_EQ(total_received, DATA_SIZE)
  14017. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  14018. << " bytes (larger than " << DATA_SIZE
  14019. << " bytes response), content_receiver should read all data, but only "
  14020. "read "
  14021. << total_received << " bytes.";
  14022. }
  14023. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  14024. // Regression test for "zip bomb" attack on the client side: a malicious server
  14025. // sends a small gzip-compressed response that decompresses to a huge payload.
  14026. // The client must enforce payload_max_length on the decompressed size.
  14027. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  14028. constexpr size_t DECOMPRESSED_SIZE =
  14029. 10 * 1024 * 1024; // 10MB after decompression
  14030. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  14031. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  14032. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  14033. std::string compressed;
  14034. {
  14035. httplib::detail::gzip_compressor compressor;
  14036. bool ok =
  14037. compressor.compress(uncompressed.data(), uncompressed.size(),
  14038. /*last=*/true, [&](const char *buf, size_t len) {
  14039. compressed.append(buf, len);
  14040. return true;
  14041. });
  14042. ASSERT_TRUE(ok);
  14043. }
  14044. // Sanity: compressed data should be much smaller than the decompressed size
  14045. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  14046. #ifndef _WIN32
  14047. signal(SIGPIPE, SIG_IGN);
  14048. #endif
  14049. // Set up the listening socket in the main thread so the server is guaranteed
  14050. // to be ready before the client connects (eliminates race condition).
  14051. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14052. default_socket_options(srv);
  14053. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14054. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14055. sockaddr_in addr{};
  14056. addr.sin_family = AF_INET;
  14057. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14058. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14059. int opt = 1;
  14060. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14061. #ifdef _WIN32
  14062. reinterpret_cast<const char *>(&opt),
  14063. #else
  14064. &opt,
  14065. #endif
  14066. sizeof(opt));
  14067. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14068. ASSERT_EQ(0, ::listen(srv, 1));
  14069. auto server_thread = std::thread([&compressed, srv] {
  14070. sockaddr_in cli_addr{};
  14071. socklen_t cli_len = sizeof(cli_addr);
  14072. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14073. if (cli != INVALID_SOCKET) {
  14074. // Read the full HTTP request (until \r\n\r\n)
  14075. char buf[4096];
  14076. size_t total = 0;
  14077. while (total < sizeof(buf)) {
  14078. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14079. if (n <= 0) break;
  14080. total += static_cast<size_t>(n);
  14081. // Check for end of headers
  14082. if (total >= 4) {
  14083. std::string req(buf, total);
  14084. if (req.find("\r\n\r\n") != std::string::npos) break;
  14085. }
  14086. }
  14087. // Malicious response: gzip-compressed body, no Content-Length
  14088. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14089. "Content-Encoding: gzip\r\n"
  14090. "Connection: close\r\n"
  14091. "\r\n";
  14092. ::send(cli,
  14093. #ifdef _WIN32
  14094. static_cast<const char *>(response_header.c_str()),
  14095. static_cast<int>(response_header.size()),
  14096. #else
  14097. response_header.c_str(), response_header.size(),
  14098. #endif
  14099. 0);
  14100. // Send the compressed payload (small on the wire, huge when decompressed)
  14101. size_t total_sent = 0;
  14102. while (total_sent < compressed.size()) {
  14103. auto to_send = std::min(compressed.size() - total_sent,
  14104. static_cast<size_t>(64 * 1024));
  14105. auto sent =
  14106. ::send(cli,
  14107. #ifdef _WIN32
  14108. static_cast<const char *>(compressed.c_str() + total_sent),
  14109. static_cast<int>(to_send),
  14110. #else
  14111. compressed.c_str() + total_sent, to_send,
  14112. #endif
  14113. 0);
  14114. if (sent <= 0) break;
  14115. total_sent += static_cast<size_t>(sent);
  14116. }
  14117. detail::close_socket(cli);
  14118. }
  14119. });
  14120. auto se = detail::scope_exit([&] {
  14121. detail::close_socket(srv);
  14122. server_thread.join();
  14123. });
  14124. size_t total_decompressed = 0;
  14125. {
  14126. Client cli("127.0.0.1", PORT + 3);
  14127. cli.set_read_timeout(5, 0);
  14128. cli.set_decompress(true);
  14129. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14130. auto stream = cli.open_stream("GET", "/zipbomb");
  14131. ASSERT_TRUE(stream.is_valid());
  14132. char buffer[64 * 1024];
  14133. ssize_t n;
  14134. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14135. total_decompressed += static_cast<size_t>(n);
  14136. }
  14137. }
  14138. // The decompressed size must be capped by payload_max_length. Without
  14139. // protection, the client would decompress the full 10MB from a tiny
  14140. // compressed payload, enabling a zip bomb DoS attack.
  14141. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14142. << "Client decompressed " << total_decompressed
  14143. << " bytes from a gzip response. The decompressed size should be "
  14144. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14145. }
  14146. #endif
  14147. TEST(HostAndPortPropertiesTest, NoSSL) {
  14148. httplib::Client cli("www.google.com", 1234);
  14149. ASSERT_EQ("www.google.com", cli.host());
  14150. ASSERT_EQ(1234, cli.port());
  14151. }
  14152. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14153. httplib::Client cli("www.google.com:1234");
  14154. ASSERT_EQ("www.google.com", cli.host());
  14155. ASSERT_EQ(1234, cli.port());
  14156. }
  14157. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14158. // Port number that overflows int — should not crash, client becomes invalid
  14159. httplib::Client cli("http://www.google.com:99999999999999999999");
  14160. ASSERT_FALSE(cli.is_valid());
  14161. }
  14162. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14163. // Port 99999 exceeds valid range (1-65535) — should not crash
  14164. httplib::Client cli("http://www.google.com:99999");
  14165. ASSERT_FALSE(cli.is_valid());
  14166. auto res = cli.Get("/");
  14167. EXPECT_FALSE(res);
  14168. EXPECT_EQ(Error::Connection, res.error());
  14169. }
  14170. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14171. httplib::Client cli("http://user:pass@localhost:1234");
  14172. ASSERT_FALSE(cli.is_valid());
  14173. EXPECT_FALSE(cli.Get("/"));
  14174. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14175. }
  14176. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14177. httplib::Client cli("http://www.google.com:80abc");
  14178. ASSERT_FALSE(cli.is_valid());
  14179. }
  14180. #ifdef CPPHTTPLIB_SSL_ENABLED
  14181. TEST(HostAndPortPropertiesTest, SSL) {
  14182. httplib::SSLClient cli("www.google.com");
  14183. ASSERT_EQ("www.google.com", cli.host());
  14184. ASSERT_EQ(443, cli.port());
  14185. }
  14186. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14187. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14188. std::string cert;
  14189. read_file(CA_CERT_FILE, cert);
  14190. httplib::SSLClient httplib_client("www.google.com");
  14191. // Load CA store first time
  14192. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14193. // Load CA store second time (update)
  14194. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14195. // Verify client is still valid and can make connections
  14196. httplib_client.enable_server_certificate_verification(true);
  14197. auto res = httplib_client.Get("/");
  14198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14199. // Google may return 200 or 301 depending on various factors
  14200. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  14201. res->status == StatusCode::MovedPermanently_301);
  14202. }
  14203. TEST(SSLClientTest, ServerNameIndication_Online) {
  14204. auto host = "httpbingo.org";
  14205. auto path = std::string{"/get"};
  14206. SSLClient cli(host, 443);
  14207. auto res = retry_gateway_errors([&] { return cli.Get(path); });
  14208. SKIP_ON_GATEWAY_ERROR(res);
  14209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14210. ASSERT_EQ(StatusCode::OK_200, res->status);
  14211. }
  14212. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14213. // Use a site that will cause SSL verification failure due to self-signed cert
  14214. SSLClient cli("self-signed.badssl.com", 443);
  14215. cli.enable_server_certificate_verification(true);
  14216. auto res = cli.Get("/");
  14217. ASSERT_TRUE(!res);
  14218. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14219. // Verify backend error is captured for SSLServerVerification
  14220. // This occurs when certificate verification fails
  14221. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14222. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14223. EXPECT_NE(0UL, res.ssl_backend_error());
  14224. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14225. res.ssl_error());
  14226. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14227. #if !defined(_WIN32) || \
  14228. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14229. // On non-Windows or when Windows Schannel is disabled, the error comes
  14230. // from OpenSSL's verification
  14231. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14232. res.ssl_backend_error());
  14233. #endif
  14234. #endif
  14235. }
  14236. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14237. // Use a site where hostname doesn't match the certificate
  14238. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14239. SSLClient cli("wrong.host.badssl.com", 443);
  14240. cli.enable_server_certificate_verification(true);
  14241. cli.enable_server_hostname_verification(true);
  14242. auto res = cli.Get("/");
  14243. ASSERT_TRUE(!res);
  14244. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14245. // Verify backend error is captured for hostname verification failure
  14246. EXPECT_NE(0UL, res.ssl_backend_error());
  14247. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14248. res.ssl_error());
  14249. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14250. #if !defined(_WIN32) || \
  14251. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14252. // On non-Windows or when Windows Schannel is disabled, the error comes
  14253. // from OpenSSL's hostname verification
  14254. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14255. res.ssl_backend_error());
  14256. #endif
  14257. #endif
  14258. }
  14259. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14260. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14261. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14262. SSLClient cli("www.google.com", 443);
  14263. cli.enable_server_certificate_verification(true);
  14264. auto res = cli.Get("/");
  14265. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14266. }
  14267. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14268. SSLClient cli("www.google.com", 443);
  14269. cli.enable_server_certificate_verification(true);
  14270. cli.enable_windows_certificate_verification(false);
  14271. auto res = cli.Get("/");
  14272. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14273. }
  14274. // The server sends an intermediate cross-signed by a root Windows trusts,
  14275. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14276. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14277. SSLClient cli("accounts.spotify.com", 443);
  14278. auto res = cli.Get("/");
  14279. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14280. << " ssl_backend_error=" << res.ssl_backend_error();
  14281. }
  14282. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14283. // policy status, which no backend reports for a self-signed certificate.
  14284. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14285. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14286. ASSERT_TRUE(svr.is_valid());
  14287. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14288. auto se = detail::scope_exit([&] {
  14289. svr.stop();
  14290. t.join();
  14291. ASSERT_FALSE(svr.is_running());
  14292. });
  14293. svr.wait_until_ready();
  14294. SSLClient cli("127.0.0.1", PORT);
  14295. cli.set_connection_timeout(30);
  14296. auto res = cli.Get("/");
  14297. ASSERT_FALSE(res);
  14298. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14299. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14300. }
  14301. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14302. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14303. ASSERT_TRUE(svr.is_valid());
  14304. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14305. auto se = detail::scope_exit([&] {
  14306. svr.stop();
  14307. t.join();
  14308. ASSERT_FALSE(svr.is_running());
  14309. });
  14310. svr.wait_until_ready();
  14311. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14312. {
  14313. ws::WebSocketClient client(url);
  14314. auto res = client.connect();
  14315. ASSERT_FALSE(res);
  14316. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14317. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14318. res.ssl_backend_error());
  14319. }
  14320. {
  14321. ws::WebSocketClient client(url);
  14322. client.enable_windows_certificate_verification(false);
  14323. auto res = client.connect();
  14324. ASSERT_FALSE(res);
  14325. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14326. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14327. res.ssl_backend_error());
  14328. }
  14329. }
  14330. #endif
  14331. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14332. Client cli("https://google.com");
  14333. auto res = cli.Get("/");
  14334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14335. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14336. }
  14337. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14338. SSLClient cli("google.com");
  14339. cli.set_ca_cert_path(CA_CERT_FILE);
  14340. auto res = cli.Get("/");
  14341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14342. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14343. }
  14344. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14345. SSLClient cli("google.com");
  14346. cli.enable_server_certificate_verification(true);
  14347. cli.set_ca_cert_path("hello");
  14348. auto res = cli.Get("/");
  14349. ASSERT_TRUE(!res);
  14350. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14351. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14352. // should be set
  14353. EXPECT_EQ(0, res.ssl_error());
  14354. // Verify backend error is captured for SSLLoadingCerts
  14355. // This error occurs when loading CA certificates fails
  14356. EXPECT_NE(0UL, res.ssl_backend_error());
  14357. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14358. // OpenSSL specific error codes:
  14359. // > openssl errstr 0x80000002
  14360. // error:80000002:system library::No such file or directory
  14361. // > openssl errstr 0xA000126
  14362. // error:0A000126:SSL routines::unexpected eof while reading
  14363. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14364. res.ssl_backend_error() == 0xA000126);
  14365. #endif
  14366. }
  14367. TEST(SSLClientTest, ServerCertificateVerification4) {
  14368. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14369. ASSERT_TRUE(svr.is_valid());
  14370. svr.Get("/test", [&](const Request &, Response &res) {
  14371. res.set_content("test", "text/plain");
  14372. svr.stop();
  14373. ASSERT_TRUE(true);
  14374. });
  14375. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14376. auto se = detail::scope_exit([&] {
  14377. t.join();
  14378. ASSERT_FALSE(svr.is_running());
  14379. });
  14380. svr.wait_until_ready();
  14381. SSLClient cli("127.0.0.1", PORT);
  14382. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14383. cli.enable_server_certificate_verification(true);
  14384. cli.set_connection_timeout(30);
  14385. auto res = cli.Get("/test");
  14386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14387. ASSERT_EQ(StatusCode::OK_200, res->status);
  14388. }
  14389. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14390. std::string cert;
  14391. read_file(CA_CERT_FILE, cert);
  14392. SSLClient cli("google.com");
  14393. cli.load_ca_cert_store(cert.data(), cert.size());
  14394. const auto res = cli.Get("/");
  14395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14396. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14397. }
  14398. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14399. // clang-format off
  14400. static constexpr char cert[] =
  14401. "GlobalSign Root CA\n"
  14402. "==================\n"
  14403. "-----BEGIN CERTIFICATE-----\n"
  14404. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14405. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14406. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14407. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14408. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14409. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14410. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14411. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14412. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14413. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14414. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14415. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14416. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14417. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14418. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14419. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14420. "-----END CERTIFICATE-----\n";
  14421. // clang-format on
  14422. SSLClient cli("google.com");
  14423. cli.load_ca_cert_store(cert, sizeof(cert));
  14424. const auto res = cli.Get("/");
  14425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14426. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14427. }
  14428. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14429. SSLClient cli("www.youtube.com");
  14430. cli.set_ca_cert_path(CA_CERT_FILE);
  14431. cli.enable_server_certificate_verification(true);
  14432. cli.set_follow_location(true);
  14433. auto res = cli.Get("/");
  14434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14435. ASSERT_EQ(StatusCode::OK_200, res->status);
  14436. }
  14437. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14438. SSLClient cli("wWw.YouTube.Com");
  14439. cli.set_ca_cert_path(CA_CERT_FILE);
  14440. cli.enable_server_certificate_verification(true);
  14441. cli.enable_server_hostname_verification(true);
  14442. cli.set_follow_location(true);
  14443. auto res = cli.Get("/");
  14444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14445. ASSERT_EQ(StatusCode::OK_200, res->status);
  14446. }
  14447. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14448. SSLClient cli("gOoGlE.COm");
  14449. cli.enable_server_certificate_verification(true);
  14450. cli.enable_server_hostname_verification(true);
  14451. cli.set_follow_location(true);
  14452. auto res = cli.Get("/");
  14453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14454. ASSERT_EQ(StatusCode::OK_200, res->status);
  14455. }
  14456. TEST(SSLClientTest, Issue2004_Online) {
  14457. Client client("https://google.com");
  14458. client.set_follow_location(true);
  14459. auto res = client.Get("/");
  14460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14461. ASSERT_EQ(StatusCode::OK_200, res->status);
  14462. auto body = res->body;
  14463. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  14464. }
  14465. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14466. // Create SSLClient with invalid cert/key to make is_valid() return false
  14467. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14468. "nonexistent_key.pem");
  14469. // is_valid() should be false due to cert loading failure
  14470. ASSERT_FALSE(cli.is_valid());
  14471. auto res = cli.Get("/");
  14472. ASSERT_FALSE(res);
  14473. EXPECT_EQ(Error::SSLConnection, res.error());
  14474. }
  14475. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14476. // Test for Issue #2251: SSL error not properly reported when client cert
  14477. // and key paths are swapped or mismatched
  14478. // This simulates the scenario where user accidentally swaps the cert and key
  14479. // files
  14480. // Using client cert file as private key and vice versa (completely wrong)
  14481. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14482. // Should fail validation due to cert/key mismatch
  14483. ASSERT_FALSE(cli.is_valid());
  14484. // Attempt to make a request should fail with proper error
  14485. auto res = cli.Get("/");
  14486. ASSERT_FALSE(res);
  14487. EXPECT_EQ(Error::SSLConnection, res.error());
  14488. // SSL error should be recorded in the Result object (this is the key fix for
  14489. // Issue #2251)
  14490. auto backend_error = res.ssl_backend_error();
  14491. EXPECT_NE(0u, backend_error);
  14492. }
  14493. // Tests cert/key mismatch detection at the TLS context level
  14494. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14495. // Test that using mismatched cert/key causes connection failure.
  14496. // We verify this at the SSLClient level rather than through internal
  14497. // TLS API functions.
  14498. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14499. cli.enable_server_certificate_verification(false);
  14500. cli.set_connection_timeout(2);
  14501. // The mismatch should cause a connection or handshake error
  14502. auto res = cli.Get("/test");
  14503. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14504. // Either way, the request should fail
  14505. EXPECT_FALSE(res);
  14506. }
  14507. #endif
  14508. #if 0
  14509. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14510. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14511. ASSERT_TRUE(cli != nullptr);
  14512. cli->set_address_family(AF_INET6);
  14513. cli->set_interface("en0");
  14514. auto res = cli->Get("/get");
  14515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14516. ASSERT_EQ(StatusCode::OK_200, res->status);
  14517. }
  14518. #endif
  14519. // Client certificate tests - work with all TLS backends
  14520. #ifdef CPPHTTPLIB_SSL_ENABLED
  14521. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14522. void ClientCertPresent(
  14523. const std::string &client_cert_file,
  14524. const std::string &client_private_key_file,
  14525. const std::string &client_encrypted_private_key_pass = std::string(),
  14526. const ClientCertServerSetup &setup = nullptr) {
  14527. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14528. ASSERT_TRUE(svr.is_valid());
  14529. if (setup) { setup(svr); }
  14530. svr.Get("/test", [&](const Request &req, Response &res) {
  14531. res.set_content("test", "text/plain");
  14532. auto cert = req.peer_cert();
  14533. ASSERT_TRUE(static_cast<bool>(cert));
  14534. std::string common_name = cert.subject_cn();
  14535. EXPECT_EQ("Common Name", common_name);
  14536. });
  14537. auto port = svr.bind_to_any_port(HOST);
  14538. ASSERT_LT(0, port);
  14539. thread t = thread([&]() { svr.listen_after_bind(); });
  14540. auto se = detail::scope_exit([&] {
  14541. svr.stop();
  14542. t.join();
  14543. ASSERT_FALSE(svr.is_running());
  14544. });
  14545. svr.wait_until_ready();
  14546. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14547. client_encrypted_private_key_pass);
  14548. cli.enable_server_certificate_verification(false);
  14549. cli.set_connection_timeout(30);
  14550. auto res = cli.Get("/test");
  14551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14552. ASSERT_EQ(StatusCode::OK_200, res->status);
  14553. }
  14554. TEST(SSLClientServerTest, ClientCertPresent) {
  14555. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14556. }
  14557. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14558. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14559. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14560. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14561. }
  14562. // Expects svr, which must require client certificates, to reject a client
  14563. // that has none
  14564. void RejectsClientWithoutCert(SSLServer &svr) {
  14565. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14566. auto port = svr.bind_to_any_port(HOST);
  14567. ASSERT_LT(0, port);
  14568. thread t = thread([&]() { svr.listen_after_bind(); });
  14569. auto se = detail::scope_exit([&] {
  14570. svr.stop();
  14571. t.join();
  14572. ASSERT_FALSE(svr.is_running());
  14573. });
  14574. svr.wait_until_ready();
  14575. SSLClient cli(HOST, port);
  14576. cli.set_connection_timeout(30);
  14577. // Skip the server certificate check, so that the request fails because the
  14578. // client certificate is missing rather than because cert.pem is not trusted
  14579. cli.enable_server_certificate_verification(false);
  14580. auto res = cli.Get("/test");
  14581. ASSERT_FALSE(res);
  14582. // The server rejects the client during the handshake, or on TLS 1.3 right
  14583. // after it, which the client notices on its first write or read
  14584. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14585. res.error() == Error::Write || res.error() == Error::Read)
  14586. << to_string(res.error());
  14587. if (res.error() == Error::SSLConnection) {
  14588. EXPECT_NE(0UL, res.ssl_backend_error());
  14589. }
  14590. // A rejection noticed on the write keeps the TLS error the write hit
  14591. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14592. }
  14593. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14594. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14595. ASSERT_TRUE(svr.is_valid());
  14596. if (setup) { setup(svr); }
  14597. RejectsClientWithoutCert(svr);
  14598. }
  14599. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14600. // A server that requires client certificates must keep requiring them after
  14601. // setup changes it, and keep accepting a client that has one
  14602. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14603. ClientCertMissing(setup);
  14604. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14605. setup);
  14606. }
  14607. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14608. ClientCertStillRequired([](SSLServer &svr) {
  14609. ASSERT_TRUE(tls::set_verify_callback(
  14610. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14611. });
  14612. }
  14613. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14614. ClientCertStillRequired([](SSLServer &svr) {
  14615. ASSERT_TRUE(tls::set_verify_callback(
  14616. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14617. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14618. });
  14619. }
  14620. // The client verifies the server certificate during the handshake, so a
  14621. // server that fails the check never gets the client certificate, even when a
  14622. // verifier of the client's own accepts it
  14623. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14624. struct Case {
  14625. const char *trusted_ca;
  14626. const char *host;
  14627. Error error;
  14628. };
  14629. // cert2.pem names localhost: the first client does not trust it, and the
  14630. // second trusts it but asks for another name
  14631. for (const auto &c :
  14632. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14633. Case{SERVER_CERT2_FILE, "example.com",
  14634. Error::SSLServerHostnameVerification}}) {
  14635. for (auto with_verifier : {false, true}) {
  14636. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14637. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14638. CLIENT_CA_CERT_FILE);
  14639. ASSERT_TRUE(svr.is_valid());
  14640. std::atomic<bool> got_client_cert{false};
  14641. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14642. [&](const tls::VerifyContext &) {
  14643. got_client_cert = true;
  14644. return true;
  14645. }));
  14646. auto port = svr.bind_to_any_port("127.0.0.1");
  14647. ASSERT_LT(0, port);
  14648. thread t = thread([&] { svr.listen_after_bind(); });
  14649. svr.wait_until_ready();
  14650. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14651. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14652. cli.set_ca_cert_path(c.trusted_ca);
  14653. if (with_verifier) {
  14654. cli.set_server_certificate_verifier(
  14655. [](const tls::VerifyContext &) { return true; });
  14656. }
  14657. auto res = cli.Get("/");
  14658. EXPECT_FALSE(res);
  14659. EXPECT_EQ(c.error, res.error());
  14660. svr.stop();
  14661. t.join();
  14662. EXPECT_FALSE(got_client_cert);
  14663. }
  14664. }
  14665. }
  14666. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14667. std::string cert_pem, key_pem, ca_pem;
  14668. read_file(SERVER_CERT_FILE, cert_pem);
  14669. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14670. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14671. ASSERT_TRUE(
  14672. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14673. }
  14674. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14675. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14676. ASSERT_TRUE(svr.is_valid());
  14677. UpdateCertsPemWithClientCA(svr);
  14678. RejectsClientWithoutCert(svr);
  14679. }
  14680. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14681. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14682. }
  14683. // A TLS error from one request must not show up in a later request's Result
  14684. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14685. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14686. ASSERT_TRUE(svr.is_valid());
  14687. svr.Get("/test", [](const Request &, Response &res) {
  14688. res.set_content("test", "text/plain");
  14689. });
  14690. auto port = svr.bind_to_any_port(HOST);
  14691. ASSERT_LT(0, port);
  14692. thread t = thread([&]() { svr.listen_after_bind(); });
  14693. auto se = detail::scope_exit([&] {
  14694. svr.stop();
  14695. t.join();
  14696. ASSERT_FALSE(svr.is_running());
  14697. });
  14698. svr.wait_until_ready();
  14699. SSLClient cli(HOST, port);
  14700. cli.set_connection_timeout(30);
  14701. cli.enable_server_hostname_verification(false);
  14702. // cert.pem is not trusted, so the handshake fails
  14703. ASSERT_FALSE(cli.Get("/test"));
  14704. cli.enable_server_certificate_verification(false);
  14705. auto res = cli.Get("/test");
  14706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14707. EXPECT_EQ(0, res.ssl_error());
  14708. EXPECT_EQ(0UL, res.ssl_backend_error());
  14709. }
  14710. // PEM memory-based constructor tests (works with all TLS backends).
  14711. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14712. // terminator after it.
  14713. void PemMemoryClientCertPresent(
  14714. const std::string &client_cert_file,
  14715. const std::string &client_private_key_file,
  14716. const std::string &client_encrypted_private_key_pass = std::string(),
  14717. bool exact_size = false) {
  14718. // Read PEM files into memory
  14719. std::string server_cert_pem, server_key_pem;
  14720. std::string client_ca_pem;
  14721. std::string client_cert_pem, client_key_pem;
  14722. read_file(SERVER_CERT_FILE, server_cert_pem);
  14723. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14724. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14725. read_file(client_cert_file, client_cert_pem);
  14726. read_file(client_private_key_file, client_key_pem);
  14727. std::list<std::vector<char>> exact_copies;
  14728. auto data = [&](const std::string &pem) -> const char * {
  14729. if (!exact_size) { return pem.c_str(); }
  14730. exact_copies.emplace_back(pem.begin(), pem.end());
  14731. return exact_copies.back().data();
  14732. };
  14733. // Create server with PEM memory
  14734. SSLServer::PemMemory server_pem = {
  14735. data(server_cert_pem),
  14736. server_cert_pem.size(),
  14737. data(server_key_pem),
  14738. server_key_pem.size(),
  14739. data(client_ca_pem),
  14740. client_ca_pem.size(),
  14741. nullptr // no password for server key
  14742. };
  14743. SSLServer svr(server_pem);
  14744. ASSERT_TRUE(svr.is_valid());
  14745. svr.Get("/test", [&](const Request &req, Response &res) {
  14746. res.set_content("test", "text/plain");
  14747. auto cert = req.peer_cert();
  14748. ASSERT_TRUE(static_cast<bool>(cert));
  14749. EXPECT_EQ("Common Name", cert.subject_cn());
  14750. });
  14751. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14752. auto se = detail::scope_exit([&] {
  14753. svr.stop();
  14754. t.join();
  14755. ASSERT_FALSE(svr.is_running());
  14756. });
  14757. svr.wait_until_ready();
  14758. // Create client with PEM memory
  14759. const char *password = client_encrypted_private_key_pass.empty()
  14760. ? nullptr
  14761. : client_encrypted_private_key_pass.c_str();
  14762. SSLClient::PemMemory client_pem = {
  14763. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14764. client_key_pem.size(), password};
  14765. SSLClient cli(HOST, PORT, client_pem);
  14766. cli.enable_server_certificate_verification(false);
  14767. cli.set_connection_timeout(30);
  14768. auto res = cli.Get("/test");
  14769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14770. ASSERT_EQ(StatusCode::OK_200, res->status);
  14771. }
  14772. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14773. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14774. }
  14775. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14776. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14777. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14778. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14779. }
  14780. // A server built from PEM memory with a client CA requires client certificates,
  14781. // also when the CA is a NUL-terminated string passed with a length of 0
  14782. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14783. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14784. read_file(SERVER_CERT_FILE, server_cert_pem);
  14785. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14786. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14787. SSLServer::PemMemory server_pem = {
  14788. server_cert_pem.c_str(),
  14789. server_cert_pem.size(),
  14790. server_key_pem.c_str(),
  14791. server_key_pem.size(),
  14792. client_ca_pem.c_str(),
  14793. client_ca_pem.size(),
  14794. nullptr // no password for server key
  14795. };
  14796. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14797. SCOPED_TRACE(client_ca_pem_len);
  14798. server_pem.client_ca_pem_len = client_ca_pem_len;
  14799. SSLServer svr(server_pem);
  14800. ASSERT_TRUE(svr.is_valid());
  14801. RejectsClientWithoutCert(svr);
  14802. }
  14803. // An empty CA fails to load instead of turning the check off
  14804. server_pem.client_ca_pem = "";
  14805. server_pem.client_ca_pem_len = 0;
  14806. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14807. }
  14808. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14809. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14810. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14811. true);
  14812. }
  14813. // A length shorter than the PEM cuts it short, so it no longer loads
  14814. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14815. std::string cert, key;
  14816. read_file(SERVER_CERT_FILE, cert);
  14817. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14818. for (auto cut_cert : {true, false}) {
  14819. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14820. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14821. SSLServer::PemMemory server_pem = {
  14822. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14823. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14824. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14825. key_len, nullptr};
  14826. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14827. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14828. key.c_str(), key_len, nullptr};
  14829. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14830. }
  14831. }
  14832. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14833. class NoListenSSLServer : public SSLServer {
  14834. public:
  14835. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14836. const char *client_ca_cert_file_path,
  14837. const char *client_ca_cert_dir_path = nullptr)
  14838. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14839. client_ca_cert_dir_path),
  14840. stop_(false) {}
  14841. std::atomic_bool stop_;
  14842. private:
  14843. bool process_and_close_socket(socket_t /*sock*/) override {
  14844. // Don't create SSL context
  14845. while (!stop_.load()) {
  14846. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14847. }
  14848. return true;
  14849. }
  14850. };
  14851. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14852. CLIENT_CA_CERT_FILE);
  14853. ASSERT_TRUE(svr.is_valid());
  14854. // Keep-alive parking would bypass the override.
  14855. svr.set_keep_alive_parking(false);
  14856. svr.Get("/test", [&](const Request &, Response &res) {
  14857. res.set_content("test", "text/plain");
  14858. });
  14859. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14860. auto se = detail::scope_exit([&] {
  14861. svr.stop_ = true;
  14862. svr.stop();
  14863. t.join();
  14864. ASSERT_FALSE(svr.is_running());
  14865. });
  14866. svr.wait_until_ready();
  14867. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14868. cli.enable_server_certificate_verification(false);
  14869. cli.set_connection_timeout(1);
  14870. auto res = cli.Get("/test");
  14871. ASSERT_TRUE(!res);
  14872. EXPECT_EQ(Error::SSLConnection, res.error());
  14873. // Timeout results in WantRead error code (maps to backend-specific value)
  14874. EXPECT_NE(0, res.ssl_error());
  14875. }
  14876. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14877. // Test SSLServer with client certificate verification using the standard
  14878. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14879. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14880. CLIENT_CA_CERT_DIR);
  14881. ASSERT_TRUE(svr.is_valid());
  14882. svr.Get("/test", [&](const Request &req, Response &res) {
  14883. res.set_content("test", "text/plain");
  14884. auto cert = req.peer_cert();
  14885. ASSERT_TRUE(static_cast<bool>(cert));
  14886. auto common_name = cert.subject_cn();
  14887. EXPECT_EQ("Common Name", common_name);
  14888. });
  14889. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14890. auto se = detail::scope_exit([&] {
  14891. svr.stop();
  14892. t.join();
  14893. ASSERT_FALSE(svr.is_running());
  14894. });
  14895. svr.wait_until_ready();
  14896. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14897. cli.enable_server_certificate_verification(false);
  14898. cli.set_connection_timeout(30);
  14899. auto res = cli.Get("/test");
  14900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14901. ASSERT_EQ(StatusCode::OK_200, res->status);
  14902. }
  14903. // Test verify_hostname on every backend: a host is named by a SAN only
  14904. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14905. using namespace httplib::tls;
  14906. // We need a running server to test against
  14907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14908. ASSERT_TRUE(svr.is_valid());
  14909. svr.Get("/test", [](const Request &, Response &res) {
  14910. res.set_content("ok", "text/plain");
  14911. });
  14912. thread t([&]() { svr.listen(HOST, PORT); });
  14913. auto se = detail::scope_exit([&] {
  14914. svr.stop();
  14915. t.join();
  14916. });
  14917. svr.wait_until_ready();
  14918. bool verify_callback_called = false;
  14919. bool verify_result_wrong = false;
  14920. SSLClient cli(HOST, PORT);
  14921. cli.enable_server_certificate_verification(true);
  14922. cli.set_ca_cert_path(CA_CERT_FILE);
  14923. cli.set_connection_timeout(5);
  14924. // Note: Test certificate has CN="Common Name", not "localhost"
  14925. bool verify_result_cn = false;
  14926. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14927. verify_callback_called = true;
  14928. if (!ctx.cert) return false;
  14929. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14930. verify_result_cn = ctx.check_hostname("Common Name");
  14931. // Test 2: wrong hostname should not match
  14932. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14933. return true; // Accept for the purpose of this test
  14934. });
  14935. auto res = cli.Get("/test");
  14936. // The request may succeed or fail depending on cert configuration
  14937. // but the callback should have been called
  14938. ASSERT_TRUE(verify_callback_called)
  14939. << "Verify callback should have been called";
  14940. EXPECT_FALSE(verify_result_cn)
  14941. << "verify_hostname must not match the certificate CN (no SAN)";
  14942. // Wrong hostname should not match
  14943. EXPECT_FALSE(verify_result_wrong)
  14944. << "verify_hostname should not match 'wronghost.example.com'";
  14945. }
  14946. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14947. // backend verifies it.
  14948. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14949. // Certificate CN is "localhost" and it carries no SAN.
  14950. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14951. ASSERT_TRUE(svr.is_valid());
  14952. svr.Get("/test", [](const Request &, Response &res) {
  14953. res.set_content("ok", "text/plain");
  14954. });
  14955. auto port = svr.bind_to_any_port(HOST);
  14956. thread t([&]() { svr.listen_after_bind(); });
  14957. auto se = detail::scope_exit([&] {
  14958. svr.stop();
  14959. t.join();
  14960. });
  14961. svr.wait_until_ready();
  14962. SSLClient cli("localhost", port);
  14963. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14964. cli.enable_server_certificate_verification(true);
  14965. cli.set_connection_timeout(5);
  14966. auto res = cli.Get("/test");
  14967. ASSERT_FALSE(res);
  14968. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14969. // The same certificate is accepted once host name verification is off, so the
  14970. // failure above is the host name and not the chain.
  14971. cli.enable_server_hostname_verification(false);
  14972. res = cli.Get("/test");
  14973. ASSERT_TRUE(res) << to_string(res.error());
  14974. EXPECT_EQ(StatusCode::OK_200, res->status);
  14975. }
  14976. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14977. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14978. // X509_check_ip behavior and must hold for every backend.
  14979. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14980. using namespace httplib::tls;
  14981. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14982. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14983. ASSERT_TRUE(svr.is_valid());
  14984. svr.Get("/test", [](const Request &, Response &res) {
  14985. res.set_content("ok", "text/plain");
  14986. });
  14987. thread t([&]() { svr.listen(HOST, PORT); });
  14988. auto se = detail::scope_exit([&] {
  14989. svr.stop();
  14990. t.join();
  14991. });
  14992. svr.wait_until_ready();
  14993. bool verify_callback_called = false;
  14994. bool ip_matched_via_cn = true;
  14995. SSLClient cli(HOST, PORT);
  14996. cli.enable_server_certificate_verification(true);
  14997. cli.set_ca_cert_path(CA_CERT_FILE);
  14998. cli.set_connection_timeout(5);
  14999. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15000. verify_callback_called = true;
  15001. if (!ctx.cert) return false;
  15002. // The IP appears only in the CN, so it must NOT be accepted.
  15003. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  15004. return true; // Accept for the purpose of this test
  15005. });
  15006. cli.Get("/test");
  15007. ASSERT_TRUE(verify_callback_called)
  15008. << "Verify callback should have been called";
  15009. EXPECT_FALSE(ip_matched_via_cn)
  15010. << "An IP host must not be authenticated via the certificate CN";
  15011. }
  15012. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  15013. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  15014. using namespace httplib::tls;
  15015. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  15016. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  15017. ASSERT_TRUE(svr.is_valid());
  15018. svr.Get("/test", [](const Request &, Response &res) {
  15019. res.set_content("ok", "text/plain");
  15020. });
  15021. thread t([&]() { svr.listen(HOST, PORT); });
  15022. auto se = detail::scope_exit([&] {
  15023. svr.stop();
  15024. t.join();
  15025. });
  15026. svr.wait_until_ready();
  15027. bool verify_callback_called = false;
  15028. bool san_matched = false;
  15029. bool wrong_ipv6_matched = true;
  15030. bool cn_ipv6_matched = true;
  15031. SSLClient cli(HOST, PORT);
  15032. cli.enable_server_certificate_verification(true);
  15033. cli.set_ca_cert_path(CA_CERT_FILE);
  15034. cli.set_connection_timeout(5);
  15035. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15036. verify_callback_called = true;
  15037. if (!ctx.cert) return false;
  15038. // Matches the IPv6 iPAddress SAN.
  15039. san_matched = ctx.check_hostname("2001:db8::1");
  15040. // A different IPv6 address must not match.
  15041. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  15042. // "::1" lives only in the CN, so it must not be accepted.
  15043. cn_ipv6_matched = ctx.check_hostname("::1");
  15044. return true; // Accept for the purpose of this test
  15045. });
  15046. cli.Get("/test");
  15047. ASSERT_TRUE(verify_callback_called)
  15048. << "Verify callback should have been called";
  15049. EXPECT_TRUE(san_matched)
  15050. << "verify_hostname should match an IPv6 iPAddress SAN";
  15051. EXPECT_FALSE(wrong_ipv6_matched)
  15052. << "verify_hostname should not match a non-matching IPv6 address";
  15053. EXPECT_FALSE(cn_ipv6_matched)
  15054. << "An IPv6 host must not be authenticated via the certificate CN";
  15055. }
  15056. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  15057. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  15058. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15059. using namespace httplib::tls;
  15060. // SANs: DNS:a.zz, IP:42.46.122.122
  15061. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15062. ASSERT_TRUE(svr.is_valid());
  15063. svr.Get("/test", [](const Request &, Response &res) {
  15064. res.set_content("ok", "text/plain");
  15065. });
  15066. auto port = svr.bind_to_any_port(HOST);
  15067. thread t([&]() { svr.listen_after_bind(); });
  15068. auto se = detail::scope_exit([&] {
  15069. svr.stop();
  15070. t.join();
  15071. });
  15072. svr.wait_until_ready();
  15073. bool verify_callback_called = false;
  15074. bool dns_san_matched = false;
  15075. bool ip_san_matched = false;
  15076. bool ip_matched_via_dns_san = true;
  15077. bool dns_matched_via_ip_san = true;
  15078. bool cn_matched_next_to_dns_san = true;
  15079. SSLClient cli(HOST, port);
  15080. cli.enable_server_certificate_verification(true);
  15081. cli.set_ca_cert_path(CA_CERT_FILE);
  15082. cli.set_connection_timeout(5);
  15083. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15084. verify_callback_called = true;
  15085. if (!ctx.cert) return false;
  15086. dns_san_matched = ctx.check_hostname("a.zz");
  15087. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15088. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15089. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15090. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15091. return true; // Accept for the purpose of this test
  15092. });
  15093. cli.Get("/test");
  15094. ASSERT_TRUE(verify_callback_called)
  15095. << "Verify callback should have been called";
  15096. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15097. EXPECT_TRUE(ip_san_matched)
  15098. << "verify_hostname should match an iPAddress SAN";
  15099. EXPECT_FALSE(ip_matched_via_dns_san)
  15100. << "An IP host must not be authenticated via a dNSName SAN";
  15101. EXPECT_FALSE(dns_matched_via_ip_san)
  15102. << "A DNS host must not be authenticated via an iPAddress SAN";
  15103. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15104. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15105. }
  15106. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15107. // "www.*.example.test" names one host and not every host under example.test.
  15108. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15109. using namespace httplib::tls;
  15110. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15111. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15112. ASSERT_TRUE(svr.is_valid());
  15113. svr.Get("/test", [](const Request &, Response &res) {
  15114. res.set_content("ok", "text/plain");
  15115. });
  15116. auto port = svr.bind_to_any_port(HOST);
  15117. thread t([&]() { svr.listen_after_bind(); });
  15118. auto se = detail::scope_exit([&] {
  15119. svr.stop();
  15120. t.join();
  15121. });
  15122. svr.wait_until_ready();
  15123. bool verify_callback_called = false;
  15124. bool leftmost_wildcard_matched = false;
  15125. bool wildcard_spanned_labels = true;
  15126. bool inner_wildcard_matched = true;
  15127. SSLClient cli(HOST, port);
  15128. cli.enable_server_certificate_verification(true);
  15129. cli.set_ca_cert_path(CA_CERT_FILE);
  15130. cli.set_connection_timeout(5);
  15131. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15132. verify_callback_called = true;
  15133. if (!ctx.cert) return false;
  15134. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15135. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15136. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15137. return true; // Accept for the purpose of this test
  15138. });
  15139. cli.Get("/test");
  15140. ASSERT_TRUE(verify_callback_called)
  15141. << "Verify callback should have been called";
  15142. EXPECT_TRUE(leftmost_wildcard_matched)
  15143. << "A leftmost wildcard should match a single label";
  15144. EXPECT_FALSE(wildcard_spanned_labels)
  15145. << "A wildcard label must not match more than one label";
  15146. EXPECT_FALSE(inner_wildcard_matched)
  15147. << "A wildcard outside the leftmost label must not be honoured";
  15148. }
  15149. // sans() must report each SAN entry under its own type.
  15150. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15151. using namespace httplib::tls;
  15152. // SANs: DNS:a.zz, IP:42.46.122.122
  15153. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15154. ASSERT_TRUE(svr.is_valid());
  15155. svr.Get("/test", [](const Request &, Response &res) {
  15156. res.set_content("ok", "text/plain");
  15157. });
  15158. auto port = svr.bind_to_any_port(HOST);
  15159. thread t([&]() { svr.listen_after_bind(); });
  15160. auto se = detail::scope_exit([&] {
  15161. svr.stop();
  15162. t.join();
  15163. });
  15164. svr.wait_until_ready();
  15165. bool verify_callback_called = false;
  15166. std::vector<SanEntry> sans;
  15167. SSLClient cli(HOST, port);
  15168. cli.enable_server_certificate_verification(true);
  15169. cli.set_ca_cert_path(CA_CERT_FILE);
  15170. cli.set_connection_timeout(5);
  15171. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15172. verify_callback_called = true;
  15173. if (!ctx.cert) return false;
  15174. sans = ctx.sans();
  15175. return true; // Accept for the purpose of this test
  15176. });
  15177. cli.Get("/test");
  15178. ASSERT_TRUE(verify_callback_called)
  15179. << "Verify callback should have been called";
  15180. auto has_san = [&](SanType type, const std::string &value) {
  15181. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15182. return san.type == type && san.value == value;
  15183. });
  15184. };
  15185. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15186. << "sans() should report the dNSName SAN";
  15187. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15188. << "sans() should report the iPAddress SAN";
  15189. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15190. << "sans() must not report the dNSName SAN as an address";
  15191. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15192. << "sans() must not report the iPAddress SAN as a DNS name";
  15193. }
  15194. #endif
  15195. // mbedTLS-specific callback constructor test
  15196. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15197. #ifdef CPPHTTPLIB_SSL_ENABLED
  15198. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15199. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15200. ASSERT_TRUE(svr.is_valid());
  15201. // Set up a handler to verify client certificate is present
  15202. bool client_cert_verified = false;
  15203. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15204. // Verify that client certificate was provided
  15205. client_cert_verified = true;
  15206. res.set_content("success", "text/plain");
  15207. });
  15208. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15209. auto se = detail::scope_exit([&] {
  15210. svr.stop();
  15211. t.join();
  15212. ASSERT_FALSE(svr.is_running());
  15213. });
  15214. svr.wait_until_ready();
  15215. // Client with certificate
  15216. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15217. cli.enable_server_certificate_verification(false);
  15218. cli.set_connection_timeout(30);
  15219. auto res = cli.Get("/test");
  15220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15221. ASSERT_EQ(StatusCode::OK_200, res->status);
  15222. ASSERT_TRUE(client_cert_verified);
  15223. EXPECT_EQ("success", res->body);
  15224. }
  15225. #endif
  15226. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15227. // backends
  15228. #ifdef CPPHTTPLIB_SSL_ENABLED
  15229. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15230. using namespace httplib::tls;
  15231. // Test that when client CA cert file is provided,
  15232. // the server properly requests and validates client certificates
  15233. // Create a server with client authentication
  15234. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15235. ASSERT_TRUE(svr.is_valid());
  15236. bool handler_called = false;
  15237. svr.Get("/test", [&](const Request &req, Response &res) {
  15238. handler_called = true;
  15239. // Verify that a client certificate was provided
  15240. auto cert = req.peer_cert();
  15241. ASSERT_TRUE(static_cast<bool>(cert));
  15242. // Get the issuer name
  15243. std::string issuer_str = cert.issuer_name();
  15244. ASSERT_FALSE(issuer_str.empty());
  15245. // The client certificate should be issued by our test CA
  15246. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15247. res.set_content("authenticated", "text/plain");
  15248. });
  15249. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15250. auto se = detail::scope_exit([&] {
  15251. svr.stop();
  15252. t.join();
  15253. ASSERT_FALSE(svr.is_running());
  15254. });
  15255. svr.wait_until_ready();
  15256. // Connect with a client certificate issued by the CA
  15257. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15258. cli.enable_server_certificate_verification(false);
  15259. cli.set_connection_timeout(30);
  15260. auto res = cli.Get("/test");
  15261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15262. ASSERT_EQ(StatusCode::OK_200, res->status);
  15263. ASSERT_TRUE(handler_called);
  15264. EXPECT_EQ("authenticated", res->body);
  15265. }
  15266. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15267. using namespace httplib::tls;
  15268. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15269. ASSERT_TRUE(svr.is_valid());
  15270. svr.Get("/test", [](const Request &, Response &res) {
  15271. res.set_content("ok", "text/plain");
  15272. });
  15273. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15274. auto se = detail::scope_exit([&] {
  15275. svr.stop();
  15276. t.join();
  15277. });
  15278. svr.wait_until_ready();
  15279. SSLClient cli(HOST, PORT);
  15280. cli.enable_server_certificate_verification(false);
  15281. cli.set_connection_timeout(30);
  15282. bool cert_checked = false;
  15283. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15284. if (ctx.cert) {
  15285. auto sans = ctx.sans();
  15286. // Test certificate may or may not have SANs - just verify the API
  15287. // works If SANs exist, verify the types are valid
  15288. for (const auto &san : sans) {
  15289. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15290. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15291. san.type == SanType::OTHER);
  15292. EXPECT_FALSE(san.value.empty());
  15293. }
  15294. cert_checked = true;
  15295. }
  15296. return true;
  15297. });
  15298. auto res = cli.Get("/test");
  15299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15300. EXPECT_TRUE(cert_checked);
  15301. }
  15302. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15303. using namespace httplib::tls;
  15304. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15305. ASSERT_TRUE(svr.is_valid());
  15306. svr.Get("/test", [](const Request &, Response &res) {
  15307. res.set_content("ok", "text/plain");
  15308. });
  15309. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15310. auto se = detail::scope_exit([&] {
  15311. svr.stop();
  15312. t.join();
  15313. });
  15314. svr.wait_until_ready();
  15315. SSLClient cli(HOST, PORT);
  15316. cli.enable_server_certificate_verification(false);
  15317. cli.set_connection_timeout(30);
  15318. bool validity_checked = false;
  15319. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15320. if (ctx.cert) {
  15321. time_t not_before = 0, not_after = 0;
  15322. bool result = ctx.validity(not_before, not_after);
  15323. EXPECT_TRUE(result);
  15324. // Verify that not_before < now < not_after for a valid cert
  15325. time_t now = time(nullptr);
  15326. EXPECT_LT(not_before, now);
  15327. EXPECT_GT(not_after, now);
  15328. validity_checked = true;
  15329. }
  15330. return true;
  15331. });
  15332. auto res = cli.Get("/test");
  15333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15334. EXPECT_TRUE(validity_checked);
  15335. }
  15336. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15337. using namespace httplib::tls;
  15338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15339. ASSERT_TRUE(svr.is_valid());
  15340. svr.Get("/test", [](const Request &, Response &res) {
  15341. res.set_content("ok", "text/plain");
  15342. });
  15343. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15344. auto se = detail::scope_exit([&] {
  15345. svr.stop();
  15346. t.join();
  15347. });
  15348. svr.wait_until_ready();
  15349. SSLClient cli(HOST, PORT);
  15350. cli.enable_server_certificate_verification(false);
  15351. cli.set_connection_timeout(30);
  15352. bool serial_checked = false;
  15353. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15354. if (ctx.cert) {
  15355. std::string serial = ctx.serial();
  15356. EXPECT_FALSE(serial.empty());
  15357. // Serial should be a hex string
  15358. for (char c : serial) {
  15359. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15360. (c >= 'a' && c <= 'f'));
  15361. }
  15362. serial_checked = true;
  15363. }
  15364. return true;
  15365. });
  15366. auto res = cli.Get("/test");
  15367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15368. EXPECT_TRUE(serial_checked);
  15369. }
  15370. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15371. // Test 1: Valid CA file - no error should be recorded
  15372. {
  15373. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15374. CLIENT_CA_CERT_FILE);
  15375. ASSERT_TRUE(svr.is_valid());
  15376. // With valid setup, last_ssl_error should be 0
  15377. EXPECT_EQ(0, svr.ssl_last_error());
  15378. }
  15379. // Test 2: Invalid CA file content
  15380. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15381. {
  15382. // Create a temporary file with completely invalid content
  15383. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15384. {
  15385. std::ofstream ofs(temp_invalid_ca);
  15386. ofs << "This is not a certificate file at all\n";
  15387. ofs << "Just plain text content\n";
  15388. }
  15389. // Create server with invalid CA file
  15390. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15391. // Clean up temporary file
  15392. std::remove(temp_invalid_ca);
  15393. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15394. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15395. // Note: SSL_CTX_load_verify_locations typically fails first,
  15396. // but our error handling code path is still exercised
  15397. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15398. }
  15399. }
  15400. TEST(VerifyCallbackTest, VerifyContextFields) {
  15401. using namespace httplib::tls;
  15402. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15403. ASSERT_TRUE(svr.is_valid());
  15404. svr.Get("/test", [](const Request &, Response &res) {
  15405. res.set_content("ok", "text/plain");
  15406. });
  15407. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15408. auto se = detail::scope_exit([&] {
  15409. svr.stop();
  15410. t.join();
  15411. });
  15412. svr.wait_until_ready();
  15413. SSLClient cli(HOST, PORT);
  15414. cli.enable_server_certificate_verification(false);
  15415. cli.set_connection_timeout(30);
  15416. int callback_count = 0;
  15417. bool saw_leaf_cert = false;
  15418. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15419. if (ctx.cert) {
  15420. callback_count++;
  15421. // We should see at least one certificate (the leaf)
  15422. std::string cn = ctx.subject_cn();
  15423. if (!cn.empty()) { saw_leaf_cert = true; }
  15424. // Verify context fields are populated
  15425. EXPECT_NE(ctx.session, nullptr);
  15426. EXPECT_GE(ctx.depth, 0);
  15427. }
  15428. return true;
  15429. });
  15430. auto res = cli.Get("/test");
  15431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15432. EXPECT_GT(callback_count, 0);
  15433. EXPECT_TRUE(saw_leaf_cert);
  15434. }
  15435. // A verifier that accepts runs alongside the built-in verification, and is the
  15436. // only check once that is turned off.
  15437. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15438. using namespace httplib::tls;
  15439. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15440. ASSERT_TRUE(svr.is_valid());
  15441. svr.Get("/test", [](const Request &, Response &res) {
  15442. res.set_content("ok", "text/plain");
  15443. });
  15444. auto port = svr.bind_to_any_port(HOST);
  15445. thread t([&]() { svr.listen_after_bind(); });
  15446. auto se = detail::scope_exit([&] {
  15447. svr.stop();
  15448. t.join();
  15449. });
  15450. svr.wait_until_ready();
  15451. SSLClient cli(HOST, port);
  15452. cli.enable_server_hostname_verification(false);
  15453. auto calls = 0;
  15454. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15455. calls++;
  15456. return true;
  15457. });
  15458. // cert.pem is not trusted
  15459. auto res = cli.Get("/test");
  15460. ASSERT_FALSE(res);
  15461. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15462. EXPECT_GT(calls, 0);
  15463. cli.enable_server_certificate_verification(false);
  15464. res = cli.Get("/test");
  15465. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15466. EXPECT_EQ("ok", res->body);
  15467. }
  15468. // A verifier belongs to the client that set it, not to the thread that set it.
  15469. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15470. using namespace httplib::tls;
  15471. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15472. ASSERT_TRUE(svr.is_valid());
  15473. svr.Get("/test", [](const Request &, Response &res) {
  15474. res.set_content("ok", "text/plain");
  15475. });
  15476. auto port = svr.bind_to_any_port(HOST);
  15477. thread t([&]() { svr.listen_after_bind(); });
  15478. auto se = detail::scope_exit([&] {
  15479. svr.stop();
  15480. t.join();
  15481. });
  15482. svr.wait_until_ready();
  15483. auto rejecting_calls = 0;
  15484. SSLClient rejecting(HOST, port);
  15485. rejecting.enable_server_certificate_verification(false);
  15486. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15487. rejecting_calls++;
  15488. return false;
  15489. });
  15490. auto accepting_calls = 0;
  15491. SSLClient accepting(HOST, port);
  15492. accepting.enable_server_certificate_verification(false);
  15493. // Set on another thread than the requests below.
  15494. thread([&]() {
  15495. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15496. accepting_calls++;
  15497. return true;
  15498. });
  15499. }).join();
  15500. // Requested on another thread than the verifier was set on.
  15501. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15502. EXPECT_GT(rejecting_calls, 0);
  15503. auto res = accepting.Get("/test");
  15504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15505. EXPECT_GT(accepting_calls, 0);
  15506. }
  15507. // A verifier replaced while a handshake runs it lives until it returns.
  15508. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15509. using namespace httplib::tls;
  15510. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15511. ASSERT_TRUE(svr.is_valid());
  15512. svr.Get("/test", [](const Request &, Response &res) {
  15513. res.set_content("ok", "text/plain");
  15514. });
  15515. auto port = svr.bind_to_any_port(HOST);
  15516. thread t([&]() { svr.listen_after_bind(); });
  15517. auto se = detail::scope_exit([&] {
  15518. svr.stop();
  15519. t.join();
  15520. });
  15521. svr.wait_until_ready();
  15522. SSLClient cli(HOST, port);
  15523. cli.enable_server_certificate_verification(false);
  15524. std::promise<void> entered;
  15525. std::promise<void> replaced;
  15526. auto replaced_future = replaced.get_future();
  15527. auto first_call = true;
  15528. // Long enough to live on the heap
  15529. std::string expected(64, 'v');
  15530. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15531. if (first_call) {
  15532. first_call = false;
  15533. entered.set_value();
  15534. replaced_future.wait();
  15535. }
  15536. return expected == std::string(64, 'v');
  15537. });
  15538. thread request([&]() {
  15539. auto res = cli.Get("/test");
  15540. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15541. });
  15542. entered.get_future().wait();
  15543. cli.set_server_certificate_verifier(
  15544. [](const VerifyContext &) { return true; });
  15545. replaced.set_value();
  15546. request.join();
  15547. }
  15548. // VerifyContext::session is the same handle the other tls:: functions take.
  15549. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15550. using namespace httplib::tls;
  15551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15552. ASSERT_TRUE(svr.is_valid());
  15553. svr.Get("/test", [](const Request &, Response &res) {
  15554. res.set_content("ok", "text/plain");
  15555. });
  15556. auto port = svr.bind_to_any_port(HOST);
  15557. thread t([&]() { svr.listen_after_bind(); });
  15558. auto se = detail::scope_exit([&] {
  15559. svr.stop();
  15560. t.join();
  15561. });
  15562. svr.wait_until_ready();
  15563. SSLClient cli(HOST, port);
  15564. cli.enable_server_certificate_verification(false);
  15565. session_t verifier_session = nullptr;
  15566. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15567. verifier_session = ctx.session;
  15568. return true;
  15569. });
  15570. session_t session_verifier_session = nullptr;
  15571. cli.set_session_verifier([&](session_t session) {
  15572. session_verifier_session = session;
  15573. return SSLVerifierResponse::NoDecisionMade;
  15574. });
  15575. auto res = cli.Get("/test");
  15576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15577. EXPECT_NE(nullptr, verifier_session);
  15578. EXPECT_EQ(session_verifier_session, verifier_session);
  15579. }
  15580. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15581. using httplib::tls::TlsError;
  15582. // Test that verify_error_to_string returns empty for success
  15583. std::string success_str = TlsError::verify_error_to_string(0);
  15584. EXPECT_TRUE(success_str.empty());
  15585. // Test that verify_error_to_string returns non-empty for error codes
  15586. // Using a common error code (certificate expired)
  15587. std::string error_str =
  15588. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15589. EXPECT_FALSE(error_str.empty());
  15590. }
  15591. TEST(SessionVerifierTest, CertificateAccepted) {
  15592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15593. ASSERT_TRUE(svr.is_valid());
  15594. svr.Get("/test", [](const Request &, Response &res) {
  15595. res.set_content("ok", "text/plain");
  15596. });
  15597. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15598. auto se = detail::scope_exit([&] {
  15599. svr.stop();
  15600. t.join();
  15601. });
  15602. svr.wait_until_ready();
  15603. SSLClient cli(HOST, PORT);
  15604. cli.enable_server_certificate_verification(false);
  15605. cli.set_connection_timeout(30);
  15606. bool callback_called = false;
  15607. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15608. EXPECT_NE(session, nullptr);
  15609. callback_called = true;
  15610. return SSLVerifierResponse::CertificateAccepted;
  15611. });
  15612. auto res = cli.Get("/test");
  15613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15614. EXPECT_EQ(200, res->status);
  15615. EXPECT_TRUE(callback_called);
  15616. }
  15617. TEST(SessionVerifierTest, CertificateRejected) {
  15618. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15619. ASSERT_TRUE(svr.is_valid());
  15620. svr.Get("/test", [](const Request &, Response &res) {
  15621. res.set_content("ok", "text/plain");
  15622. });
  15623. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15624. auto se = detail::scope_exit([&] {
  15625. svr.stop();
  15626. t.join();
  15627. });
  15628. svr.wait_until_ready();
  15629. SSLClient cli(HOST, PORT);
  15630. cli.enable_server_certificate_verification(false);
  15631. cli.set_connection_timeout(30);
  15632. bool callback_called = false;
  15633. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15634. EXPECT_NE(session, nullptr);
  15635. callback_called = true;
  15636. return SSLVerifierResponse::CertificateRejected;
  15637. });
  15638. auto res = cli.Get("/test");
  15639. EXPECT_FALSE(res);
  15640. EXPECT_TRUE(callback_called);
  15641. }
  15642. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15643. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15644. ASSERT_TRUE(svr.is_valid());
  15645. svr.Get("/test", [](const Request &, Response &res) {
  15646. res.set_content("ok", "text/plain");
  15647. });
  15648. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15649. auto se = detail::scope_exit([&] {
  15650. svr.stop();
  15651. t.join();
  15652. });
  15653. svr.wait_until_ready();
  15654. // NoDecisionMade with verification disabled should succeed (no default check)
  15655. SSLClient cli(HOST, PORT);
  15656. cli.enable_server_certificate_verification(false);
  15657. cli.set_connection_timeout(30);
  15658. bool callback_called = false;
  15659. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15660. EXPECT_NE(session, nullptr);
  15661. callback_called = true;
  15662. return SSLVerifierResponse::NoDecisionMade;
  15663. });
  15664. auto res = cli.Get("/test");
  15665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15666. EXPECT_EQ(200, res->status);
  15667. EXPECT_TRUE(callback_called);
  15668. }
  15669. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15671. ASSERT_TRUE(svr.is_valid());
  15672. svr.Get("/test", [](const Request &, Response &res) {
  15673. res.set_content("ok", "text/plain");
  15674. });
  15675. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15676. auto se = detail::scope_exit([&] {
  15677. svr.stop();
  15678. t.join();
  15679. });
  15680. svr.wait_until_ready();
  15681. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15682. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15683. // so we only check that the request fails, not whether the callback was
  15684. // called.
  15685. SSLClient cli(HOST, PORT);
  15686. cli.enable_server_certificate_verification(true);
  15687. cli.set_connection_timeout(30);
  15688. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15689. EXPECT_NE(session, nullptr);
  15690. return SSLVerifierResponse::NoDecisionMade;
  15691. });
  15692. auto res = cli.Get("/test");
  15693. EXPECT_FALSE(res);
  15694. }
  15695. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15696. // Test SSL server using PemMemory constructor with client CA certificates
  15697. // Read PEM files
  15698. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15699. read_file(SERVER_CERT_FILE, server_cert_pem);
  15700. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15701. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15702. // Create SSLServer with PemMemory constructor including client CA
  15703. SSLServer::PemMemory server_pem = {
  15704. server_cert_pem.c_str(),
  15705. server_cert_pem.size(),
  15706. server_key_pem.c_str(),
  15707. server_key_pem.size(),
  15708. client_ca_pem.c_str(),
  15709. client_ca_pem.size(),
  15710. nullptr // no password for server key
  15711. };
  15712. SSLServer svr(server_pem);
  15713. ASSERT_TRUE(svr.is_valid());
  15714. // No SSL error should be recorded for valid setup
  15715. EXPECT_EQ(0, svr.ssl_last_error());
  15716. // Set up server endpoints
  15717. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15718. res.set_content("ok", "text/plain");
  15719. });
  15720. // Start server in a thread
  15721. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15722. svr.wait_until_ready();
  15723. // Connect with client certificate (using constructor with paths)
  15724. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15725. cli.enable_server_certificate_verification(false);
  15726. auto res = cli.Get("/test-pem-ca");
  15727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15728. EXPECT_EQ(200, res->status);
  15729. EXPECT_EQ("ok", res->body);
  15730. svr.stop();
  15731. server_thread.join();
  15732. }
  15733. #endif
  15734. #ifdef _WIN32
  15735. TEST(CleanupTest, WSACleanup) {
  15736. int ret = WSACleanup();
  15737. ASSERT_EQ(0, ret);
  15738. }
  15739. #endif
  15740. #ifndef CPPHTTPLIB_SSL_ENABLED
  15741. TEST(NoSSLSupport, SimpleInterface) {
  15742. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15743. }
  15744. #endif
  15745. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15746. TEST(InvalidScheme, SimpleInterface) {
  15747. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15748. }
  15749. #endif
  15750. TEST(NoScheme, SimpleInterface) {
  15751. Client cli("yahoo.com:80");
  15752. ASSERT_TRUE(cli.is_valid());
  15753. }
  15754. TEST(SendAPI, SimpleInterface_Online) {
  15755. Client cli("http://yahoo.com");
  15756. Request req;
  15757. req.method = "GET";
  15758. req.path = "/";
  15759. auto res = cli.send(req);
  15760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15761. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15762. }
  15763. TEST(SendAPI, WithParamsInRequest) {
  15764. Server svr;
  15765. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15766. EXPECT_TRUE(req.has_param("test"));
  15767. EXPECT_EQ("test_value", req.get_param_value("test"));
  15768. });
  15769. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15770. auto se = detail::scope_exit([&] {
  15771. svr.stop();
  15772. t.join();
  15773. ASSERT_FALSE(svr.is_running());
  15774. });
  15775. svr.wait_until_ready();
  15776. Client cli(HOST, PORT);
  15777. {
  15778. Request req;
  15779. req.method = "GET";
  15780. req.path = "/";
  15781. req.params.emplace("test", "test_value");
  15782. auto res = cli.send(req);
  15783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15784. }
  15785. {
  15786. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15788. }
  15789. }
  15790. TEST(ClientImplMethods, GetSocketTest) {
  15791. httplib::Server svr;
  15792. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15793. res.status = StatusCode::OK_200;
  15794. });
  15795. auto port = svr.bind_to_any_port("127.0.0.1");
  15796. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15797. auto se = detail::scope_exit([&] {
  15798. svr.stop();
  15799. thread.join();
  15800. ASSERT_FALSE(svr.is_running());
  15801. });
  15802. svr.wait_until_ready();
  15803. {
  15804. httplib::Client cli("127.0.0.1", port);
  15805. cli.set_keep_alive(true);
  15806. // Use the behavior of cpp-httplib of opening the connection
  15807. // only when the first request happens. If that changes,
  15808. // this test would be obsolete.
  15809. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15810. // This also implicitly tests the server. But other tests would fail much
  15811. // earlier than this one to be considered.
  15812. auto res = cli.Get("/");
  15813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15814. EXPECT_EQ(StatusCode::OK_200, res->status);
  15815. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15816. }
  15817. }
  15818. #ifdef CPPHTTPLIB_SSL_ENABLED
  15819. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15820. Client cli("http://yahoo.com");
  15821. auto res = cli.Get("/");
  15822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15823. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15824. cli.set_follow_location(true);
  15825. res = cli.Get("/");
  15826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15827. EXPECT_EQ(StatusCode::OK_200, res->status);
  15828. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15829. }
  15830. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15831. Client cli("https://yahoo.com");
  15832. auto res = cli.Get("/");
  15833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15834. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15835. cli.set_follow_location(true);
  15836. res = cli.Get("/");
  15837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15838. EXPECT_EQ(StatusCode::OK_200, res->status);
  15839. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15840. }
  15841. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15842. Client cli("https://yahoo.com");
  15843. auto res = cli.Get("/");
  15844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15845. ASSERT_FALSE(!res);
  15846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15847. ASSERT_FALSE(res == nullptr);
  15848. ASSERT_TRUE(res != nullptr);
  15849. EXPECT_EQ(Error::Success, res.error());
  15850. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15851. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15852. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15853. cli.set_follow_location(true);
  15854. res = cli.Get("/");
  15855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15856. EXPECT_EQ(Error::Success, res.error());
  15857. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15858. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15859. EXPECT_EQ(StatusCode::OK_200, res->status);
  15860. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15861. }
  15862. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15863. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15864. Client cli("https://cdnjs.cloudflare.com");
  15865. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15866. Headers{{"Accept-Encoding", "br"}});
  15867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15868. EXPECT_EQ(StatusCode::OK_200, res->status);
  15869. EXPECT_EQ(287630U, res->body.size());
  15870. EXPECT_EQ("application/javascript; charset=utf-8",
  15871. res->get_header_value("Content-Type"));
  15872. }
  15873. #endif
  15874. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15875. #undef REDIR_HOST // Silence compiler warning
  15876. #define REDIR_HOST "https://httpbingo.org"
  15877. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15878. Client cli(REDIR_HOST);
  15879. cli.set_follow_location(true);
  15880. auto res = retry_gateway_errors([&] {
  15881. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15882. });
  15883. SKIP_ON_GATEWAY_ERROR(res);
  15884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15885. EXPECT_EQ(StatusCode::OK_200, res->status);
  15886. }
  15887. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15888. Client cli(REDIR_HOST);
  15889. cli.set_follow_location(true);
  15890. Params params;
  15891. params.emplace("url", "http://example.com");
  15892. params.emplace("status_code", "302");
  15893. auto res = retry_gateway_errors(
  15894. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  15895. SKIP_ON_GATEWAY_ERROR(res);
  15896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15897. EXPECT_EQ(StatusCode::OK_200, res->status);
  15898. }
  15899. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15900. Client cli(REDIR_HOST);
  15901. cli.set_follow_location(true);
  15902. Params params;
  15903. params.emplace("url", "http://example.com");
  15904. auto res = retry_gateway_errors([&] {
  15905. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15906. });
  15907. SKIP_ON_GATEWAY_ERROR(res);
  15908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15909. EXPECT_EQ(StatusCode::OK_200, res->status);
  15910. }
  15911. TEST(HttpToHttpsRedirectTest, CertFile) {
  15912. auto ssl_port = PORT + 1;
  15913. Server svr;
  15914. ASSERT_TRUE(svr.is_valid());
  15915. svr.Get("/index", [&](const Request &, Response &res) {
  15916. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15917. "/index");
  15918. svr.stop();
  15919. });
  15920. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15921. ASSERT_TRUE(ssl_svr.is_valid());
  15922. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15923. res.set_content("test", "text/plain");
  15924. ssl_svr.stop();
  15925. });
  15926. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15927. thread t2 =
  15928. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15929. auto se = detail::scope_exit([&] {
  15930. t2.join();
  15931. t.join();
  15932. ASSERT_FALSE(svr.is_running());
  15933. });
  15934. svr.wait_until_ready();
  15935. ssl_svr.wait_until_ready();
  15936. Client cli("127.0.0.1", PORT);
  15937. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15938. cli.enable_server_certificate_verification(true);
  15939. cli.set_follow_location(true);
  15940. cli.set_connection_timeout(30);
  15941. auto res = cli.Get("/index");
  15942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15943. ASSERT_EQ(StatusCode::OK_200, res->status);
  15944. }
  15945. TEST(UppercaseSchemeTest, UsesTLS) {
  15946. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15947. ASSERT_TRUE(ssl_svr.is_valid());
  15948. ssl_svr.Get("/index", [](const Request &, Response &res) {
  15949. res.set_content("test", "text/plain");
  15950. });
  15951. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  15952. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  15953. Server svr;
  15954. svr.Get("/index", [&](const Request &, Response &res) {
  15955. res.set_redirect(https_url + "/index");
  15956. });
  15957. auto port = svr.bind_to_any_port("127.0.0.1");
  15958. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  15959. auto t2 = thread([&] { svr.listen_after_bind(); });
  15960. auto se = detail::scope_exit([&] {
  15961. svr.stop();
  15962. ssl_svr.stop();
  15963. t2.join();
  15964. t.join();
  15965. });
  15966. ssl_svr.wait_until_ready();
  15967. svr.wait_until_ready();
  15968. {
  15969. Client cli(https_url);
  15970. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15971. auto res = cli.Get("/index");
  15972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15973. EXPECT_EQ("test", res->body);
  15974. }
  15975. {
  15976. Client cli("127.0.0.1", port);
  15977. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15978. cli.set_follow_location(true);
  15979. auto res = cli.Get("/index");
  15980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15981. EXPECT_EQ("test", res->body);
  15982. }
  15983. }
  15984. TEST(SSLClientRedirectTest, CertFile) {
  15985. auto ssl_port = PORT + 1;
  15986. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15987. ASSERT_TRUE(ssl_svr1.is_valid());
  15988. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15989. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15990. "/index");
  15991. ssl_svr1.stop();
  15992. });
  15993. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15994. ASSERT_TRUE(ssl_svr2.is_valid());
  15995. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15996. res.set_content("test", "text/plain");
  15997. ssl_svr2.stop();
  15998. });
  15999. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16000. thread t2 =
  16001. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16002. auto se = detail::scope_exit([&] {
  16003. t2.join();
  16004. t.join();
  16005. ASSERT_FALSE(ssl_svr1.is_running());
  16006. });
  16007. ssl_svr1.wait_until_ready();
  16008. ssl_svr2.wait_until_ready();
  16009. SSLClient cli("127.0.0.1", PORT);
  16010. std::string cert;
  16011. read_file(SERVER_CERT2_FILE, cert);
  16012. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16013. cli.enable_server_certificate_verification(true);
  16014. cli.set_follow_location(true);
  16015. cli.set_connection_timeout(30);
  16016. auto res = cli.Get("/index");
  16017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16018. ASSERT_EQ(StatusCode::OK_200, res->status);
  16019. }
  16020. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  16021. // another port, so the client follows it with a new client.
  16022. static Result GetThroughTlsRedirectToDifferentPort(
  16023. const std::function<void(SSLClient &)> &setup,
  16024. const char *target_cert = SERVER_CERT2_FILE,
  16025. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  16026. auto ssl_port = PORT + 1;
  16027. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16028. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16029. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16030. "/index");
  16031. });
  16032. SSLServer ssl_svr2(target_cert, target_key);
  16033. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16034. res.set_content("test", "text/plain");
  16035. });
  16036. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  16037. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  16038. auto se = detail::scope_exit([&] {
  16039. ssl_svr2.stop();
  16040. ssl_svr1.stop();
  16041. t2.join();
  16042. t.join();
  16043. });
  16044. ssl_svr1.wait_until_ready();
  16045. ssl_svr2.wait_until_ready();
  16046. SSLClient cli("127.0.0.1", PORT);
  16047. cli.set_follow_location(true);
  16048. cli.set_connection_timeout(30);
  16049. setup(cli);
  16050. return cli.Get("/index");
  16051. }
  16052. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  16053. auto calls = 0;
  16054. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  16055. cli.enable_server_certificate_verification(false);
  16056. // Accept the first server only.
  16057. cli.set_session_verifier([&](tls::session_t) {
  16058. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  16059. : SSLVerifierResponse::CertificateRejected;
  16060. });
  16061. });
  16062. ASSERT_FALSE(res);
  16063. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16064. EXPECT_EQ(2, calls);
  16065. }
  16066. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16067. std::string pinned;
  16068. auto res = GetThroughTlsRedirectToDifferentPort(
  16069. [&](SSLClient &cli) {
  16070. cli.enable_server_certificate_verification(false);
  16071. // Pin the first certificate seen.
  16072. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16073. if (pinned.empty()) { pinned = ctx.serial(); }
  16074. return ctx.serial() == pinned;
  16075. });
  16076. },
  16077. // A certificate other than the first server's.
  16078. SERVER_CERT_FILE);
  16079. EXPECT_FALSE(res);
  16080. EXPECT_FALSE(pinned.empty());
  16081. }
  16082. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16083. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16084. std::string cert;
  16085. read_file(SERVER_CERT2_FILE, cert);
  16086. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16087. });
  16088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16089. EXPECT_EQ(StatusCode::OK_200, res->status);
  16090. }
  16091. // The target's certificate is signed by the root CA, which the first server's
  16092. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16093. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16094. auto res = GetThroughTlsRedirectToDifferentPort(
  16095. [](SSLClient &cli) {
  16096. std::string root_ca, cert;
  16097. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16098. read_file(SERVER_CERT2_FILE, cert);
  16099. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16100. cli.load_ca_cert_store(cert.data(), cert.size());
  16101. cli.enable_server_hostname_verification(false);
  16102. },
  16103. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16105. EXPECT_EQ(StatusCode::OK_200, res->status);
  16106. }
  16107. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16108. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16109. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16110. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16111. auto res = GetThroughTlsRedirectToDifferentPort(
  16112. [](SSLClient &cli) {
  16113. std::string root_ca, cert;
  16114. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16115. read_file(SERVER_CERT2_FILE, cert);
  16116. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16117. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16118. cli.enable_server_hostname_verification(false);
  16119. },
  16120. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16121. ASSERT_FALSE(res);
  16122. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16123. }
  16124. #endif
  16125. #endif
  16126. #ifdef CPPHTTPLIB_SSL_ENABLED
  16127. // Test that set_ca_cert_store() skips system certs (consistent with
  16128. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16129. // should be trusted - system certs should NOT be loaded.
  16130. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16131. // Load a specific cert that is NOT a system CA cert
  16132. std::string cert;
  16133. read_file(SERVER_CERT2_FILE, cert);
  16134. SSLClient cli("google.com");
  16135. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16136. cli.enable_server_certificate_verification(true);
  16137. // This should FAIL because:
  16138. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16139. // 2. System certs should NOT be loaded when custom store is set
  16140. // If system certs WERE loaded, this would succeed
  16141. auto res = cli.Get("/");
  16142. ASSERT_FALSE(res);
  16143. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16144. }
  16145. // Same as above, but through the native store handle path. Regression test:
  16146. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16147. // merged system certs into the user-provided store.
  16148. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16149. std::string cert;
  16150. read_file(SERVER_CERT2_FILE, cert);
  16151. SSLClient cli("google.com");
  16152. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16153. cli.enable_server_certificate_verification(true);
  16154. auto res = cli.Get("/");
  16155. ASSERT_FALSE(res);
  16156. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16157. }
  16158. // A custom store set via the native handle must still verify a server whose
  16159. // cert it does contain.
  16160. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16161. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16162. ASSERT_TRUE(svr.is_valid());
  16163. svr.Get("/test", [&](const Request &, Response &res) {
  16164. res.set_content("test", "text/plain");
  16165. });
  16166. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16167. auto se = detail::scope_exit([&] {
  16168. svr.stop();
  16169. t.join();
  16170. ASSERT_FALSE(svr.is_running());
  16171. });
  16172. svr.wait_until_ready();
  16173. SSLClient cli("127.0.0.1", PORT);
  16174. std::string cert;
  16175. read_file(SERVER_CERT2_FILE, cert);
  16176. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16177. cli.enable_server_certificate_verification(true);
  16178. cli.set_connection_timeout(30);
  16179. auto res = cli.Get("/test");
  16180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16181. ASSERT_EQ(StatusCode::OK_200, res->status);
  16182. }
  16183. // CA certs loaded through the universal Client must be transferred to the
  16184. // client created internally for following an HTTPS redirect. Regression test:
  16185. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16186. // the CA data for redirect transfer.
  16187. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16188. auto ssl_port = PORT + 1;
  16189. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16190. ASSERT_TRUE(ssl_svr1.is_valid());
  16191. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16192. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16193. "/index");
  16194. });
  16195. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16196. ASSERT_TRUE(ssl_svr2.is_valid());
  16197. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16198. res.set_content("test", "text/plain");
  16199. });
  16200. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16201. thread t2 =
  16202. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16203. auto se = detail::scope_exit([&] {
  16204. ssl_svr2.stop();
  16205. ssl_svr1.stop();
  16206. t2.join();
  16207. t.join();
  16208. ASSERT_FALSE(ssl_svr1.is_running());
  16209. });
  16210. ssl_svr1.wait_until_ready();
  16211. ssl_svr2.wait_until_ready();
  16212. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16213. std::string cert;
  16214. read_file(SERVER_CERT2_FILE, cert);
  16215. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16216. cli.enable_server_certificate_verification(true);
  16217. cli.set_follow_location(true);
  16218. cli.set_connection_timeout(30);
  16219. auto res = cli.Get("/index");
  16220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16221. ASSERT_EQ(StatusCode::OK_200, res->status);
  16222. }
  16223. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16224. // so a host signed by a system CA verifies even though a custom CA is set
  16225. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16226. std::string cert;
  16227. read_file(SERVER_CERT2_FILE, cert);
  16228. SSLClient cli("google.com");
  16229. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16230. cli.enable_system_ca(true);
  16231. cli.enable_server_certificate_verification(true);
  16232. auto res = cli.Get("/");
  16233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16234. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16235. }
  16236. // The custom CA remains effective when combined with the system CA
  16237. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16238. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16239. ASSERT_TRUE(svr.is_valid());
  16240. svr.Get("/test", [&](const Request &, Response &res) {
  16241. res.set_content("test", "text/plain");
  16242. });
  16243. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16244. auto se = detail::scope_exit([&] {
  16245. svr.stop();
  16246. t.join();
  16247. ASSERT_FALSE(svr.is_running());
  16248. });
  16249. svr.wait_until_ready();
  16250. SSLClient cli("127.0.0.1", PORT);
  16251. std::string cert;
  16252. read_file(SERVER_CERT2_FILE, cert);
  16253. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16254. cli.enable_system_ca(true);
  16255. cli.enable_server_certificate_verification(true);
  16256. cli.set_connection_timeout(30);
  16257. auto res = cli.Get("/test");
  16258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16259. ASSERT_EQ(StatusCode::OK_200, res->status);
  16260. }
  16261. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16262. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16263. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16264. static CFDictionaryRef
  16265. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16266. const SecTrustSettingsResult *result) {
  16267. auto constraint =
  16268. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16269. &kCFTypeDictionaryValueCallBacks);
  16270. if (policy) {
  16271. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16272. }
  16273. if (policy_string) {
  16274. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16275. kCFStringEncodingUTF8);
  16276. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16277. CFRelease(str);
  16278. }
  16279. if (result) {
  16280. auto number_value = static_cast<SInt32>(*result);
  16281. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16282. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16283. CFRelease(number);
  16284. }
  16285. return constraint;
  16286. }
  16287. static SecTrustSettingsResult
  16288. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16289. auto trust_settings =
  16290. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16291. for (auto constraint : constraints) {
  16292. CFArrayAppendValue(trust_settings, constraint);
  16293. CFRelease(constraint);
  16294. }
  16295. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16296. CFRelease(trust_settings);
  16297. return result;
  16298. }
  16299. // The system CA loader takes a Keychain certificate as a trusted root only
  16300. // when its Trust Settings say so for SSL, not merely because it has some.
  16301. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16302. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16303. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16304. const auto deny = kSecTrustSettingsResultDeny;
  16305. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16306. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16307. auto x509_policy = SecPolicyCreateBasicX509();
  16308. // "Always Trust", which stores no constraint at all
  16309. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16310. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16311. ssl_trust_settings_result(
  16312. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16313. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16314. ssl_trust_settings_result(
  16315. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16316. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16317. ssl_trust_settings_result(
  16318. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16319. // "Never Trust", for everything or for SSL
  16320. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16321. ssl_trust_settings_result(
  16322. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16323. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16324. ssl_trust_settings_result(
  16325. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16326. // Trusted for another policy, for one host, or not at all
  16327. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16328. ssl_trust_settings_result(
  16329. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16330. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16331. ssl_trust_settings_result({make_usage_constraint(
  16332. ssl_policy, "www.example.com", &trust_root)}));
  16333. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16334. ssl_trust_settings_result(
  16335. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16336. // The first constraint that applies to SSL decides
  16337. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16338. ssl_trust_settings_result(
  16339. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16340. make_usage_constraint(nullptr, nullptr, &deny)}));
  16341. CFRelease(x509_policy);
  16342. CFRelease(ssl_policy);
  16343. }
  16344. #endif
  16345. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16346. // skip chain verification entirely (only the certificate identity was
  16347. // checked), so a server presenting an untrusted certificate with a matching
  16348. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16349. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16350. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16351. ASSERT_TRUE(svr.is_valid());
  16352. svr.Get("/test", [&](const Request &, Response &res) {
  16353. res.set_content("test", "text/plain");
  16354. });
  16355. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16356. auto se = detail::scope_exit([&] {
  16357. svr.stop();
  16358. t.join();
  16359. ASSERT_FALSE(svr.is_running());
  16360. });
  16361. svr.wait_until_ready();
  16362. SSLClient cli("127.0.0.1", PORT);
  16363. std::string cert;
  16364. // A trusted CA that did not sign the server certificate. The server cert
  16365. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16366. // this connection.
  16367. read_file(CLIENT_CA_CERT_FILE, cert);
  16368. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16369. cli.enable_server_certificate_verification(true);
  16370. cli.set_connection_timeout(30);
  16371. auto res = cli.Get("/test");
  16372. ASSERT_FALSE(res);
  16373. }
  16374. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16375. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16376. // CA that failed to come through fails verification instead of trusting them.
  16377. // (wolfSSL does not list the system CAs it loaded.)
  16378. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16379. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16380. ASSERT_TRUE(svr.is_valid());
  16381. auto port = svr.bind_to_any_port("127.0.0.1");
  16382. ASSERT_LT(0, port);
  16383. thread t = thread([&] { svr.listen_after_bind(); });
  16384. auto se = detail::scope_exit([&] {
  16385. svr.stop();
  16386. t.join();
  16387. ASSERT_FALSE(svr.is_running());
  16388. });
  16389. svr.wait_until_ready();
  16390. // The CAs a client trusts once its first request has loaded them
  16391. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16392. Client cli("https://127.0.0.1:" + std::to_string(port));
  16393. setup(cli);
  16394. cli.Get("/");
  16395. return tls::get_ca_names(cli.tls_context()).size();
  16396. };
  16397. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16398. EXPECT_EQ(0u,
  16399. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16400. }
  16401. #endif
  16402. // A TLS setting changed between requests applies to the next one, not just to
  16403. // the next connection
  16404. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16405. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16406. ASSERT_TRUE(svr.is_valid());
  16407. svr.Get("/", [](const Request &req, Response &res) {
  16408. res.set_content(std::to_string(req.remote_port), "text/plain");
  16409. });
  16410. auto port = svr.bind_to_any_port("127.0.0.1");
  16411. ASSERT_LT(0, port);
  16412. thread t = thread([&] { svr.listen_after_bind(); });
  16413. auto se = detail::scope_exit([&] {
  16414. svr.stop();
  16415. t.join();
  16416. ASSERT_FALSE(svr.is_running());
  16417. });
  16418. svr.wait_until_ready();
  16419. SSLClient cli("127.0.0.1", port);
  16420. cli.set_keep_alive(true);
  16421. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16422. cli.enable_server_certificate_verification(false);
  16423. // The port the request went out from, so a new one means a new connection
  16424. auto client_port = [&] {
  16425. auto res = cli.Get("/");
  16426. return res ? res->body : std::string();
  16427. };
  16428. auto last = client_port();
  16429. ASSERT_FALSE(last.empty());
  16430. // Setting a value it already has keeps the connection
  16431. cli.enable_server_certificate_verification(false);
  16432. cli.enable_server_hostname_verification(true);
  16433. EXPECT_EQ(last, client_port());
  16434. cli.enable_server_certificate_verification(true);
  16435. auto res = cli.Get("/");
  16436. EXPECT_FALSE(res);
  16437. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16438. std::string ca;
  16439. read_file(SERVER_CERT2_FILE, ca);
  16440. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16441. last = client_port();
  16442. ASSERT_FALSE(last.empty());
  16443. std::vector<std::function<void()>> setters = {
  16444. [&] { cli.enable_server_hostname_verification(false); },
  16445. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16446. [&] {
  16447. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16448. },
  16449. [&] {
  16450. cli.set_server_certificate_verifier(
  16451. [](const tls::VerifyContext &) { return true; });
  16452. },
  16453. [&] {
  16454. cli.set_session_verifier(
  16455. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16456. },
  16457. };
  16458. for (const auto &setter : setters) {
  16459. setter();
  16460. auto next = client_port();
  16461. ASSERT_FALSE(next.empty());
  16462. EXPECT_NE(last, next);
  16463. last = next;
  16464. }
  16465. cli.set_session_verifier(
  16466. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16467. auto handle = cli.open_stream("GET", "/");
  16468. EXPECT_FALSE(handle.is_valid());
  16469. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16470. }
  16471. // A PEM given to create_ca_store() needs no NUL after it
  16472. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16473. std::string pem;
  16474. read_file(SERVER_CERT2_FILE, pem);
  16475. auto buf = pem + "X";
  16476. auto store = tls::create_ca_store(buf.data(), pem.size());
  16477. EXPECT_TRUE(store != nullptr);
  16478. SSLClient cli("localhost");
  16479. cli.set_ca_cert_store(store);
  16480. }
  16481. // enable_system_ca(false) prevents system CA loading entirely
  16482. TEST(SSLClientTest, DisableSystemCa_Online) {
  16483. SSLClient cli("google.com");
  16484. cli.enable_system_ca(false);
  16485. cli.enable_server_certificate_verification(true);
  16486. auto res = cli.Get("/");
  16487. ASSERT_FALSE(res);
  16488. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16489. // itself when the CA chain is empty
  16490. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16491. res.error() == Error::SSLConnection);
  16492. }
  16493. // The universal Client forwards enable_system_ca()
  16494. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16495. std::string cert;
  16496. read_file(SERVER_CERT2_FILE, cert);
  16497. Client cli("https://google.com");
  16498. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16499. cli.enable_system_ca(true);
  16500. cli.enable_server_certificate_verification(true);
  16501. auto res = cli.Get("/");
  16502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16503. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  16504. }
  16505. // The system CA policy must carry over to the client created internally for
  16506. // following a cross-host HTTPS redirect
  16507. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16508. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16509. ASSERT_TRUE(svr.is_valid());
  16510. svr.Get("/index", [&](const Request &, Response &res) {
  16511. res.set_redirect("https://www.google.com/");
  16512. });
  16513. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16514. auto se = detail::scope_exit([&] {
  16515. svr.stop();
  16516. t.join();
  16517. ASSERT_FALSE(svr.is_running());
  16518. });
  16519. svr.wait_until_ready();
  16520. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16521. std::string cert;
  16522. read_file(SERVER_CERT2_FILE, cert);
  16523. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16524. cli.enable_system_ca(true);
  16525. cli.enable_server_certificate_verification(true);
  16526. cli.set_follow_location(true);
  16527. cli.set_connection_timeout(30);
  16528. // Receiving any response proves the redirect client completed the TLS
  16529. // handshake with a system-CA-signed host
  16530. auto res = cli.Get("/index");
  16531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16532. }
  16533. TEST(MultipartFormDataTest, LargeData) {
  16534. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16535. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16536. const ContentReader &content_reader) {
  16537. if (req.is_multipart_form_data()) {
  16538. std::vector<FormData> items;
  16539. content_reader(
  16540. [&](const FormData &file) {
  16541. items.push_back(file);
  16542. return true;
  16543. },
  16544. [&](const char *data, size_t data_length) {
  16545. items.back().content.append(data, data_length);
  16546. return true;
  16547. });
  16548. EXPECT_TRUE(std::string(items[0].name) == "document");
  16549. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16550. EXPECT_TRUE(items[0].filename == "2MB_data");
  16551. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16552. EXPECT_TRUE(items[1].name == "hello");
  16553. EXPECT_TRUE(items[1].content == "world");
  16554. EXPECT_TRUE(items[1].filename == "");
  16555. EXPECT_TRUE(items[1].content_type == "");
  16556. } else {
  16557. std::string body;
  16558. content_reader([&](const char *data, size_t data_length) {
  16559. body.append(data, data_length);
  16560. return true;
  16561. });
  16562. }
  16563. });
  16564. auto port = svr.bind_to_any_port(HOST);
  16565. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16566. auto se = detail::scope_exit([&] {
  16567. svr.stop();
  16568. t.join();
  16569. ASSERT_FALSE(svr.is_running());
  16570. });
  16571. svr.wait_until_ready();
  16572. {
  16573. std::string data(1024 * 1024 * 2, '.');
  16574. std::stringstream buffer;
  16575. buffer << data;
  16576. SSLClient cli(HOST, port);
  16577. cli.enable_server_certificate_verification(false);
  16578. UploadFormDataItems items{
  16579. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16580. {"hello", "world", "", ""},
  16581. };
  16582. auto res = cli.Post("/post", items);
  16583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16584. ASSERT_EQ(StatusCode::OK_200, res->status);
  16585. }
  16586. }
  16587. TEST(MultipartFormDataTest, DataProviderItems) {
  16588. std::random_device seed_gen;
  16589. std::mt19937 random(seed_gen());
  16590. std::string rand1;
  16591. rand1.resize(1000);
  16592. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16593. std::string rand2;
  16594. rand2.resize(3000);
  16595. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16596. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16597. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16598. const ContentReader &content_reader) {
  16599. ASSERT_FALSE(req.is_multipart_form_data());
  16600. std::string body;
  16601. content_reader([&](const char *data, size_t data_length) {
  16602. body.append(data, data_length);
  16603. return true;
  16604. });
  16605. EXPECT_EQ(body, "");
  16606. });
  16607. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16608. const ContentReader &content_reader) {
  16609. ASSERT_TRUE(req.is_multipart_form_data());
  16610. std::vector<FormData> items;
  16611. content_reader(
  16612. [&](const FormData &file) {
  16613. items.push_back(file);
  16614. return true;
  16615. },
  16616. [&](const char *data, size_t data_length) {
  16617. items.back().content.append(data, data_length);
  16618. return true;
  16619. });
  16620. ASSERT_TRUE(items.size() == 2);
  16621. EXPECT_EQ(std::string(items[0].name), "name1");
  16622. EXPECT_EQ(items[0].content, "Testing123");
  16623. EXPECT_EQ(items[0].filename, "filename1");
  16624. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16625. EXPECT_EQ(items[1].name, "name2");
  16626. EXPECT_EQ(items[1].content, "Testing456");
  16627. EXPECT_EQ(items[1].filename, "");
  16628. EXPECT_EQ(items[1].content_type, "");
  16629. });
  16630. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16631. const ContentReader &content_reader) {
  16632. ASSERT_TRUE(req.is_multipart_form_data());
  16633. std::vector<FormData> items;
  16634. content_reader(
  16635. [&](const FormData &file) {
  16636. items.push_back(file);
  16637. return true;
  16638. },
  16639. [&](const char *data, size_t data_length) {
  16640. items.back().content.append(data, data_length);
  16641. return true;
  16642. });
  16643. ASSERT_TRUE(items.size() == 2);
  16644. EXPECT_EQ(items[0].name, "name3");
  16645. EXPECT_EQ(items[0].content, rand1);
  16646. EXPECT_EQ(items[0].filename, "filename3");
  16647. EXPECT_EQ(items[0].content_type, "");
  16648. EXPECT_EQ(items[1].name, "name4");
  16649. EXPECT_EQ(items[1].content, rand2);
  16650. EXPECT_EQ(items[1].filename, "filename4");
  16651. EXPECT_EQ(items[1].content_type, "");
  16652. });
  16653. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16654. const ContentReader &content_reader) {
  16655. ASSERT_TRUE(req.is_multipart_form_data());
  16656. std::vector<FormData> items;
  16657. content_reader(
  16658. [&](const FormData &file) {
  16659. items.push_back(file);
  16660. return true;
  16661. },
  16662. [&](const char *data, size_t data_length) {
  16663. items.back().content.append(data, data_length);
  16664. return true;
  16665. });
  16666. ASSERT_TRUE(items.size() == 4);
  16667. EXPECT_EQ(std::string(items[0].name), "name1");
  16668. EXPECT_EQ(items[0].content, "Testing123");
  16669. EXPECT_EQ(items[0].filename, "filename1");
  16670. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16671. EXPECT_EQ(items[1].name, "name2");
  16672. EXPECT_EQ(items[1].content, "Testing456");
  16673. EXPECT_EQ(items[1].filename, "");
  16674. EXPECT_EQ(items[1].content_type, "");
  16675. EXPECT_EQ(items[2].name, "name3");
  16676. EXPECT_EQ(items[2].content, rand1);
  16677. EXPECT_EQ(items[2].filename, "filename3");
  16678. EXPECT_EQ(items[2].content_type, "");
  16679. EXPECT_EQ(items[3].name, "name4");
  16680. EXPECT_EQ(items[3].content, rand2);
  16681. EXPECT_EQ(items[3].filename, "filename4");
  16682. EXPECT_EQ(items[3].content_type, "");
  16683. });
  16684. auto port = svr.bind_to_any_port("localhost");
  16685. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16686. auto se = detail::scope_exit([&] {
  16687. svr.stop();
  16688. t.join();
  16689. ASSERT_FALSE(svr.is_running());
  16690. });
  16691. svr.wait_until_ready();
  16692. {
  16693. SSLClient cli("localhost", port);
  16694. cli.enable_server_certificate_verification(false);
  16695. UploadFormDataItems items{
  16696. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16697. {"name2", "Testing456", "", ""}, // not a file
  16698. };
  16699. {
  16700. auto res = cli.Post("/post-none", {}, {}, {});
  16701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16702. ASSERT_EQ(StatusCode::OK_200, res->status);
  16703. }
  16704. FormDataProviderItems providers;
  16705. {
  16706. auto res =
  16707. cli.Post("/post-items", {}, items, providers); // empty providers
  16708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16709. ASSERT_EQ(StatusCode::OK_200, res->status);
  16710. }
  16711. providers.push_back({"name3",
  16712. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16713. // test the offset is given correctly at each step
  16714. if (!offset)
  16715. sink.os.write(rand1.data(), 30);
  16716. else if (offset == 30)
  16717. sink.os.write(rand1.data() + 30, 300);
  16718. else if (offset == 330)
  16719. sink.os.write(rand1.data() + 330, 670);
  16720. else if (offset == rand1.size())
  16721. sink.done();
  16722. return true;
  16723. },
  16724. "filename3",
  16725. {}});
  16726. providers.push_back({"name4",
  16727. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16728. // test the offset is given correctly at each step
  16729. if (!offset)
  16730. sink.os.write(rand2.data(), 2000);
  16731. else if (offset == 2000)
  16732. sink.os.write(rand2.data() + 2000, 1);
  16733. else if (offset == 2001)
  16734. sink.os.write(rand2.data() + 2001, 999);
  16735. else if (offset == rand2.size())
  16736. sink.done();
  16737. return true;
  16738. },
  16739. "filename4",
  16740. {}});
  16741. {
  16742. auto res = cli.Post("/post-providers", {}, {}, providers);
  16743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16744. ASSERT_EQ(StatusCode::OK_200, res->status);
  16745. }
  16746. {
  16747. auto res = cli.Post("/post-both", {}, items, providers);
  16748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16749. ASSERT_EQ(StatusCode::OK_200, res->status);
  16750. }
  16751. }
  16752. }
  16753. TEST(MultipartFormDataTest, BadHeader) {
  16754. Server svr;
  16755. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16756. res.set_content("ok", "text/plain");
  16757. });
  16758. thread t = thread([&] { svr.listen(HOST, PORT); });
  16759. auto se = detail::scope_exit([&] {
  16760. svr.stop();
  16761. t.join();
  16762. ASSERT_FALSE(svr.is_running());
  16763. });
  16764. svr.wait_until_ready();
  16765. const std::string body =
  16766. "This is the preamble. It is to be ignored, though it\r\n"
  16767. "is a handy place for composition agents to include an\r\n"
  16768. "explanatory note to non-MIME conformant readers.\r\n"
  16769. "\r\n"
  16770. "\r\n"
  16771. "--simple boundary\r\n"
  16772. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16773. ": BAD...\r\n"
  16774. "\r\n"
  16775. "value1\r\n"
  16776. "--simple boundary\r\n"
  16777. "Content-Disposition: form-data; name=\"field2\"; "
  16778. "filename=\"example.txt\"\r\n"
  16779. "\r\n"
  16780. "value2\r\n"
  16781. "--simple boundary--\r\n"
  16782. "This is the epilogue. It is also to be ignored.\r\n";
  16783. std::string content_type =
  16784. R"(multipart/form-data; boundary="simple boundary")";
  16785. Client cli(HOST, PORT);
  16786. auto res = cli.Post("/post", body, content_type.c_str());
  16787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16788. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16789. }
  16790. TEST(MultipartFormDataTest, WithPreamble) {
  16791. Server svr;
  16792. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16793. res.set_content("ok", "text/plain");
  16794. });
  16795. thread t = thread([&] { svr.listen(HOST, PORT); });
  16796. auto se = detail::scope_exit([&] {
  16797. svr.stop();
  16798. t.join();
  16799. ASSERT_FALSE(svr.is_running());
  16800. });
  16801. svr.wait_until_ready();
  16802. const std::string body =
  16803. "This is the preamble. It is to be ignored, though it\r\n"
  16804. "is a handy place for composition agents to include an\r\n"
  16805. "explanatory note to non-MIME conformant readers.\r\n"
  16806. "\r\n"
  16807. "\r\n"
  16808. "--simple boundary\r\n"
  16809. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16810. "\r\n"
  16811. "value1\r\n"
  16812. "--simple boundary\r\n"
  16813. "Content-Disposition: form-data; name=\"field2\"; "
  16814. "filename=\"example.txt\"\r\n"
  16815. "\r\n"
  16816. "value2\r\n"
  16817. "--simple boundary--\r\n"
  16818. "This is the epilogue. It is also to be ignored.\r\n";
  16819. std::string content_type =
  16820. R"(multipart/form-data; boundary="simple boundary")";
  16821. Client cli(HOST, PORT);
  16822. auto res = cli.Post("/post", body, content_type.c_str());
  16823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16824. EXPECT_EQ(StatusCode::OK_200, res->status);
  16825. }
  16826. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16827. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16828. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16829. const ContentReader &content_reader) {
  16830. if (req.is_multipart_form_data()) {
  16831. std::vector<FormData> items;
  16832. content_reader(
  16833. [&](const FormData &file) {
  16834. items.push_back(file);
  16835. return true;
  16836. },
  16837. [&](const char *data, size_t data_length) {
  16838. items.back().content.append(data, data_length);
  16839. return true;
  16840. });
  16841. EXPECT_TRUE(std::string(items[0].name) == "document");
  16842. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16843. EXPECT_TRUE(items[0].filename == "2MB_data");
  16844. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16845. EXPECT_TRUE(items[1].name == "hello");
  16846. EXPECT_TRUE(items[1].content == "world");
  16847. EXPECT_TRUE(items[1].filename == "");
  16848. EXPECT_TRUE(items[1].content_type == "");
  16849. } else {
  16850. std::string body;
  16851. content_reader([&](const char *data, size_t data_length) {
  16852. body.append(data, data_length);
  16853. return true;
  16854. });
  16855. }
  16856. });
  16857. auto port = svr.bind_to_any_port("localhost");
  16858. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16859. auto se = detail::scope_exit([&] {
  16860. svr.stop();
  16861. t.join();
  16862. ASSERT_FALSE(svr.is_running());
  16863. });
  16864. svr.wait_until_ready();
  16865. {
  16866. std::string data(1024 * 1024 * 2, '.');
  16867. std::stringstream buffer;
  16868. buffer << data;
  16869. SSLClient cli("localhost", port);
  16870. cli.enable_server_certificate_verification(false);
  16871. UploadFormDataItems items{
  16872. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16873. {"hello", "world", "", ""},
  16874. };
  16875. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16877. ASSERT_EQ(StatusCode::OK_200, res->status);
  16878. }
  16879. }
  16880. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16881. std::string data(1024 * 1024 * 2, '&');
  16882. std::stringstream buffer;
  16883. buffer << data;
  16884. Client cli("https://localhost:8080");
  16885. UploadFormDataItems items{
  16886. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16887. {"hello", "world", "", ""},
  16888. };
  16889. for (const char &c : " \t\r\n") {
  16890. auto res =
  16891. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16892. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16893. ASSERT_FALSE(res);
  16894. }
  16895. }
  16896. TEST(MultipartFormDataTest, PutFormData) {
  16897. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16898. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16899. const ContentReader &content_reader) {
  16900. if (req.is_multipart_form_data()) {
  16901. std::vector<FormData> items;
  16902. content_reader(
  16903. [&](const FormData &file) {
  16904. items.push_back(file);
  16905. return true;
  16906. },
  16907. [&](const char *data, size_t data_length) {
  16908. items.back().content.append(data, data_length);
  16909. return true;
  16910. });
  16911. EXPECT_TRUE(std::string(items[0].name) == "document");
  16912. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16913. EXPECT_TRUE(items[0].filename == "2MB_data");
  16914. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16915. EXPECT_TRUE(items[1].name == "hello");
  16916. EXPECT_TRUE(items[1].content == "world");
  16917. EXPECT_TRUE(items[1].filename == "");
  16918. EXPECT_TRUE(items[1].content_type == "");
  16919. } else {
  16920. std::string body;
  16921. content_reader([&](const char *data, size_t data_length) {
  16922. body.append(data, data_length);
  16923. return true;
  16924. });
  16925. }
  16926. });
  16927. auto port = svr.bind_to_any_port("localhost");
  16928. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16929. auto se = detail::scope_exit([&] {
  16930. svr.stop();
  16931. t.join();
  16932. ASSERT_FALSE(svr.is_running());
  16933. });
  16934. svr.wait_until_ready();
  16935. {
  16936. std::string data(1024 * 1024 * 2, '&');
  16937. std::stringstream buffer;
  16938. buffer << data;
  16939. SSLClient cli("localhost", port);
  16940. cli.enable_server_certificate_verification(false);
  16941. UploadFormDataItems items{
  16942. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16943. {"hello", "world", "", ""},
  16944. };
  16945. auto res = cli.Put("/put", items);
  16946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16947. ASSERT_EQ(StatusCode::OK_200, res->status);
  16948. }
  16949. }
  16950. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16952. svr.Put("/put_customboundary",
  16953. [&](const Request &req, const Response & /*res*/,
  16954. const ContentReader &content_reader) {
  16955. if (req.is_multipart_form_data()) {
  16956. std::vector<FormData> items;
  16957. content_reader(
  16958. [&](const FormData &file) {
  16959. items.push_back(file);
  16960. return true;
  16961. },
  16962. [&](const char *data, size_t data_length) {
  16963. items.back().content.append(data, data_length);
  16964. return true;
  16965. });
  16966. EXPECT_TRUE(std::string(items[0].name) == "document");
  16967. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16968. EXPECT_TRUE(items[0].filename == "2MB_data");
  16969. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16970. EXPECT_TRUE(items[1].name == "hello");
  16971. EXPECT_TRUE(items[1].content == "world");
  16972. EXPECT_TRUE(items[1].filename == "");
  16973. EXPECT_TRUE(items[1].content_type == "");
  16974. } else {
  16975. std::string body;
  16976. content_reader([&](const char *data, size_t data_length) {
  16977. body.append(data, data_length);
  16978. return true;
  16979. });
  16980. }
  16981. });
  16982. auto port = svr.bind_to_any_port("localhost");
  16983. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16984. auto se = detail::scope_exit([&] {
  16985. svr.stop();
  16986. t.join();
  16987. ASSERT_FALSE(svr.is_running());
  16988. });
  16989. svr.wait_until_ready();
  16990. {
  16991. std::string data(1024 * 1024 * 2, '&');
  16992. std::stringstream buffer;
  16993. buffer << data;
  16994. SSLClient cli("localhost", port);
  16995. cli.enable_server_certificate_verification(false);
  16996. UploadFormDataItems items{
  16997. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16998. {"hello", "world", "", ""},
  16999. };
  17000. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  17001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17002. ASSERT_EQ(StatusCode::OK_200, res->status);
  17003. }
  17004. }
  17005. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  17006. std::string data(1024 * 1024 * 2, '&');
  17007. std::stringstream buffer;
  17008. buffer << data;
  17009. Client cli("https://localhost:8080");
  17010. cli.enable_server_certificate_verification(false);
  17011. UploadFormDataItems items{
  17012. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17013. {"hello", "world", "", ""},
  17014. };
  17015. for (const char &c : " \t\r\n") {
  17016. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  17017. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17018. ASSERT_FALSE(res);
  17019. }
  17020. }
  17021. TEST(MultipartFormDataTest, AlternateFilename) {
  17022. auto handled = false;
  17023. Server svr;
  17024. svr.Post("/test", [&](const Request &req, Response &res) {
  17025. ASSERT_EQ(2u, req.form.files.size());
  17026. ASSERT_EQ(1u, req.form.fields.size());
  17027. // Test files
  17028. const auto &file1 = req.form.get_file("file1");
  17029. ASSERT_EQ("file1", file1.name);
  17030. ASSERT_EQ("A.txt", file1.filename);
  17031. ASSERT_EQ("text/plain", file1.content_type);
  17032. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  17033. const auto &file2 = req.form.get_file("file2");
  17034. ASSERT_EQ("file2", file2.name);
  17035. ASSERT_EQ("a.html", file2.filename);
  17036. ASSERT_EQ("text/html", file2.content_type);
  17037. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  17038. file2.content);
  17039. // Test text field
  17040. const auto &text = req.form.get_field("text");
  17041. ASSERT_EQ("text default", text);
  17042. res.set_content("ok", "text/plain");
  17043. handled = true;
  17044. });
  17045. thread t = thread([&] { svr.listen(HOST, PORT); });
  17046. auto se = detail::scope_exit([&] {
  17047. svr.stop();
  17048. t.join();
  17049. ASSERT_FALSE(svr.is_running());
  17050. ASSERT_TRUE(handled);
  17051. });
  17052. svr.wait_until_ready();
  17053. auto req = "POST /test HTTP/1.1\r\n"
  17054. "Host: localhost\r\n"
  17055. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17056. "Content-Length: 399\r\n"
  17057. "\r\n"
  17058. "----------\r\n"
  17059. "Content-Disposition: form-data; name=\"text\"\r\n"
  17060. "\r\n"
  17061. "text default\r\n"
  17062. "----------\r\n"
  17063. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  17064. "filename=\"a.txt\"; name=\"file1\"\r\n"
  17065. "Content-Type: text/plain\r\n"
  17066. "\r\n"
  17067. "Content of a.txt.\r\n"
  17068. "\r\n"
  17069. "----------\r\n"
  17070. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17071. "\"a.html\"\r\n"
  17072. "Content-Type: text/html\r\n"
  17073. "\r\n"
  17074. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17075. "\r\n"
  17076. "------------\r\n";
  17077. ASSERT_TRUE(send_request(1, req));
  17078. }
  17079. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17080. auto handled = false;
  17081. Server svr;
  17082. svr.Post("/test", [&](const Request &req, Response &res) {
  17083. // Case-insensitive "utf-8''" prefix with a long value
  17084. const auto &file = req.form.get_file("file1");
  17085. ASSERT_EQ("file1", file.name);
  17086. // 8000 chars exercises both the Content-Disposition parser and the
  17087. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17088. // Prior to the fix, std::regex_match on this header would cause O(N)
  17089. // stack recursion in libstdc++, leading to SIGSEGV.
  17090. std::string expected_filename(8000, 'A');
  17091. ASSERT_EQ(expected_filename, file.filename);
  17092. res.set_content("ok", "text/plain");
  17093. handled = true;
  17094. });
  17095. thread t = thread([&] { svr.listen(HOST, PORT); });
  17096. auto se = detail::scope_exit([&] {
  17097. svr.stop();
  17098. t.join();
  17099. ASSERT_FALSE(svr.is_running());
  17100. ASSERT_TRUE(handled);
  17101. });
  17102. svr.wait_until_ready();
  17103. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17104. // Regression test for GHSA-qq6v-r583-3h69
  17105. std::string long_filename(8000, 'A');
  17106. std::string body = "----------\r\n"
  17107. "Content-Disposition: form-data; name=\"file1\"; "
  17108. "filename*=\"Utf-8''" +
  17109. long_filename +
  17110. "\"\r\n"
  17111. "\r\n"
  17112. "hello\r\n"
  17113. "------------\r\n";
  17114. auto req = "POST /test HTTP/1.1\r\n"
  17115. "Host: localhost\r\n"
  17116. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17117. "Content-Length: " +
  17118. std::to_string(body.size()) + "\r\n\r\n" + body;
  17119. ASSERT_TRUE(send_request(1, req));
  17120. }
  17121. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17122. auto handled = false;
  17123. Server svr;
  17124. svr.Post("/test", [&](const Request &req, Response &) {
  17125. ASSERT_EQ(2u, req.form.fields.size());
  17126. const auto &text1 = req.form.get_field("text1");
  17127. ASSERT_EQ("text1", text1);
  17128. const auto &text2 = req.form.get_field("text2");
  17129. ASSERT_EQ("text2", text2);
  17130. handled = true;
  17131. });
  17132. thread t = thread([&] { svr.listen(HOST, PORT); });
  17133. auto se = detail::scope_exit([&] {
  17134. svr.stop();
  17135. t.join();
  17136. ASSERT_FALSE(svr.is_running());
  17137. ASSERT_TRUE(handled);
  17138. });
  17139. svr.wait_until_ready();
  17140. auto req = "POST /test HTTP/1.1\r\n"
  17141. "Host: localhost\r\n"
  17142. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17143. "Content-Length: 146\r\n"
  17144. "\r\n----------\r\n"
  17145. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17146. "\r\n"
  17147. "text1"
  17148. "\r\n----------\r\n"
  17149. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17150. "\r\n"
  17151. "text2"
  17152. "\r\n------------";
  17153. std::string response;
  17154. ASSERT_TRUE(send_request(1, req, &response));
  17155. ASSERT_EQ("200", response.substr(9, 3));
  17156. }
  17157. TEST(MultipartFormDataTest, ContentLength) {
  17158. auto handled = false;
  17159. Server svr;
  17160. svr.Post("/test", [&](const Request &req, Response &) {
  17161. ASSERT_EQ(2u, req.form.fields.size());
  17162. const auto &text1 = req.form.get_field("text1");
  17163. ASSERT_EQ("text1", text1);
  17164. const auto &text2 = req.form.get_field("text2");
  17165. ASSERT_EQ("text2", text2);
  17166. handled = true;
  17167. });
  17168. thread t = thread([&] { svr.listen(HOST, PORT); });
  17169. auto se = detail::scope_exit([&] {
  17170. svr.stop();
  17171. t.join();
  17172. ASSERT_FALSE(svr.is_running());
  17173. ASSERT_TRUE(handled);
  17174. });
  17175. svr.wait_until_ready();
  17176. auto req = "POST /test HTTP/1.1\r\n"
  17177. "Host: localhost\r\n"
  17178. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17179. "Content-Length: 167\r\n"
  17180. "\r\n----------\r\n"
  17181. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17182. "Content-Length: 5\r\n"
  17183. "\r\n"
  17184. "text1"
  17185. "\r\n----------\r\n"
  17186. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17187. "\r\n"
  17188. "text2"
  17189. "\r\n------------\r\n";
  17190. std::string response;
  17191. ASSERT_TRUE(send_request(1, req, &response));
  17192. ASSERT_EQ("200", response.substr(9, 3));
  17193. }
  17194. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17195. auto handled = false;
  17196. Server svr;
  17197. svr.Post("/test", [&](const Request &req, Response &) {
  17198. ASSERT_EQ(2u, req.form.fields.size());
  17199. const auto &text1 = req.form.get_field("text1");
  17200. ASSERT_EQ("text1", text1);
  17201. // TODO: Add header access for text fields if needed
  17202. const auto &text2 = req.form.get_field("text2");
  17203. ASSERT_EQ("text2", text2);
  17204. // TODO: Header access for text fields needs to be implemented
  17205. // auto &headers = it->second.headers;
  17206. // ASSERT_EQ(3U, headers.size());
  17207. // auto custom_header = headers.find("x-whatever");
  17208. // ASSERT_TRUE(custom_header != headers.end());
  17209. // ASSERT_NE("customvalue", custom_header->second);
  17210. // ASSERT_EQ("CustomValue", custom_header->second);
  17211. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17212. handled = true;
  17213. });
  17214. thread t = thread([&] { svr.listen(HOST, PORT); });
  17215. auto se = detail::scope_exit([&] {
  17216. svr.stop();
  17217. t.join();
  17218. ASSERT_FALSE(svr.is_running());
  17219. ASSERT_TRUE(handled);
  17220. });
  17221. svr.wait_until_ready();
  17222. auto req = "POST /test HTTP/1.1\r\n"
  17223. "Host: localhost\r\n"
  17224. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17225. "Content-Length: 232\r\n"
  17226. "\r\n----------\r\n"
  17227. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17228. "Content-Length: 5\r\n"
  17229. "X-Test: 1\r\n"
  17230. "\r\n"
  17231. "text1"
  17232. "\r\n----------\r\n"
  17233. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17234. "Content-Type: text/plain\r\n"
  17235. "X-Whatever: CustomValue\r\n"
  17236. "\r\n"
  17237. "text2"
  17238. "\r\n------------\r\n"
  17239. "That should be disregarded. Not even read";
  17240. std::string response;
  17241. ASSERT_TRUE(send_request(1, req, &response));
  17242. ASSERT_EQ("200", response.substr(9, 3));
  17243. }
  17244. TEST(MultipartFormDataTest, LargeHeader) {
  17245. auto handled = false;
  17246. Server svr;
  17247. svr.Post("/test", [&](const Request &req, Response &) {
  17248. ASSERT_EQ(1u, req.form.fields.size());
  17249. const auto &text = req.form.get_field("name1");
  17250. ASSERT_EQ("text1", text);
  17251. handled = true;
  17252. });
  17253. thread t = thread([&] { svr.listen(HOST, PORT); });
  17254. auto se = detail::scope_exit([&] {
  17255. svr.stop();
  17256. t.join();
  17257. ASSERT_FALSE(svr.is_running());
  17258. ASSERT_TRUE(handled);
  17259. });
  17260. svr.wait_until_ready();
  17261. auto boundary = std::string("cpp-httplib-multipart-data");
  17262. std::string content = "--" + boundary +
  17263. "\r\n"
  17264. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17265. "\r\n"
  17266. "text1\r\n"
  17267. "--" +
  17268. boundary + "--\r\n";
  17269. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17270. "Host: localhost\r\n"
  17271. "Content-Type: multipart/form-data;boundary=" +
  17272. boundary +
  17273. "\r\n"
  17274. "Content-Length: " +
  17275. std::to_string(content.size()) +
  17276. "\r\n"
  17277. "Dummy-Header: ";
  17278. std::string header_suffix = "\r\n"
  17279. "\r\n";
  17280. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17281. size_t header_dummy_size =
  17282. read_buff_size -
  17283. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17284. auto header_dummy = std::string(header_dummy_size, '@');
  17285. auto req = header_prefix + header_dummy + header_suffix + content;
  17286. std::string response;
  17287. ASSERT_TRUE(send_request(1, req, &response));
  17288. ASSERT_EQ("200", response.substr(9, 3));
  17289. }
  17290. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17291. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17292. // (not chunked Transfer-Encoding) after the streaming refactor.
  17293. auto handled = false;
  17294. Server svr;
  17295. svr.Post("/upload", [&](const Request &req, Response &res) {
  17296. auto cl_it = req.headers.find("Content-Length");
  17297. EXPECT_TRUE(cl_it != req.headers.end());
  17298. auto te_it = req.headers.find("Transfer-Encoding");
  17299. EXPECT_TRUE(te_it == req.headers.end());
  17300. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17301. res.set_content("ok", "text/plain");
  17302. handled = true;
  17303. });
  17304. auto port = svr.bind_to_any_port(HOST);
  17305. auto t = thread([&] { svr.listen_after_bind(); });
  17306. auto se = detail::scope_exit([&] {
  17307. svr.stop();
  17308. t.join();
  17309. ASSERT_FALSE(svr.is_running());
  17310. ASSERT_TRUE(handled);
  17311. });
  17312. svr.wait_until_ready();
  17313. UploadFormDataItems items = {
  17314. {"field1", "hello", "", "text/plain"},
  17315. {"file1", "world", "test.txt", "application/octet-stream"},
  17316. };
  17317. Client cli(HOST, port);
  17318. auto res = cli.Post("/upload", {}, items);
  17319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17320. EXPECT_EQ(StatusCode::OK_200, res->status);
  17321. }
  17322. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17323. // Verify that make_multipart_content_provider coalesces many small segments
  17324. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17325. constexpr size_t kItemCount = 1000;
  17326. UploadFormDataItems items;
  17327. items.reserve(kItemCount);
  17328. for (size_t i = 0; i < kItemCount; i++) {
  17329. items.push_back(
  17330. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17331. }
  17332. const std::string boundary = "----test-boundary";
  17333. auto content_length = detail::get_multipart_content_length(items, boundary);
  17334. auto provider = detail::make_multipart_content_provider(items, boundary);
  17335. // Drive the provider the same way write_content_with_progress does
  17336. size_t write_count = 0;
  17337. size_t total_bytes = 0;
  17338. DataSink sink;
  17339. size_t offset = 0;
  17340. sink.write = [&](const char *d, size_t l) -> bool {
  17341. (void)d;
  17342. write_count++;
  17343. total_bytes += l;
  17344. offset += l;
  17345. return true;
  17346. };
  17347. sink.is_writable = []() -> bool { return true; };
  17348. while (offset < content_length) {
  17349. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17350. }
  17351. EXPECT_EQ(content_length, total_bytes);
  17352. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17353. // With buffering into 64KB blocks, write_count should be much smaller.
  17354. auto segment_count = 3 * kItemCount + 1;
  17355. EXPECT_LT(write_count, segment_count / 10);
  17356. }
  17357. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17358. // Integration test: send many UploadFormDataItems and verify the server
  17359. // receives all of them correctly (#2410).
  17360. constexpr size_t kItemCount = 500;
  17361. auto handled = false;
  17362. Server svr;
  17363. svr.Post("/upload", [&](const Request &req, Response &res) {
  17364. EXPECT_EQ(kItemCount, req.form.fields.size());
  17365. for (size_t i = 0; i < kItemCount; i++) {
  17366. auto key = "field" + std::to_string(i);
  17367. auto val = "value" + std::to_string(i);
  17368. auto it = req.form.fields.find(key);
  17369. if (it != req.form.fields.end()) {
  17370. EXPECT_EQ(val, it->second.content);
  17371. } else {
  17372. ADD_FAILURE() << "Missing field: " << key;
  17373. }
  17374. }
  17375. res.set_content("ok", "text/plain");
  17376. handled = true;
  17377. });
  17378. auto port = svr.bind_to_any_port(HOST);
  17379. auto t = thread([&] { svr.listen_after_bind(); });
  17380. auto se = detail::scope_exit([&] {
  17381. svr.stop();
  17382. t.join();
  17383. ASSERT_FALSE(svr.is_running());
  17384. ASSERT_TRUE(handled);
  17385. });
  17386. svr.wait_until_ready();
  17387. UploadFormDataItems items;
  17388. items.reserve(kItemCount);
  17389. for (size_t i = 0; i < kItemCount; i++) {
  17390. items.push_back(
  17391. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17392. }
  17393. Client cli(HOST, port);
  17394. auto res = cli.Post("/upload", items);
  17395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17396. EXPECT_EQ(StatusCode::OK_200, res->status);
  17397. }
  17398. TEST(MultipartFormDataTest, MakeFileProvider) {
  17399. // Verify make_file_provider sends a file's contents correctly.
  17400. const std::string file_content(4096, 'Z');
  17401. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17402. {
  17403. std::ofstream ofs(tmp_path, std::ios::binary);
  17404. ofs.write(file_content.data(),
  17405. static_cast<std::streamsize>(file_content.size()));
  17406. }
  17407. auto handled = false;
  17408. Server svr;
  17409. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17410. const ContentReader &content_reader) {
  17411. ASSERT_TRUE(req.is_multipart_form_data());
  17412. std::vector<FormData> items;
  17413. content_reader(
  17414. [&](const FormData &file) {
  17415. items.push_back(file);
  17416. return true;
  17417. },
  17418. [&](const char *data, size_t data_length) {
  17419. items.back().content.append(data, data_length);
  17420. return true;
  17421. });
  17422. ASSERT_EQ(1u, items.size());
  17423. EXPECT_EQ("myfile", items[0].name);
  17424. EXPECT_EQ("data.bin", items[0].filename);
  17425. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17426. EXPECT_EQ(file_content, items[0].content);
  17427. handled = true;
  17428. });
  17429. auto port = svr.bind_to_any_port(HOST);
  17430. auto t = thread([&] { svr.listen_after_bind(); });
  17431. auto se = detail::scope_exit([&] {
  17432. svr.stop();
  17433. t.join();
  17434. ASSERT_FALSE(svr.is_running());
  17435. ASSERT_TRUE(handled);
  17436. std::remove(tmp_path.c_str());
  17437. });
  17438. svr.wait_until_ready();
  17439. FormDataProviderItems providers;
  17440. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17441. "application/octet-stream"));
  17442. Client cli(HOST, port);
  17443. auto res = cli.Post("/upload", {}, {}, providers);
  17444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17445. EXPECT_EQ(StatusCode::OK_200, res->status);
  17446. }
  17447. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17448. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17449. // (100) headers is rejected with a 400 Bad Request response.
  17450. Server svr;
  17451. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17452. res.set_content("ok", "text/plain");
  17453. });
  17454. thread t = thread([&] { svr.listen(HOST, PORT); });
  17455. auto se = detail::scope_exit([&] {
  17456. svr.stop();
  17457. t.join();
  17458. ASSERT_FALSE(svr.is_running());
  17459. });
  17460. svr.wait_until_ready();
  17461. // Build a multipart part with 101 custom headers (exceeding
  17462. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17463. std::stringstream body;
  17464. body << "--simpleboundary\r\n"
  17465. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17466. for (int i = 0; i < 101; i++) {
  17467. body << "X-Custom-Header-" << i << ": value\r\n";
  17468. }
  17469. body << "\r\n"
  17470. << "value1\r\n"
  17471. << "--simpleboundary--\r\n";
  17472. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17473. Client cli(HOST, PORT);
  17474. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17476. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17477. }
  17478. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17479. // A body that never contains the declared boundary must not be accumulated
  17480. // while the parser waits for it. Buffering it would also make every read
  17481. // rescan everything seen so far, which is quadratic in the body size.
  17482. Server svr;
  17483. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17484. res.set_content("ok", "text/plain");
  17485. });
  17486. auto port = svr.bind_to_any_port(HOST);
  17487. thread t = thread([&] { svr.listen_after_bind(); });
  17488. auto se = detail::scope_exit([&] {
  17489. svr.stop();
  17490. t.join();
  17491. ASSERT_FALSE(svr.is_running());
  17492. });
  17493. svr.wait_until_ready();
  17494. Client cli(HOST, port);
  17495. cli.set_read_timeout(60, 0);
  17496. cli.set_write_timeout(60, 0);
  17497. // '-' is the worst case: it matches the first character of the boundary, so
  17498. // every position has to be checked against it.
  17499. auto post_dashes = [&](size_t size) {
  17500. const std::string body(size, '-');
  17501. auto start = std::chrono::steady_clock::now();
  17502. auto res =
  17503. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17504. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17505. std::chrono::steady_clock::now() - start)
  17506. .count();
  17507. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17508. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17509. return ms;
  17510. };
  17511. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17512. // Windows.
  17513. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17514. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17515. // Comparing the two sizes rather than checking an absolute duration keeps
  17516. // this meaningful across build types and CI load, both of which move the
  17517. // absolute numbers by more than an order of magnitude. Four times the bytes
  17518. // costs about four times the time when parsing is linear, and about sixteen
  17519. // times when the body is buffered and rescanned.
  17520. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17521. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17522. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17523. << "ms, which suggests the body is being buffered and rescanned";
  17524. }
  17525. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17526. // A boundary can only be followed by CRLF or by "--", so anything else is
  17527. // malformed no matter what comes next. The parser must say so right away
  17528. // instead of buffering the rest of the declared body.
  17529. Server svr;
  17530. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17531. res.set_content("ok", "text/plain");
  17532. });
  17533. auto port = svr.bind_to_any_port(HOST);
  17534. thread t = thread([&] { svr.listen_after_bind(); });
  17535. auto se = detail::scope_exit([&] {
  17536. svr.stop();
  17537. t.join();
  17538. ASSERT_FALSE(svr.is_running());
  17539. });
  17540. svr.wait_until_ready();
  17541. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17542. // buffers instead of failing would still be waiting for the remaining bytes.
  17543. const std::string body = "--zzzz\r\n"
  17544. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17545. "\r\n"
  17546. "text1"
  17547. "\r\n--zzzzXX";
  17548. const std::string req = "POST /post HTTP/1.1\r\n"
  17549. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17550. "Content-Length: 1048576\r\n"
  17551. "\r\n" +
  17552. body;
  17553. std::string response;
  17554. ASSERT_TRUE(send_request(3, req, &response, port));
  17555. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17556. EXPECT_EQ("400", response.substr(9, 3));
  17557. }
  17558. // Posts a multipart body split into two writes, so that the server sees the
  17559. // split at whatever offset the caller chose, and expects the single "text1"
  17560. // field to come through.
  17561. static void expect_split_multipart_ok(const std::string &body1,
  17562. const std::string &body2) {
  17563. auto handled = false;
  17564. Server svr;
  17565. svr.Post("/post", [&](const Request &req, Response &) {
  17566. EXPECT_EQ(1u, req.form.fields.size());
  17567. EXPECT_EQ("text1", req.form.get_field("text1"));
  17568. handled = true;
  17569. });
  17570. auto port = svr.bind_to_any_port(HOST);
  17571. thread t = thread([&] { svr.listen_after_bind(); });
  17572. auto se = detail::scope_exit([&] {
  17573. svr.stop();
  17574. t.join();
  17575. ASSERT_FALSE(svr.is_running());
  17576. ASSERT_TRUE(handled);
  17577. });
  17578. svr.wait_until_ready();
  17579. // "Connection: close" makes the server close once it has answered, so the
  17580. // response drain ends immediately instead of idling until the read timeout.
  17581. const std::string head =
  17582. "POST /post HTTP/1.1\r\n"
  17583. "Host: localhost\r\n"
  17584. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17585. "Connection: close\r\n"
  17586. "Content-Length: " +
  17587. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17588. std::string response;
  17589. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17590. ASSERT_GE(response.size(), 12u) << "no response";
  17591. EXPECT_EQ("200", response.substr(9, 3));
  17592. }
  17593. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17594. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17595. // ignored, including when it does not arrive in the same read as the
  17596. // close-delimiter itself.
  17597. expect_split_multipart_ok("--zzzz\r\n"
  17598. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17599. "\r\n"
  17600. "text1"
  17601. "\r\n--zzzz--",
  17602. "\r\nthis epilogue must be ignored\r\n");
  17603. }
  17604. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17605. // The initial boundary may be preceded by a preamble of any length and may
  17606. // straddle a read boundary. Discarding data while waiting for it must not
  17607. // throw away a partial boundary sitting at the end of the buffer.
  17608. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17609. "zz\r\n"
  17610. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17611. "\r\n"
  17612. "text1"
  17613. "\r\n--zzzz--\r\n");
  17614. }
  17615. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17616. // The received boundary was only checked for being non-empty, so it could be
  17617. // as long as a header is allowed to be. The parser scans the body for
  17618. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17619. // costs a nearly full comparison at nearly every position, making the
  17620. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17621. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17622. Server svr;
  17623. svr.Post("/post", [](const Request &req, Response &res) {
  17624. EXPECT_EQ(1u, req.form.fields.size());
  17625. EXPECT_EQ("text1", req.form.get_field("text1"));
  17626. res.set_content("ok", "text/plain");
  17627. });
  17628. auto port = svr.bind_to_any_port(HOST);
  17629. thread t = thread([&] { svr.listen_after_bind(); });
  17630. auto se = detail::scope_exit([&] {
  17631. svr.stop();
  17632. t.join();
  17633. ASSERT_FALSE(svr.is_running());
  17634. });
  17635. svr.wait_until_ready();
  17636. Client cli(HOST, port);
  17637. auto post_with_boundary_of_length = [&](size_t len) {
  17638. const std::string boundary(len, 'a');
  17639. const std::string body =
  17640. "--" + boundary +
  17641. "\r\n"
  17642. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17643. "\r\n"
  17644. "text1"
  17645. "\r\n--" +
  17646. boundary + "--\r\n";
  17647. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17648. };
  17649. auto res = post_with_boundary_of_length(70);
  17650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17651. EXPECT_EQ(StatusCode::OK_200, res->status);
  17652. res = post_with_boundary_of_length(71);
  17653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17654. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17655. }
  17656. TEST(MakeFileBodyTest, Basic) {
  17657. const std::string file_content(4096, 'Z');
  17658. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17659. {
  17660. std::ofstream ofs(tmp_path, std::ios::binary);
  17661. ofs.write(file_content.data(),
  17662. static_cast<std::streamsize>(file_content.size()));
  17663. }
  17664. auto handled = false;
  17665. Server svr;
  17666. svr.Post("/upload", [&](const Request &req, Response &res) {
  17667. EXPECT_EQ(file_content, req.body);
  17668. handled = true;
  17669. res.status = StatusCode::OK_200;
  17670. });
  17671. auto port = svr.bind_to_any_port(HOST);
  17672. auto t = thread([&] { svr.listen_after_bind(); });
  17673. auto se = detail::scope_exit([&] {
  17674. svr.stop();
  17675. t.join();
  17676. ASSERT_FALSE(svr.is_running());
  17677. ASSERT_TRUE(handled);
  17678. std::remove(tmp_path.c_str());
  17679. });
  17680. svr.wait_until_ready();
  17681. auto fb = make_file_body(tmp_path);
  17682. ASSERT_GT(fb.first, 0u);
  17683. Client cli(HOST, port);
  17684. auto res =
  17685. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17687. EXPECT_EQ(StatusCode::OK_200, res->status);
  17688. }
  17689. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17690. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17691. {
  17692. std::ofstream ofs(path, std::ios::binary);
  17693. const std::string content(100, 'A');
  17694. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17695. }
  17696. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17697. auto body = make_file_body(path);
  17698. ASSERT_EQ(100u, body.first);
  17699. ASSERT_TRUE(static_cast<bool>(body.second));
  17700. // Rewritten shorter after its length was measured - and, on a server, after
  17701. // that length has already gone out as Content-Length.
  17702. {
  17703. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17704. const std::string content(10, 'A');
  17705. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17706. }
  17707. std::string written;
  17708. DataSink sink;
  17709. sink.write = [&](const char *d, size_t l) {
  17710. written.append(d, l);
  17711. return true;
  17712. };
  17713. // The provider has to report failure. write_content_with_progress() advances
  17714. // its offset only by what was written, so a provider that returns true
  17715. // without completing the length it promised is called again straight away,
  17716. // and again.
  17717. EXPECT_FALSE(body.second(0, body.first, sink));
  17718. EXPECT_EQ(std::string(10, 'A'), written);
  17719. }
  17720. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17721. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17722. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17723. {
  17724. std::ofstream ofs(path, std::ios::binary);
  17725. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17726. }
  17727. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17728. auto body = make_file_body(path);
  17729. ASSERT_EQ(content.size(), body.first);
  17730. ASSERT_TRUE(static_cast<bool>(body.second));
  17731. std::string written;
  17732. DataSink sink;
  17733. sink.write = [&](const char *d, size_t l) {
  17734. written.append(d, l);
  17735. return true;
  17736. };
  17737. EXPECT_TRUE(body.second(0, body.first, sink));
  17738. EXPECT_EQ(content, written);
  17739. }
  17740. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17741. static constexpr unsigned int number_of_tasks{1000000};
  17742. std::atomic_uint count{0};
  17743. std::unique_ptr<TaskQueue> task_queue{
  17744. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17745. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17746. auto queued = task_queue->enqueue(
  17747. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17748. EXPECT_TRUE(queued);
  17749. }
  17750. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17751. task_queue->shutdown();
  17752. #else
  17753. EXPECT_NO_THROW(task_queue->shutdown());
  17754. #endif
  17755. EXPECT_EQ(number_of_tasks, count.load());
  17756. }
  17757. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17758. static constexpr unsigned int number_of_tasks{1000000};
  17759. static constexpr unsigned int qlimit{2};
  17760. unsigned int queued_count{0};
  17761. std::atomic_uint count{0};
  17762. std::unique_ptr<TaskQueue> task_queue{
  17763. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17764. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17765. if (task_queue->enqueue(
  17766. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17767. queued_count++;
  17768. }
  17769. }
  17770. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17771. task_queue->shutdown();
  17772. #else
  17773. EXPECT_NO_THROW(task_queue->shutdown());
  17774. #endif
  17775. EXPECT_EQ(queued_count, count.load());
  17776. EXPECT_TRUE(queued_count <= number_of_tasks);
  17777. EXPECT_TRUE(queued_count >= qlimit);
  17778. }
  17779. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17780. // Use a short idle timeout so a dynamic thread spawns, times out and
  17781. // exits during the test, and the pool keeps working afterwards.
  17782. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17783. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17784. /*idle_timeout_sec=*/1}};
  17785. std::atomic_uint count{0};
  17786. std::condition_variable cv;
  17787. std::mutex mtx;
  17788. bool release = false;
  17789. // Block the base thread so the second task spawns a dynamic thread.
  17790. EXPECT_TRUE(task_queue->enqueue([&] {
  17791. std::unique_lock<std::mutex> lock(mtx);
  17792. while (!release) {
  17793. cv.wait(lock);
  17794. }
  17795. count++;
  17796. }));
  17797. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17798. // Let the dynamic thread finish its task and exceed the idle timeout.
  17799. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17800. {
  17801. std::unique_lock<std::mutex> lock(mtx);
  17802. release = true;
  17803. }
  17804. cv.notify_all();
  17805. // The pool must still accept and run tasks after the dynamic thread exited.
  17806. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17807. task_queue->shutdown();
  17808. EXPECT_EQ(3u, count.load());
  17809. }
  17810. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17811. static constexpr size_t number_of_tasks{32};
  17812. std::unique_ptr<TaskQueue> task_queue{
  17813. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17814. // Let the base threads go idle so the burst below finds them waiting.
  17815. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17816. std::mutex mtx;
  17817. std::condition_variable cv;
  17818. size_t running = 0;
  17819. bool release = false;
  17820. for (size_t i = 0; i < number_of_tasks; i++) {
  17821. EXPECT_TRUE(task_queue->enqueue([&] {
  17822. std::unique_lock<std::mutex> lock(mtx);
  17823. running++;
  17824. cv.notify_all();
  17825. cv.wait(lock, [&] { return release; });
  17826. }));
  17827. }
  17828. {
  17829. std::unique_lock<std::mutex> lock(mtx);
  17830. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17831. [&] { return running == number_of_tasks; }));
  17832. release = true;
  17833. }
  17834. cv.notify_all();
  17835. task_queue->shutdown();
  17836. }
  17837. TEST(TaskQueueTest, MaxQueuedRequests) {
  17838. static constexpr unsigned int qlimit{3};
  17839. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17840. std::condition_variable sem_cv;
  17841. std::mutex sem_mtx;
  17842. int credits = 0;
  17843. bool queued;
  17844. /* Fill up the queue with tasks that will block until we give them credits to
  17845. * complete. */
  17846. for (unsigned int n = 0; n <= qlimit;) {
  17847. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17848. std::unique_lock<std::mutex> lock(sem_mtx);
  17849. while (credits <= 0) {
  17850. sem_cv.wait(lock);
  17851. }
  17852. /* Consume the credit and signal the test code if they are all gone. */
  17853. if (--credits == 0) { sem_cv.notify_one(); }
  17854. });
  17855. if (n < qlimit) {
  17856. /* The first qlimit enqueues must succeed. */
  17857. EXPECT_TRUE(queued);
  17858. } else {
  17859. /* The last one will succeed only when the worker thread
  17860. * starts and dequeues the first blocking task. Although
  17861. * not necessary for the correctness of this test, we sleep for
  17862. * a short while to avoid busy waiting. */
  17863. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17864. }
  17865. if (queued) { n++; }
  17866. }
  17867. /* Further enqueues must fail since the queue is full. */
  17868. for (auto i = 0; i < 4; i++) {
  17869. queued = task_queue->enqueue([] {});
  17870. EXPECT_FALSE(queued);
  17871. }
  17872. /* Give the credits to allow the previous tasks to complete. */
  17873. {
  17874. std::unique_lock<std::mutex> lock(sem_mtx);
  17875. credits += qlimit + 1;
  17876. }
  17877. sem_cv.notify_all();
  17878. /* Wait for all the credits to be consumed. */
  17879. {
  17880. std::unique_lock<std::mutex> lock(sem_mtx);
  17881. while (credits > 0) {
  17882. sem_cv.wait(lock);
  17883. }
  17884. }
  17885. /* Check that we are able again to enqueue at least qlimit tasks. */
  17886. for (unsigned int i = 0; i < qlimit; i++) {
  17887. queued = task_queue->enqueue([] {});
  17888. EXPECT_TRUE(queued);
  17889. }
  17890. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17891. task_queue->shutdown();
  17892. #else
  17893. EXPECT_NO_THROW(task_queue->shutdown());
  17894. #endif
  17895. }
  17896. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17897. Server svr;
  17898. std::string method;
  17899. std::string body;
  17900. auto has_content_length = false;
  17901. auto has_transfer_encoding = false;
  17902. std::atomic<int> bad_requests{0};
  17903. // Leftover body bytes get parsed as a malformed request and answered with
  17904. // 400
  17905. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17906. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17907. });
  17908. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17909. res.set_redirect("/down", StatusCode::SeeOther_303);
  17910. });
  17911. svr.Get("/down", [&](const Request &req, Response &res) {
  17912. method = req.method;
  17913. body = req.body;
  17914. has_content_length = req.has_header("Content-Length");
  17915. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17916. res.set_content("ok", "text/plain");
  17917. });
  17918. auto port = svr.bind_to_any_port(HOST);
  17919. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17920. auto se = detail::scope_exit([&] {
  17921. svr.stop();
  17922. thread.join();
  17923. ASSERT_FALSE(svr.is_running());
  17924. });
  17925. svr.wait_until_ready();
  17926. const std::string payload = "SECRET-BODY";
  17927. auto check = [&](Client &cli, const Result &res) {
  17928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17929. EXPECT_EQ(StatusCode::OK_200, res->status);
  17930. EXPECT_EQ("ok", res->body);
  17931. EXPECT_EQ("GET", method);
  17932. EXPECT_TRUE(body.empty());
  17933. EXPECT_FALSE(has_content_length);
  17934. EXPECT_FALSE(has_transfer_encoding);
  17935. // Nothing of the original body may be left on the connection
  17936. auto res2 = cli.Get("/down");
  17937. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17938. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17939. EXPECT_EQ("ok", res2->body);
  17940. EXPECT_EQ(0, bad_requests);
  17941. };
  17942. // With content length
  17943. {
  17944. Client cli(HOST, port);
  17945. cli.set_keep_alive(true);
  17946. cli.set_follow_location(true);
  17947. auto res = cli.Post(
  17948. "/up", payload.size(),
  17949. [&](size_t offset, size_t length, DataSink &sink) {
  17950. return sink.write(payload.data() + offset, length);
  17951. },
  17952. "text/plain");
  17953. check(cli, res);
  17954. }
  17955. // Without content length (chunked)
  17956. {
  17957. Client cli(HOST, port);
  17958. cli.set_keep_alive(true);
  17959. cli.set_follow_location(true);
  17960. auto res = cli.Post(
  17961. "/up",
  17962. [&](size_t /*offset*/, DataSink &sink) {
  17963. sink.write(payload.data(), payload.size());
  17964. sink.done();
  17965. return true;
  17966. },
  17967. "text/plain");
  17968. check(cli, res);
  17969. }
  17970. }
  17971. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17972. Server svr;
  17973. std::string target;
  17974. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17975. // Echo the still-encoded name back in the Location
  17976. const std::string prefix = "/start/";
  17977. res.status = StatusCode::Found_302;
  17978. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17979. });
  17980. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17981. target = req.target;
  17982. res.set_content("ok", "text/plain");
  17983. });
  17984. auto port = svr.bind_to_any_port(HOST);
  17985. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17986. auto se = detail::scope_exit([&] {
  17987. svr.stop();
  17988. thread.join();
  17989. ASSERT_FALSE(svr.is_running());
  17990. });
  17991. svr.wait_until_ready();
  17992. // Decoding the Location path would turn the first four into a path
  17993. // separator, a query delimiter, a fragment delimiter and a different
  17994. // percent-encoded octet. The rest must keep reaching the server as they are.
  17995. const std::vector<std::string> names = {
  17996. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17997. };
  17998. for (auto path_encode : {true, false}) {
  17999. Client cli(HOST, port);
  18000. cli.set_follow_location(true);
  18001. cli.set_path_encode(path_encode);
  18002. for (const auto &name : names) {
  18003. target.clear();
  18004. auto res = cli.Get("/start/" + name);
  18005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18006. EXPECT_EQ(StatusCode::OK_200, res->status);
  18007. EXPECT_EQ("/dest/" + name, target);
  18008. }
  18009. }
  18010. }
  18011. TEST(RedirectTest, NotModifiedIsReturned) {
  18012. Server svr;
  18013. svr.Get("/cached", [](const Request &, Response &res) {
  18014. res.status = StatusCode::NotModified_304;
  18015. });
  18016. auto port = svr.bind_to_any_port(HOST);
  18017. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18018. auto se = detail::scope_exit([&] {
  18019. svr.stop();
  18020. thread.join();
  18021. ASSERT_FALSE(svr.is_running());
  18022. });
  18023. svr.wait_until_ready();
  18024. Client cli(HOST, port);
  18025. cli.set_follow_location(true);
  18026. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  18027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18028. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  18029. }
  18030. TEST(RedirectTest, NoLocationIsReturned) {
  18031. Server svr;
  18032. svr.Get("/no-location", [](const Request &, Response &res) {
  18033. res.status = StatusCode::Found_302;
  18034. res.set_content("no location", "text/plain");
  18035. });
  18036. auto port = svr.bind_to_any_port(HOST);
  18037. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18038. auto se = detail::scope_exit([&] {
  18039. svr.stop();
  18040. thread.join();
  18041. ASSERT_FALSE(svr.is_running());
  18042. });
  18043. svr.wait_until_ready();
  18044. Client cli(HOST, port);
  18045. cli.set_follow_location(true);
  18046. auto res = cli.Get("/no-location");
  18047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18048. EXPECT_EQ(StatusCode::Found_302, res->status);
  18049. EXPECT_EQ("no location", res->body);
  18050. // The callbacks see the body of the response that is returned
  18051. auto handler_called = false;
  18052. auto progress_called = false;
  18053. std::string body;
  18054. auto res2 = cli.Get(
  18055. "/no-location",
  18056. [&](const Response &) {
  18057. handler_called = true;
  18058. return true;
  18059. },
  18060. [&](const char *data, size_t data_length) {
  18061. body.append(data, data_length);
  18062. return true;
  18063. },
  18064. [&](size_t, size_t) {
  18065. progress_called = true;
  18066. return true;
  18067. });
  18068. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18069. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18070. EXPECT_TRUE(handler_called);
  18071. EXPECT_TRUE(progress_called);
  18072. EXPECT_EQ("no location", body);
  18073. }
  18074. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18075. Server svr;
  18076. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18077. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18078. });
  18079. svr.Get("/hello", [](const Request &req, Response &res) {
  18080. res.set_content(req.get_param_value("key"), "text/plain");
  18081. });
  18082. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18083. auto se = detail::scope_exit([&] {
  18084. svr.stop();
  18085. thread.join();
  18086. ASSERT_FALSE(svr.is_running());
  18087. });
  18088. svr.wait_until_ready();
  18089. {
  18090. Client cli(HOST, PORT);
  18091. cli.set_follow_location(true);
  18092. auto res = cli.Get("/");
  18093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18094. EXPECT_EQ(StatusCode::OK_200, res->status);
  18095. EXPECT_EQ("val&key2=val2", res->body);
  18096. }
  18097. }
  18098. #endif
  18099. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18100. Server svr;
  18101. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18102. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18103. });
  18104. svr.Get("/hello", [](const Request &req, Response &res) {
  18105. res.set_content(req.get_param_value("key"), "text/plain");
  18106. });
  18107. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18108. auto se = detail::scope_exit([&] {
  18109. svr.stop();
  18110. thread.join();
  18111. ASSERT_FALSE(svr.is_running());
  18112. });
  18113. svr.wait_until_ready();
  18114. {
  18115. Client cli(HOST, PORT);
  18116. cli.set_follow_location(true);
  18117. auto res = cli.Get("/");
  18118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18119. EXPECT_EQ(StatusCode::OK_200, res->status);
  18120. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18121. }
  18122. }
  18123. TEST(RedirectTest, RedirectWithPlusInPath) {
  18124. Server svr;
  18125. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18126. res.set_redirect("/a+b");
  18127. });
  18128. // Route pattern uses regex; escape + as \\+
  18129. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18130. res.set_content(req.path, "text/plain");
  18131. });
  18132. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18133. auto se = detail::scope_exit([&] {
  18134. svr.stop();
  18135. thread.join();
  18136. ASSERT_FALSE(svr.is_running());
  18137. });
  18138. svr.wait_until_ready();
  18139. {
  18140. Client cli(HOST, PORT);
  18141. cli.set_follow_location(true);
  18142. auto res = cli.Get("/");
  18143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18144. EXPECT_EQ(StatusCode::OK_200, res->status);
  18145. EXPECT_EQ("/a+b", res->body);
  18146. }
  18147. }
  18148. TEST(RedirectTest, ResolveRelativeLocation) {
  18149. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18150. const std::vector<std::pair<std::string, std::string>> cases = {
  18151. {"g", "/b/c/g"},
  18152. {"./g", "/b/c/g"},
  18153. {"g/", "/b/c/g/"},
  18154. {"?y", "/b/c/d;p?y"},
  18155. {"g?y", "/b/c/g?y"},
  18156. {"#s", "/b/c/d;p?q#s"},
  18157. {"g#s", "/b/c/g#s"},
  18158. {"g?y#s", "/b/c/g?y#s"},
  18159. {";x", "/b/c/;x"},
  18160. {"g;x", "/b/c/g;x"},
  18161. {".", "/b/c/"},
  18162. {"./", "/b/c/"},
  18163. {"..", "/b/"},
  18164. {"../", "/b/"},
  18165. {"../g", "/b/g"},
  18166. {"../..", "/"},
  18167. {"../../", "/"},
  18168. {"../../g", "/g"},
  18169. {"../../../g", "/g"},
  18170. {"g.", "/b/c/g."},
  18171. {".g", "/b/c/.g"},
  18172. {"g..", "/b/c/g.."},
  18173. {"..g", "/b/c/..g"},
  18174. {"./../g", "/b/g"},
  18175. {"./g/.", "/b/c/g/"},
  18176. {"g/./h", "/b/c/g/h"},
  18177. {"g/../h", "/b/c/h"},
  18178. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18179. {"g;x=1/../y", "/b/c/y"},
  18180. {"g?y/./x", "/b/c/g?y/./x"},
  18181. {"g#s/../x", "/b/c/g#s/../x"},
  18182. // Not relative-path references, so left for parse_url.
  18183. {"/g", "/g"},
  18184. {"//g", "//g"},
  18185. {"http://g/x", "http://g/x"},
  18186. {"g:h", "g:h"},
  18187. };
  18188. for (const auto &c : cases) {
  18189. EXPECT_EQ(c.second,
  18190. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18191. << c.first;
  18192. }
  18193. // A result starting with "//" is still a path, not a network-path reference
  18194. EXPECT_EQ("/.//g",
  18195. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18196. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18197. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18198. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18199. }
  18200. TEST(RedirectTest, RemoveDotSegments) {
  18201. // RFC 3986 section 5.2.4
  18202. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18203. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18204. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18205. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18206. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18207. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18208. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18209. }
  18210. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18211. Server svr;
  18212. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18213. res.set_redirect("/dir/../target?x=1");
  18214. });
  18215. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18216. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18217. "/dir/./../target");
  18218. });
  18219. svr.Get("/target", [](const Request &req, Response &res) {
  18220. res.set_content(req.path, "text/plain");
  18221. });
  18222. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18223. auto se = detail::scope_exit([&] {
  18224. svr.stop();
  18225. th.join();
  18226. ASSERT_FALSE(svr.is_running());
  18227. });
  18228. svr.wait_until_ready();
  18229. Client cli("localhost", PORT);
  18230. cli.set_follow_location(true);
  18231. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18232. auto res = cli.Get(path);
  18233. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18234. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18235. EXPECT_EQ("/target", res->body) << path;
  18236. }
  18237. }
  18238. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18239. Server svr;
  18240. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18241. res.set_redirect(req.get_param_value("to"));
  18242. });
  18243. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18244. res.set_content(req.target, "text/plain");
  18245. });
  18246. svr.Get("/other", [](const Request &req, Response &res) {
  18247. res.set_content(req.target, "text/plain");
  18248. });
  18249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  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. const std::vector<std::pair<std::string, std::string>> cases = {
  18257. {"next", "/dir/next"},
  18258. {"./next?x=1", "/dir/next?x=1"},
  18259. {"../other", "/other"},
  18260. };
  18261. for (const auto &c : cases) {
  18262. Client cli(HOST, PORT);
  18263. cli.set_follow_location(true);
  18264. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18265. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18266. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18267. EXPECT_EQ(c.second, res->body) << c.first;
  18268. }
  18269. }
  18270. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18271. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18272. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18273. Server other;
  18274. std::atomic<int> other_hits{0};
  18275. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18276. other_hits++;
  18277. res.set_content("other", "text/plain");
  18278. });
  18279. auto other_port = other.bind_to_any_port("127.0.0.1");
  18280. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18281. Server svr;
  18282. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18283. res.set_redirect(req.get_param_value("to"));
  18284. });
  18285. svr.Get(".*", [](const Request &req, Response &res) {
  18286. res.set_content(req.path, "text/plain");
  18287. });
  18288. auto port = svr.bind_to_any_port(HOST);
  18289. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18290. auto se = detail::scope_exit([&] {
  18291. svr.stop();
  18292. thread.join();
  18293. other.stop();
  18294. other_thread.join();
  18295. ASSERT_FALSE(svr.is_running());
  18296. ASSERT_FALSE(other.is_running());
  18297. });
  18298. svr.wait_until_ready();
  18299. other.wait_until_ready();
  18300. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18301. for (const auto &to :
  18302. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18303. Client cli(HOST, port);
  18304. cli.set_follow_location(true);
  18305. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18306. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18307. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18308. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18309. }
  18310. EXPECT_EQ(0, other_hits.load());
  18311. }
  18312. #ifdef CPPHTTPLIB_SSL_ENABLED
  18313. TEST(RedirectTest, Issue2185_Online) {
  18314. SSLClient client("github.com");
  18315. client.set_follow_location(true);
  18316. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18317. "Coollab-Windows.zip");
  18318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18319. EXPECT_EQ(StatusCode::OK_200, res->status);
  18320. EXPECT_EQ(9920427U, res->body.size());
  18321. }
  18322. #endif
  18323. TEST(VulnerabilityTest, CRLFInjection) {
  18324. Server svr;
  18325. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18326. res.set_content("Hello 1", "text/plain");
  18327. });
  18328. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18329. res.set_content("Hello 2", "text/plain");
  18330. });
  18331. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18332. res.set_content("Hello 3", "text/plain");
  18333. });
  18334. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18335. res.set_content("Hello 4", "text/plain");
  18336. });
  18337. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18338. for (const auto &x : req.headers) {
  18339. auto key = x.first;
  18340. EXPECT_STRNE("evil", key.c_str());
  18341. }
  18342. });
  18343. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18344. auto se = detail::scope_exit([&] {
  18345. svr.stop();
  18346. thread.join();
  18347. ASSERT_FALSE(svr.is_running());
  18348. });
  18349. svr.wait_until_ready();
  18350. {
  18351. Client cli(HOST, PORT);
  18352. cli.Post("/test1", "A=B",
  18353. "application/x-www-form-urlencoded\r\nevil: hello1");
  18354. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18355. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18356. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18357. }
  18358. }
  18359. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18360. auto server_thread = std::thread([] {
  18361. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18362. default_socket_options(srv);
  18363. sockaddr_in addr{};
  18364. addr.sin_family = AF_INET;
  18365. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18366. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18367. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18368. ::listen(srv, 1);
  18369. sockaddr_in cli_addr{};
  18370. socklen_t cli_len = sizeof(cli_addr);
  18371. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18372. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18373. std::string buf_all;
  18374. char buf[2048];
  18375. ssize_t n;
  18376. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18377. buf_all.append(buf, static_cast<size_t>(n));
  18378. size_t pos;
  18379. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18380. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18381. auto e = request_block.find("\r\n");
  18382. if (e != std::string::npos) {
  18383. auto request_line = request_block.substr(0, e);
  18384. std::string msg =
  18385. "CRLF injection detected in request line: '" + request_line + "'";
  18386. EXPECT_FALSE(true) << msg;
  18387. }
  18388. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18389. ::send(cli,
  18390. #ifdef _WIN32
  18391. static_cast<const char *>(resp.c_str()),
  18392. static_cast<int>(resp.size()),
  18393. #else
  18394. resp.c_str(), resp.size(),
  18395. #endif
  18396. 0);
  18397. buf_all.erase(0, pos + 4);
  18398. }
  18399. }
  18400. detail::close_socket(cli);
  18401. detail::close_socket(srv);
  18402. });
  18403. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18404. auto cli = Client("127.0.0.1", PORT + 1);
  18405. auto headers = Headers{
  18406. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18407. {"Connection", "keep-alive"}};
  18408. auto res = cli.Get("/hi", headers);
  18409. EXPECT_FALSE(res);
  18410. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18411. server_thread.join();
  18412. }
  18413. // A request rejected before any byte reaches the socket must fail right away
  18414. // instead of waiting for a response the server will never send.
  18415. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18416. // The kernel completes the TCP handshake from the listen backlog, so the
  18417. // client connects, but nothing ever reads, responds or closes.
  18418. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18419. default_socket_options(srv);
  18420. sockaddr_in addr{};
  18421. addr.sin_family = AF_INET;
  18422. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18423. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18424. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18425. ASSERT_EQ(0, ::listen(srv, 8));
  18426. auto cli = Client("127.0.0.1", PORT + 1);
  18427. cli.set_read_timeout(10, 0);
  18428. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18429. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18430. std::chrono::steady_clock::now() - start)
  18431. .count();
  18432. };
  18433. {
  18434. Request req;
  18435. req.method = "GE T";
  18436. req.path = "/";
  18437. auto start = std::chrono::steady_clock::now();
  18438. auto res = cli.send(req);
  18439. EXPECT_FALSE(res);
  18440. EXPECT_EQ(Error::Write, res.error());
  18441. EXPECT_LT(elapsed_ms(start), 1000);
  18442. }
  18443. {
  18444. auto start = std::chrono::steady_clock::now();
  18445. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18446. EXPECT_FALSE(res);
  18447. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18448. EXPECT_LT(elapsed_ms(start), 1000);
  18449. }
  18450. EXPECT_FALSE(cli.is_socket_open());
  18451. detail::close_socket(srv);
  18452. }
  18453. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18454. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18455. default_socket_options(srv);
  18456. sockaddr_in addr{};
  18457. addr.sin_family = AF_INET;
  18458. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18459. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18460. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18461. ASSERT_EQ(0, ::listen(srv, 1));
  18462. std::string received;
  18463. auto server_thread = std::thread([&] {
  18464. auto sock = ::accept(srv, nullptr, nullptr);
  18465. if (sock == INVALID_SOCKET) { return; }
  18466. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18467. char buf[2048];
  18468. ssize_t n;
  18469. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18470. received.append(buf, static_cast<size_t>(n));
  18471. }
  18472. detail::close_socket(sock);
  18473. });
  18474. {
  18475. auto cli = Client("127.0.0.1", PORT + 1);
  18476. // "Z" sorts after the default headers, so writing straight to the socket
  18477. // would have sent the request line and those headers before the rejection.
  18478. auto handle =
  18479. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18480. EXPECT_FALSE(handle.is_valid());
  18481. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18482. }
  18483. server_thread.join();
  18484. detail::close_socket(srv);
  18485. EXPECT_TRUE(received.empty()) << received;
  18486. }
  18487. TEST(PathParamsTest, StaticMatch) {
  18488. const auto pattern = "/users/all";
  18489. detail::PathParamsMatcher matcher(pattern);
  18490. Request request;
  18491. request.path = "/users/all";
  18492. ASSERT_TRUE(matcher.match(request));
  18493. std::unordered_map<std::string, std::string> expected_params = {};
  18494. EXPECT_EQ(request.path_params, expected_params);
  18495. }
  18496. TEST(PathParamsTest, StaticMismatch) {
  18497. const auto pattern = "/users/all";
  18498. detail::PathParamsMatcher matcher(pattern);
  18499. Request request;
  18500. request.path = "/users/1";
  18501. ASSERT_FALSE(matcher.match(request));
  18502. }
  18503. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18504. const auto pattern = "/users/:id/subscriptions";
  18505. detail::PathParamsMatcher matcher(pattern);
  18506. Request request;
  18507. request.path = "/users/42/subscriptions";
  18508. ASSERT_TRUE(matcher.match(request));
  18509. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18510. EXPECT_EQ(request.path_params, expected_params);
  18511. }
  18512. TEST(PathParamsTest, SingleParamInTheEnd) {
  18513. const auto pattern = "/users/:id";
  18514. detail::PathParamsMatcher matcher(pattern);
  18515. Request request;
  18516. request.path = "/users/24";
  18517. ASSERT_TRUE(matcher.match(request));
  18518. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18519. EXPECT_EQ(request.path_params, expected_params);
  18520. }
  18521. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18522. const auto pattern = "/users/:id/";
  18523. detail::PathParamsMatcher matcher(pattern);
  18524. Request request;
  18525. request.path = "/users/42/";
  18526. ASSERT_TRUE(matcher.match(request));
  18527. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18528. EXPECT_EQ(request.path_params, expected_params);
  18529. }
  18530. TEST(PathParamsTest, EmptyParam) {
  18531. const auto pattern = "/users/:id/";
  18532. detail::PathParamsMatcher matcher(pattern);
  18533. Request request;
  18534. request.path = "/users//";
  18535. ASSERT_TRUE(matcher.match(request));
  18536. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18537. EXPECT_EQ(request.path_params, expected_params);
  18538. }
  18539. TEST(PathParamsTest, FragmentMismatch) {
  18540. const auto pattern = "/users/:id/";
  18541. detail::PathParamsMatcher matcher(pattern);
  18542. Request request;
  18543. request.path = "/admins/24/";
  18544. ASSERT_FALSE(matcher.match(request));
  18545. }
  18546. TEST(PathParamsTest, ExtraFragments) {
  18547. const auto pattern = "/users/:id";
  18548. detail::PathParamsMatcher matcher(pattern);
  18549. Request request;
  18550. request.path = "/users/42/subscriptions";
  18551. ASSERT_FALSE(matcher.match(request));
  18552. }
  18553. TEST(PathParamsTest, MissingTrailingParam) {
  18554. const auto pattern = "/users/:id";
  18555. detail::PathParamsMatcher matcher(pattern);
  18556. Request request;
  18557. request.path = "/users";
  18558. ASSERT_FALSE(matcher.match(request));
  18559. }
  18560. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18561. const auto pattern = "/users/:id/subscriptions";
  18562. detail::PathParamsMatcher matcher(pattern);
  18563. Request request;
  18564. request.path = "/users/subscriptions";
  18565. ASSERT_FALSE(matcher.match(request));
  18566. }
  18567. TEST(PathParamsTest, MultipleParams) {
  18568. const auto pattern = "/users/:userid/subscriptions/:subid";
  18569. detail::PathParamsMatcher matcher(pattern);
  18570. Request request;
  18571. request.path = "/users/42/subscriptions/2";
  18572. ASSERT_TRUE(matcher.match(request));
  18573. std::unordered_map<std::string, std::string> expected_params = {
  18574. {"userid", "42"}, {"subid", "2"}};
  18575. EXPECT_EQ(request.path_params, expected_params);
  18576. }
  18577. TEST(PathParamsTest, SequenceOfParams) {
  18578. const auto pattern = "/values/:x/:y/:z";
  18579. detail::PathParamsMatcher matcher(pattern);
  18580. Request request;
  18581. request.path = "/values/1/2/3";
  18582. ASSERT_TRUE(matcher.match(request));
  18583. std::unordered_map<std::string, std::string> expected_params = {
  18584. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18585. EXPECT_EQ(request.path_params, expected_params);
  18586. }
  18587. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18588. const auto pattern = "/prefix:suffix";
  18589. detail::PathParamsMatcher matcher(pattern);
  18590. Request request;
  18591. request.path = "/prefix:suffix";
  18592. ASSERT_TRUE(matcher.match(request));
  18593. const std::unordered_map<std::string, std::string> expected_params = {};
  18594. EXPECT_EQ(request.path_params, expected_params);
  18595. }
  18596. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18597. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18598. // calling thread's stack on a long enough path for a quantified pattern;
  18599. // RegexMatcher must refuse to run regex matching on paths beyond
  18600. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18601. detail::RegexMatcher matcher("/files/(.*)");
  18602. Request within_limit;
  18603. within_limit.path = "/files/" + std::string(10, 'A');
  18604. EXPECT_TRUE(matcher.match(within_limit));
  18605. Request over_limit;
  18606. over_limit.path =
  18607. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18608. EXPECT_FALSE(matcher.match(over_limit));
  18609. }
  18610. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18611. Server svr;
  18612. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18613. res.set_content("ok", "text/plain");
  18614. });
  18615. auto port = svr.bind_to_any_port(HOST);
  18616. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18617. auto se = detail::scope_exit([&] {
  18618. svr.stop();
  18619. thread.join();
  18620. ASSERT_FALSE(svr.is_running());
  18621. });
  18622. svr.wait_until_ready();
  18623. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18624. // request URI limit; this used to be able to crash the process.
  18625. std::string path =
  18626. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18627. std::string req = "GET " + path +
  18628. " HTTP/1.1\r\n"
  18629. "Host: " +
  18630. std::string(HOST) + ":" + std::to_string(port) +
  18631. "\r\n"
  18632. "Connection: close\r\n"
  18633. "\r\n";
  18634. std::string response;
  18635. ASSERT_TRUE(send_request(5, req, &response, port));
  18636. EXPECT_NE(std::string::npos, response.find("404"));
  18637. }
  18638. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18639. Server svr;
  18640. auto handler = [](const Request & /*req*/, Response &res) {
  18641. res.set_content("hit", "text/plain");
  18642. };
  18643. // No regex metacharacter, so this one is compared literally
  18644. svr.Get("/literal/route", handler);
  18645. // '.' is a regex metacharacter, so this one must keep regex semantics
  18646. svr.Get("/a.c", handler);
  18647. auto port = svr.bind_to_any_port(HOST);
  18648. std::thread t([&]() { svr.listen_after_bind(); });
  18649. auto se = detail::scope_exit([&] {
  18650. svr.stop();
  18651. t.join();
  18652. ASSERT_FALSE(svr.is_running());
  18653. });
  18654. svr.wait_until_ready();
  18655. Client cli(HOST, port);
  18656. struct {
  18657. const char *path;
  18658. int status;
  18659. } cases[] = {
  18660. {"/literal/route", StatusCode::OK_200},
  18661. {"/literal/routes", StatusCode::NotFound_404},
  18662. {"/literal/rout", StatusCode::NotFound_404},
  18663. {"/abc", StatusCode::OK_200},
  18664. {"/a.c", StatusCode::OK_200},
  18665. };
  18666. for (const auto &x : cases) {
  18667. auto res = cli.Get(x.path);
  18668. ASSERT_TRUE(res) << x.path;
  18669. EXPECT_EQ(x.status, res->status) << x.path;
  18670. }
  18671. }
  18672. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18673. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18674. // from exhausting the stack, so it must only constrain routes that actually
  18675. // run a regular expression. A literal route is matched by comparison and
  18676. // stays usable at any length.
  18677. Server svr;
  18678. const std::string pattern =
  18679. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18680. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18681. res.set_content("hit", "text/plain");
  18682. });
  18683. auto port = svr.bind_to_any_port(HOST);
  18684. std::thread t([&]() { svr.listen_after_bind(); });
  18685. auto se = detail::scope_exit([&] {
  18686. svr.stop();
  18687. t.join();
  18688. ASSERT_FALSE(svr.is_running());
  18689. });
  18690. svr.wait_until_ready();
  18691. Client cli(HOST, port);
  18692. auto res = cli.Get(pattern);
  18693. ASSERT_TRUE(res);
  18694. EXPECT_EQ(StatusCode::OK_200, res->status);
  18695. }
  18696. TEST(ParseUrlTest, VariousPatterns) {
  18697. {
  18698. detail::UrlComponents uc;
  18699. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18700. EXPECT_EQ("http", uc.scheme);
  18701. EXPECT_EQ("example.com", uc.host);
  18702. EXPECT_EQ("8080", uc.port);
  18703. EXPECT_EQ("/path", uc.path);
  18704. EXPECT_EQ("?q=1", uc.query);
  18705. }
  18706. {
  18707. detail::UrlComponents uc;
  18708. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18709. EXPECT_EQ("https", uc.scheme);
  18710. EXPECT_EQ("example.com", uc.host);
  18711. EXPECT_TRUE(uc.port.empty());
  18712. EXPECT_EQ("/path", uc.path);
  18713. }
  18714. {
  18715. detail::UrlComponents uc;
  18716. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18717. EXPECT_EQ("::1", uc.host);
  18718. EXPECT_EQ("8080", uc.port);
  18719. EXPECT_EQ("/path", uc.path);
  18720. }
  18721. {
  18722. detail::UrlComponents uc;
  18723. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18724. }
  18725. {
  18726. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18727. // the path while the connection still targets the bracketed host.
  18728. detail::UrlComponents uc;
  18729. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18730. }
  18731. {
  18732. detail::UrlComponents uc;
  18733. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18734. }
  18735. {
  18736. detail::UrlComponents uc;
  18737. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18738. EXPECT_EQ("::1", uc.host);
  18739. EXPECT_TRUE(uc.port.empty());
  18740. EXPECT_EQ("/path", uc.path);
  18741. }
  18742. {
  18743. detail::UrlComponents uc;
  18744. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18745. EXPECT_TRUE(uc.scheme.empty());
  18746. EXPECT_EQ("example.com", uc.host);
  18747. EXPECT_EQ("/path", uc.path);
  18748. EXPECT_EQ("?q=1", uc.query);
  18749. }
  18750. {
  18751. detail::UrlComponents uc;
  18752. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18753. EXPECT_TRUE(uc.host.empty());
  18754. EXPECT_EQ("/path", uc.path);
  18755. EXPECT_EQ("?q=1", uc.query);
  18756. }
  18757. {
  18758. detail::UrlComponents uc;
  18759. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18760. EXPECT_EQ("example.com", uc.host);
  18761. EXPECT_EQ("8080", uc.port);
  18762. }
  18763. {
  18764. // Unix socket path — must not be parsed as host
  18765. detail::UrlComponents uc;
  18766. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18767. EXPECT_TRUE(uc.host.empty());
  18768. }
  18769. {
  18770. detail::UrlComponents uc;
  18771. ASSERT_TRUE(detail::parse_url("", uc));
  18772. EXPECT_TRUE(uc.host.empty());
  18773. EXPECT_TRUE(uc.path.empty());
  18774. }
  18775. {
  18776. detail::UrlComponents uc;
  18777. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  18778. EXPECT_EQ("http", uc.scheme);
  18779. }
  18780. {
  18781. detail::UrlComponents uc;
  18782. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18783. }
  18784. {
  18785. // Accepted by parse_url; callers restrict to http/https
  18786. detail::UrlComponents uc;
  18787. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18788. EXPECT_EQ("ftp", uc.scheme);
  18789. }
  18790. {
  18791. detail::UrlComponents uc;
  18792. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18793. }
  18794. {
  18795. detail::UrlComponents uc;
  18796. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18797. }
  18798. }
  18799. TEST(ParseUrlTest, FragmentHandling) {
  18800. {
  18801. detail::UrlComponents uc;
  18802. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18803. EXPECT_EQ("/path", uc.path);
  18804. EXPECT_TRUE(uc.query.empty());
  18805. }
  18806. {
  18807. detail::UrlComponents uc;
  18808. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18809. EXPECT_TRUE(uc.path.empty());
  18810. EXPECT_TRUE(uc.query.empty());
  18811. }
  18812. }
  18813. TEST(ParseUrlTest, UserinfoHandling) {
  18814. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18815. // parsers would see evil.com as the host.
  18816. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18817. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18818. for (auto url : urls) {
  18819. detail::UrlComponents uc;
  18820. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18821. }
  18822. }
  18823. TEST(ParseUrlTest, IPv6EdgeCases) {
  18824. {
  18825. detail::UrlComponents uc;
  18826. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18827. EXPECT_TRUE(uc.scheme.empty());
  18828. EXPECT_EQ("::1", uc.host);
  18829. EXPECT_EQ("8080", uc.port);
  18830. }
  18831. {
  18832. // Zone ID '%25' is not in [a-fA-F0-9:]
  18833. detail::UrlComponents uc;
  18834. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18835. }
  18836. }
  18837. TEST(ParseUrlTest, SchemeEdgeCases) {
  18838. {
  18839. detail::UrlComponents uc;
  18840. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18841. }
  18842. {
  18843. detail::UrlComponents uc;
  18844. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18845. }
  18846. {
  18847. detail::UrlComponents uc;
  18848. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18849. }
  18850. {
  18851. detail::UrlComponents uc;
  18852. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  18853. EXPECT_EQ("https", uc.scheme);
  18854. }
  18855. }
  18856. TEST(ParseUrlTest, PortEdgeCases) {
  18857. {
  18858. detail::UrlComponents uc;
  18859. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18860. EXPECT_TRUE(uc.port.empty());
  18861. EXPECT_EQ("/path", uc.path);
  18862. }
  18863. {
  18864. // parse_url accepts any port string; validation is done by parse_port
  18865. detail::UrlComponents uc;
  18866. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18867. EXPECT_EQ("abc", uc.port);
  18868. }
  18869. }
  18870. TEST(ParseUrlTest, WebSocketPatterns) {
  18871. {
  18872. detail::UrlComponents uc;
  18873. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18874. EXPECT_EQ("ws", uc.scheme);
  18875. EXPECT_EQ("echo.example.com", uc.host);
  18876. EXPECT_EQ("8080", uc.port);
  18877. EXPECT_EQ("/ws", uc.path);
  18878. }
  18879. {
  18880. detail::UrlComponents uc;
  18881. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18882. EXPECT_EQ("wss", uc.scheme);
  18883. EXPECT_EQ("echo.example.com", uc.host);
  18884. EXPECT_TRUE(uc.port.empty());
  18885. EXPECT_EQ("/ws", uc.path);
  18886. }
  18887. }
  18888. TEST(ParseUrlTest, QueryOnly) {
  18889. detail::UrlComponents uc;
  18890. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18891. EXPECT_TRUE(uc.host.empty());
  18892. EXPECT_TRUE(uc.path.empty());
  18893. EXPECT_EQ("?q=1&r=2", uc.query);
  18894. }
  18895. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18896. detail::UrlComponents uc;
  18897. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18898. EXPECT_TRUE(uc.scheme.empty());
  18899. EXPECT_EQ("example.com", uc.host);
  18900. EXPECT_EQ("443", uc.port);
  18901. EXPECT_EQ("/path", uc.path);
  18902. }
  18903. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18904. // If ipv6 regex working, regex match codepath is taken.
  18905. // else port will default to 80 in Client impl
  18906. int clientImplMagicPort = 80;
  18907. int port = 4321;
  18908. // above ports must be different to avoid false negative
  18909. EXPECT_NE(clientImplMagicPort, port);
  18910. std::string ipV6TestURL = "http://[ff06::c3]";
  18911. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18912. CLIENT_PRIVATE_KEY_FILE);
  18913. EXPECT_EQ(cli.port(), port);
  18914. }
  18915. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18916. auto file_path = "./www/dir/index.html";
  18917. auto dir_path = "./www/dir";
  18918. detail::FileStat stat_file(file_path);
  18919. EXPECT_TRUE(stat_file.is_file());
  18920. EXPECT_FALSE(stat_file.is_dir());
  18921. detail::FileStat stat_dir(dir_path);
  18922. EXPECT_FALSE(stat_dir.is_file());
  18923. EXPECT_TRUE(stat_dir.is_dir());
  18924. }
  18925. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18926. // IPv4 with default HTTP port (80)
  18927. EXPECT_EQ("example.com",
  18928. detail::make_host_and_port_string("example.com", 80, false));
  18929. // IPv4 with default HTTPS port (443)
  18930. EXPECT_EQ("example.com",
  18931. detail::make_host_and_port_string("example.com", 443, true));
  18932. // IPv4 with non-default HTTP port
  18933. EXPECT_EQ("example.com:8080",
  18934. detail::make_host_and_port_string("example.com", 8080, false));
  18935. // IPv4 with non-default HTTPS port
  18936. EXPECT_EQ("example.com:8443",
  18937. detail::make_host_and_port_string("example.com", 8443, true));
  18938. // IPv6 with default HTTP port (80)
  18939. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18940. // IPv6 with default HTTPS port (443)
  18941. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18942. // IPv6 with non-default HTTP port
  18943. EXPECT_EQ("[::1]:8080",
  18944. detail::make_host_and_port_string("::1", 8080, false));
  18945. // IPv6 with non-default HTTPS port
  18946. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18947. // IPv6 full address with default port
  18948. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18949. detail::make_host_and_port_string(
  18950. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18951. // IPv6 full address with non-default port
  18952. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18953. detail::make_host_and_port_string(
  18954. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18955. // IPv6 localhost with non-default port
  18956. EXPECT_EQ("[::1]:3000",
  18957. detail::make_host_and_port_string("::1", 3000, false));
  18958. // IPv6 with zone ID (link-local address) with default port
  18959. EXPECT_EQ("[fe80::1%eth0]",
  18960. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18961. // IPv6 with zone ID (link-local address) with non-default port
  18962. EXPECT_EQ("[fe80::1%eth0]:8080",
  18963. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18964. // Edge case: Port 443 with is_ssl=false (should add port)
  18965. EXPECT_EQ("example.com:443",
  18966. detail::make_host_and_port_string("example.com", 443, false));
  18967. // Edge case: Port 80 with is_ssl=true (should add port)
  18968. EXPECT_EQ("example.com:80",
  18969. detail::make_host_and_port_string("example.com", 80, true));
  18970. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18971. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18972. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18973. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18974. // Security fix: Already bracketed IPv6 should not get double brackets
  18975. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18976. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18977. EXPECT_EQ("[::1]:8080",
  18978. detail::make_host_and_port_string("[::1]", 8080, false));
  18979. EXPECT_EQ("[2001:db8::1]:8080",
  18980. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18981. EXPECT_EQ("[fe80::1%eth0]",
  18982. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18983. EXPECT_EQ("[fe80::1%eth0]:8080",
  18984. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18985. // Edge case: Empty host (should return as-is)
  18986. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18987. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18988. // This is a known limitation but shouldn't crash
  18989. EXPECT_EQ("[host:name]",
  18990. detail::make_host_and_port_string("host:name", 80, false));
  18991. // Port number edge cases (no validation, but should not crash)
  18992. EXPECT_EQ("example.com:0",
  18993. detail::make_host_and_port_string("example.com", 0, false));
  18994. EXPECT_EQ("example.com:-1",
  18995. detail::make_host_and_port_string("example.com", -1, false));
  18996. EXPECT_EQ("example.com:65535",
  18997. detail::make_host_and_port_string("example.com", 65535, false));
  18998. EXPECT_EQ("example.com:65536",
  18999. detail::make_host_and_port_string("example.com", 65536, false));
  19000. }
  19001. namespace httplib {
  19002. namespace detail {
  19003. std::string
  19004. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  19005. const std::string &host, int port);
  19006. } // namespace detail
  19007. } // namespace httplib
  19008. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  19009. std::map<std::string, std::string> addr_map = {
  19010. {"ipv4.example", "192.0.2.10"},
  19011. {"ipv6.example", "2001:db8::1"},
  19012. {"name.example", "internal.example.lan"},
  19013. {"empty.example", ""}};
  19014. EXPECT_EQ("192.0.2.10:443",
  19015. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  19016. EXPECT_EQ("[2001:db8::1]:443",
  19017. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  19018. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  19019. addr_map, "name.example", 8443));
  19020. // An empty or absent mapping keeps the hostname as the target
  19021. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  19022. addr_map, "empty.example", 443));
  19023. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  19024. addr_map, "other.example", 443));
  19025. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  19026. }
  19027. #ifdef CPPHTTPLIB_SSL_ENABLED
  19028. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  19029. httplib::SSLClient cli("roblox.com", 443);
  19030. cli.set_follow_location(true);
  19031. auto res = cli.Get("/");
  19032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19033. EXPECT_EQ(StatusCode::OK_200, res->status);
  19034. }
  19035. #endif
  19036. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  19037. Server svr;
  19038. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19039. EXPECT_EQ(res.status, 400);
  19040. });
  19041. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19042. auto se = detail::scope_exit([&] {
  19043. svr.stop();
  19044. thread.join();
  19045. ASSERT_FALSE(svr.is_running());
  19046. });
  19047. svr.wait_until_ready();
  19048. Client cli(HOST, PORT);
  19049. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  19050. }
  19051. TEST(InvalidHeaderCharsTest, is_field_name) {
  19052. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  19053. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  19054. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  19055. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  19056. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  19057. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  19058. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  19059. EXPECT_FALSE(detail::fields::is_field_name(""));
  19060. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  19061. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  19062. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  19063. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  19064. }
  19065. TEST(InvalidHeaderCharsTest, is_field_value) {
  19066. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19067. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19068. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19069. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19070. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19071. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19072. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19073. EXPECT_TRUE(detail::fields::is_field_value(""));
  19074. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19075. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19076. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19077. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19078. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19079. }
  19080. TEST(InvalidHeaderCharsTest, OnServer) {
  19081. Server svr;
  19082. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19083. std::string header = "Not Set";
  19084. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19085. res.set_header(header, "value");
  19086. res.set_content("Page Content Page Content", "text/plain");
  19087. });
  19088. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19089. std::string header = "Not Set";
  19090. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19091. res.set_header("X-Test", header);
  19092. res.set_content("Page Content Page Content", "text/plain");
  19093. });
  19094. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19095. auto se = detail::scope_exit([&] {
  19096. svr.stop();
  19097. thread.join();
  19098. ASSERT_FALSE(svr.is_running());
  19099. });
  19100. svr.wait_until_ready();
  19101. Client cli(HOST, PORT);
  19102. {
  19103. auto res = cli.Get(
  19104. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19106. EXPECT_EQ("Page Content Page Content", res->body);
  19107. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19108. }
  19109. {
  19110. auto res = cli.Get(
  19111. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19113. EXPECT_EQ("Page Content Page Content", res->body);
  19114. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19115. }
  19116. }
  19117. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19118. auto handled = false;
  19119. Server svr;
  19120. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19121. thread t = thread([&] { svr.listen(HOST, PORT); });
  19122. auto se = detail::scope_exit([&] {
  19123. svr.stop();
  19124. t.join();
  19125. ASSERT_FALSE(svr.is_running());
  19126. ASSERT_FALSE(handled);
  19127. });
  19128. svr.wait_until_ready();
  19129. auto req = "POST /test HTTP/1.1\r\n"
  19130. "Content-Length: x\r\n"
  19131. "\r\n";
  19132. std::string response;
  19133. ASSERT_TRUE(send_request(1, req, &response));
  19134. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19135. response.substr(0, response.find("\r\n")));
  19136. }
  19137. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19138. // case-insensitive, and a server that receives a 100-continue expectation in
  19139. // an HTTP/1.0 request MUST ignore it.
  19140. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19141. std::string response;
  19142. ASSERT_TRUE(send_request(1, req, &response, port));
  19143. *got_100 = response.find("100 Continue") != std::string::npos;
  19144. }
  19145. class ExpectTokenTest : public ::testing::Test {
  19146. protected:
  19147. void SetUp() override {
  19148. svr_.Post("/p", [](const Request &, Response &res) {
  19149. res.set_content("ok", "text/plain");
  19150. });
  19151. port_ = svr_.bind_to_any_port(HOST);
  19152. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19153. svr_.wait_until_ready();
  19154. }
  19155. void TearDown() override {
  19156. svr_.stop();
  19157. if (thread_.joinable()) { thread_.join(); }
  19158. }
  19159. std::string request(const char *version, const char *expect_value) const {
  19160. return std::string("POST /p ") + version +
  19161. "\r\n"
  19162. "Host: localhost\r\n"
  19163. "Content-Length: 2\r\n"
  19164. "Connection: close\r\n"
  19165. "Expect: " +
  19166. expect_value +
  19167. "\r\n"
  19168. "\r\n"
  19169. "hi";
  19170. }
  19171. Server svr_;
  19172. int port_ = 0;
  19173. thread thread_;
  19174. };
  19175. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19176. bool got_100 = false;
  19177. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19178. EXPECT_TRUE(got_100);
  19179. }
  19180. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19181. bool got_100 = true;
  19182. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19183. EXPECT_FALSE(got_100);
  19184. }
  19185. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19186. bool got_100 = false;
  19187. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19188. EXPECT_TRUE(got_100);
  19189. }
  19190. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19191. bool got_100 = false;
  19192. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19193. EXPECT_TRUE(got_100);
  19194. }
  19195. // `100 Continue` is sent only when the server starts reading the body, so a
  19196. // request rejected before that never invites the client to send it. The
  19197. // requests below carry the expectation but withhold the body, as a client
  19198. // waiting for `100 Continue` would.
  19199. // A POST that expects `100 Continue` and withholds its two-byte body.
  19200. static std::string expect_headers_only(const std::string &path) {
  19201. return "POST " + path +
  19202. " HTTP/1.1\r\n"
  19203. "Host: localhost\r\n"
  19204. "Content-Length: 2\r\n"
  19205. "Expect: 100-continue\r\n"
  19206. "\r\n";
  19207. }
  19208. class ExpectLazyContinueTest : public ::testing::Test {
  19209. protected:
  19210. void SetUp() override {
  19211. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19212. if (req.path == "/pre-routing") {
  19213. res.status = StatusCode::Unauthorized_401;
  19214. return Server::HandlerResponse::Handled;
  19215. }
  19216. return Server::HandlerResponse::Unhandled;
  19217. });
  19218. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19219. if (req.matched_route == "/pre-request") {
  19220. res.status = StatusCode::Forbidden_403;
  19221. return Server::HandlerResponse::Handled;
  19222. }
  19223. return Server::HandlerResponse::Unhandled;
  19224. });
  19225. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19226. res.set_content("ok", "text/plain");
  19227. });
  19228. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19229. res.set_content("ok", "text/plain");
  19230. });
  19231. svr_.Post("/reader-used", [](const Request &, Response &res,
  19232. const ContentReader &content_reader) {
  19233. std::string body;
  19234. content_reader([&](const char *data, size_t len) {
  19235. body.append(data, len);
  19236. return true;
  19237. });
  19238. res.set_content(body, "text/plain");
  19239. });
  19240. svr_.Post("/reader-unused",
  19241. [](const Request &, Response &res, const ContentReader &) {
  19242. res.set_content("ignored", "text/plain");
  19243. });
  19244. port_ = svr_.bind_to_any_port(HOST);
  19245. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19246. svr_.wait_until_ready();
  19247. }
  19248. void TearDown() override {
  19249. svr_.stop();
  19250. if (thread_.joinable()) { thread_.join(); }
  19251. }
  19252. // Sends `req` and reads until the server closes the connection. Returns
  19253. // false if the read had to wait for the client-side timeout instead.
  19254. bool send_until_closed(const std::string &req, std::string *resp) const {
  19255. auto start = std::chrono::steady_clock::now();
  19256. if (!send_request(3, req, resp, port_)) { return false; }
  19257. auto elapsed = std::chrono::steady_clock::now() - start;
  19258. return elapsed < std::chrono::seconds(2);
  19259. }
  19260. // The final response comes without `100 Continue`, and the server closes
  19261. // the connection since the body may or may not follow.
  19262. void expect_final_without_interim(const std::string &path,
  19263. const char *status_line) const {
  19264. std::string resp;
  19265. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19266. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19267. EXPECT_EQ(0u, resp.find(status_line));
  19268. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19269. }
  19270. Server svr_;
  19271. int port_ = 0;
  19272. thread thread_;
  19273. };
  19274. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19275. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19276. }
  19277. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19278. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19279. }
  19280. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19281. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19282. }
  19283. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19284. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19285. }
  19286. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19287. // The body follows once `100 Continue` has had time to arrive.
  19288. auto req = expect_headers_only("/reader-used");
  19289. req.insert(req.size() - 2, "Connection: close\r\n");
  19290. std::string resp;
  19291. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19292. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19293. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19294. EXPECT_NE(std::string::npos, resp.find("hi"));
  19295. }
  19296. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19297. // Large enough for the client to add `Expect: 100-continue` itself.
  19298. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19299. std::atomic<bool> body_sent{false};
  19300. Client cli(HOST, port_);
  19301. auto res = cli.Post(
  19302. "/pre-request", length,
  19303. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19304. body_sent = true;
  19305. std::string chunk(len, 'x');
  19306. sink.write(chunk.data(), chunk.size());
  19307. return true;
  19308. },
  19309. "application/octet-stream");
  19310. ASSERT_TRUE(res);
  19311. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19312. EXPECT_FALSE(body_sent);
  19313. }
  19314. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19315. Server svr;
  19316. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19317. return StatusCode::ExpectationFailed_417;
  19318. });
  19319. svr.Post("/p", [](const Request &, Response &res) {
  19320. res.set_content("ok", "text/plain");
  19321. });
  19322. auto port = svr.bind_to_any_port(HOST);
  19323. thread t = thread([&] { svr.listen_after_bind(); });
  19324. auto se = detail::scope_exit([&] {
  19325. svr.stop();
  19326. t.join();
  19327. });
  19328. svr.wait_until_ready();
  19329. std::string resp;
  19330. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19331. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19332. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19333. // Exactly one response: the route handler must not run after the 417.
  19334. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19335. }
  19336. #ifndef _WIN32
  19337. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19338. static constexpr char reject[] = "Unauthorized";
  19339. static constexpr char accept[] = "Upload accepted";
  19340. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19341. Server svr;
  19342. svr.set_expect_100_continue_handler(
  19343. [](const Request & /*req*/, Response &res) {
  19344. res.status = StatusCode::Unauthorized_401;
  19345. res.set_content(reject, "text/plain");
  19346. return res.status;
  19347. });
  19348. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19349. res.set_content(accept, "text/plain");
  19350. });
  19351. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19352. auto se = detail::scope_exit([&] {
  19353. svr.stop();
  19354. thread.join();
  19355. ASSERT_FALSE(svr.is_running());
  19356. });
  19357. svr.wait_until_ready();
  19358. {
  19359. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19360. curl_easy_init(), &curl_easy_cleanup};
  19361. ASSERT_NE(curl, nullptr);
  19362. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19363. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19364. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19365. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19366. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19367. &curl_slist_free_all};
  19368. ASSERT_NE(list, nullptr);
  19369. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19370. struct read_data {
  19371. uint64_t read_size;
  19372. uint64_t total_size;
  19373. } data = {0, total_size};
  19374. using read_callback_t =
  19375. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19376. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19377. void *userdata) -> size_t {
  19378. read_data *d = (read_data *)userdata;
  19379. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19380. std::fill_n(ptr, size * nmemb, 'A');
  19381. d->read_size += size * nmemb;
  19382. return size * nmemb;
  19383. };
  19384. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19385. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19386. std::vector<char> buffer;
  19387. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19388. using write_callback_t =
  19389. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19390. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19391. void *userdata) -> size_t {
  19392. std::vector<char> *buf = (std::vector<char> *)userdata;
  19393. buf->reserve(buf->size() + size * nmemb + 1);
  19394. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19395. return size * nmemb;
  19396. };
  19397. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19398. {
  19399. const auto res = curl_easy_perform(curl.get());
  19400. ASSERT_EQ(res, CURLE_OK);
  19401. }
  19402. {
  19403. auto response_code = long{};
  19404. const auto res =
  19405. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19406. ASSERT_EQ(res, CURLE_OK);
  19407. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19408. }
  19409. {
  19410. auto dl = curl_off_t{};
  19411. const auto res =
  19412. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19413. ASSERT_EQ(res, CURLE_OK);
  19414. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19415. }
  19416. {
  19417. buffer.push_back('\0');
  19418. ASSERT_STRCASEEQ(buffer.data(), reject);
  19419. }
  19420. }
  19421. }
  19422. #endif
  19423. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19424. // Regression test for #2458.
  19425. //
  19426. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19427. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19428. // ticket can make the client socket spuriously readable during the
  19429. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19430. // the client withholds the body and then blocks reading a response that never
  19431. // comes, failing with `Failed to read connection`.
  19432. //
  19433. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19434. // within the timeout. This raw OpenSSL server deliberately never sends
  19435. // `100 Continue`; the client must still deliver the body and receive 200.
  19436. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19437. signal(SIGPIPE, SIG_IGN);
  19438. const auto port = PORT + 4;
  19439. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19440. ASSERT_NE(srv, INVALID_SOCKET);
  19441. int opt = 1;
  19442. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19443. sockaddr_in addr{};
  19444. addr.sin_family = AF_INET;
  19445. addr.sin_port = htons(static_cast<uint16_t>(port));
  19446. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19447. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19448. ASSERT_EQ(0, ::listen(srv, 1));
  19449. std::atomic<size_t> server_body_bytes{0};
  19450. auto server_thread = std::thread([&] {
  19451. sockaddr_in cli_addr{};
  19452. socklen_t cli_len = sizeof(cli_addr);
  19453. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19454. if (cli == INVALID_SOCKET) { return; }
  19455. // Bound the lifetime of the server side so a buggy client (which never
  19456. // sends the body) cannot make this thread block forever on join.
  19457. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19458. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19459. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19460. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19461. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19462. SSL *ssl = SSL_new(ctx);
  19463. SSL_set_fd(ssl, static_cast<int>(cli));
  19464. if (SSL_accept(ssl) > 0) {
  19465. // Read the request headers. Reading here also flushes the TLS 1.3
  19466. // session tickets to the client. Deliberately do NOT send
  19467. // `100 Continue`.
  19468. std::string buf;
  19469. char tmp[1024];
  19470. while (buf.find("\r\n\r\n") == std::string::npos) {
  19471. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19472. if (n <= 0) { break; }
  19473. buf.append(tmp, static_cast<size_t>(n));
  19474. }
  19475. // A correct client sends the body now; count what arrives.
  19476. auto pos = buf.find("\r\n\r\n");
  19477. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19478. while (body < 4096) {
  19479. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19480. if (n <= 0) { break; }
  19481. body += static_cast<size_t>(n);
  19482. }
  19483. server_body_bytes = body;
  19484. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19485. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19486. SSL_shutdown(ssl);
  19487. }
  19488. SSL_free(ssl);
  19489. detail::close_socket(cli);
  19490. SSL_CTX_free(ctx);
  19491. });
  19492. auto se = detail::scope_exit([&] {
  19493. server_thread.join();
  19494. detail::close_socket(srv);
  19495. });
  19496. SSLClient cli("127.0.0.1", port);
  19497. cli.enable_server_certificate_verification(false);
  19498. cli.set_connection_timeout(5, 0);
  19499. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19500. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19501. std::string body(4096, 'A');
  19502. auto res = cli.Put("/api/test", body, "application/json");
  19503. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19504. EXPECT_EQ(StatusCode::OK_200, res->status);
  19505. EXPECT_EQ(body.size(), server_body_bytes.load());
  19506. }
  19507. #endif
  19508. template <typename S, typename C>
  19509. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19510. svr.Get("/stream", [&](const Request &, Response &res) {
  19511. auto data = new std::string("01234567890123456789");
  19512. res.set_content_provider(
  19513. data->size(), "text/plain",
  19514. [&, data](size_t offset, size_t length, DataSink &sink) {
  19515. const size_t DATA_CHUNK_SIZE = 4;
  19516. const auto &d = *data;
  19517. std::this_thread::sleep_for(std::chrono::seconds(1));
  19518. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19519. return true;
  19520. },
  19521. [data](bool success) {
  19522. EXPECT_FALSE(success);
  19523. delete data;
  19524. });
  19525. });
  19526. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19527. auto i = new size_t(0);
  19528. res.set_content_provider(
  19529. "text/plain",
  19530. [i](size_t, DataSink &sink) {
  19531. if (*i < 5) {
  19532. std::this_thread::sleep_for(std::chrono::seconds(1));
  19533. sink.write("abcd", 4);
  19534. (*i)++;
  19535. } else {
  19536. sink.done();
  19537. }
  19538. return true;
  19539. },
  19540. [i](bool success) {
  19541. EXPECT_FALSE(success);
  19542. delete i;
  19543. });
  19544. });
  19545. svr.Get("/chunked", [&](const Request &, Response &res) {
  19546. auto i = new size_t(0);
  19547. res.set_chunked_content_provider(
  19548. "text/plain",
  19549. [i](size_t, DataSink &sink) {
  19550. if (*i < 5) {
  19551. std::this_thread::sleep_for(std::chrono::seconds(1));
  19552. sink.os << "abcd";
  19553. (*i)++;
  19554. } else {
  19555. sink.done();
  19556. }
  19557. return true;
  19558. },
  19559. [i](bool success) {
  19560. EXPECT_FALSE(success);
  19561. delete i;
  19562. });
  19563. });
  19564. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19565. auto se = detail::scope_exit([&] {
  19566. svr.stop();
  19567. listen_thread.join();
  19568. ASSERT_FALSE(svr.is_running());
  19569. });
  19570. svr.wait_until_ready();
  19571. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19572. {
  19573. auto start = std::chrono::steady_clock::now();
  19574. auto res = cli.Get("/stream");
  19575. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19576. std::chrono::steady_clock::now() - start)
  19577. .count();
  19578. ASSERT_FALSE(res);
  19579. EXPECT_EQ(Error::Read, res.error());
  19580. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19581. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19582. }
  19583. {
  19584. auto start = std::chrono::steady_clock::now();
  19585. auto res = cli.Get("/stream_without_length");
  19586. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19587. std::chrono::steady_clock::now() - start)
  19588. .count();
  19589. ASSERT_FALSE(res);
  19590. EXPECT_EQ(Error::Read, res.error());
  19591. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19592. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19593. }
  19594. {
  19595. auto start = std::chrono::steady_clock::now();
  19596. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19597. EXPECT_EQ("abcd", string(data, data_length));
  19598. return true;
  19599. });
  19600. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19601. std::chrono::steady_clock::now() - start)
  19602. .count();
  19603. ASSERT_FALSE(res);
  19604. EXPECT_EQ(Error::Read, res.error());
  19605. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19606. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19607. }
  19608. }
  19609. TEST(MaxTimeoutTest, ContentStream) {
  19610. time_t timeout = 2000;
  19611. time_t threshold = 200;
  19612. Server svr;
  19613. Client cli("localhost", PORT);
  19614. max_timeout_test(svr, cli, timeout, threshold);
  19615. }
  19616. #ifdef CPPHTTPLIB_SSL_ENABLED
  19617. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19618. time_t timeout = 2000;
  19619. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19620. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19621. SSLClient cli("localhost", PORT);
  19622. cli.enable_server_certificate_verification(false);
  19623. max_timeout_test(svr, cli, timeout, threshold);
  19624. }
  19625. #endif
  19626. class EventDispatcher {
  19627. public:
  19628. EventDispatcher() {}
  19629. bool wait_event(DataSink *sink) {
  19630. unique_lock<mutex> lk(m_);
  19631. int id = id_;
  19632. // Wait with timeout to prevent hanging if client disconnects
  19633. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19634. [&] { return cid_ == id; })) {
  19635. return false; // Timeout occurred
  19636. }
  19637. sink->write(message_.data(), message_.size());
  19638. return true;
  19639. }
  19640. void send_event(const string &message) {
  19641. lock_guard<mutex> lk(m_);
  19642. cid_ = id_++;
  19643. message_ = message;
  19644. cv_.notify_all();
  19645. }
  19646. private:
  19647. mutex m_;
  19648. condition_variable cv_;
  19649. atomic_int id_{0};
  19650. atomic_int cid_{-1};
  19651. string message_;
  19652. };
  19653. TEST(ClientInThreadTest, Issue2068) {
  19654. EventDispatcher ed;
  19655. Server svr;
  19656. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19657. res.set_chunked_content_provider("text/event-stream",
  19658. [&](size_t /*offset*/, DataSink &sink) {
  19659. return ed.wait_event(&sink);
  19660. });
  19661. });
  19662. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19663. svr.wait_until_ready();
  19664. thread event_thread([&] {
  19665. int id = 0;
  19666. while (svr.is_running()) {
  19667. this_thread::sleep_for(chrono::milliseconds(500));
  19668. std::stringstream ss;
  19669. ss << "data: " << id << "\n\n";
  19670. ed.send_event(ss.str());
  19671. id++;
  19672. }
  19673. });
  19674. auto se = detail::scope_exit([&] {
  19675. svr.stop();
  19676. listen_thread.join();
  19677. event_thread.join();
  19678. ASSERT_FALSE(svr.is_running());
  19679. });
  19680. {
  19681. auto client = detail::make_unique<Client>(HOST, PORT);
  19682. client->set_read_timeout(std::chrono::minutes(10));
  19683. std::atomic<bool> stop{false};
  19684. std::thread t([&] {
  19685. client->Get("/event1",
  19686. [&](const char *, size_t) -> bool { return !stop; });
  19687. });
  19688. std::this_thread::sleep_for(std::chrono::seconds(2));
  19689. stop = true;
  19690. client->stop();
  19691. t.join();
  19692. // Reset client after thread has finished
  19693. client.reset();
  19694. }
  19695. }
  19696. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19697. auto handled = false;
  19698. Server svr;
  19699. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19700. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19701. auto se = detail::scope_exit([&] {
  19702. svr.stop();
  19703. t.join();
  19704. ASSERT_FALSE(svr.is_running());
  19705. ASSERT_FALSE(handled);
  19706. });
  19707. svr.wait_until_ready();
  19708. // Two Content-Length headers with different values — must be rejected
  19709. auto req = "POST /test HTTP/1.1\r\n"
  19710. "Content-Length: 5\r\n"
  19711. "Content-Length: 10\r\n"
  19712. "\r\n"
  19713. "hello";
  19714. std::string response;
  19715. ASSERT_TRUE(send_request(1, req, &response));
  19716. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19717. response.substr(0, response.find("\r\n")));
  19718. }
  19719. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19720. auto handled = false;
  19721. Server svr;
  19722. svr.Post("/test", [&](const Request &, Response &res) {
  19723. handled = true;
  19724. res.set_content("ok", "text/plain");
  19725. });
  19726. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19727. auto se = detail::scope_exit([&] {
  19728. svr.stop();
  19729. t.join();
  19730. ASSERT_FALSE(svr.is_running());
  19731. ASSERT_TRUE(handled);
  19732. });
  19733. svr.wait_until_ready();
  19734. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19735. auto req = "POST /test HTTP/1.1\r\n"
  19736. "Host: localhost\r\n"
  19737. "Content-Length: 5\r\n"
  19738. "Content-Length: 5\r\n"
  19739. "\r\n"
  19740. "hello";
  19741. std::string response;
  19742. ASSERT_TRUE(send_request(1, req, &response));
  19743. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19744. }
  19745. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19746. Server svr;
  19747. svr.Get("/test", [](const Request &, Response &res) {
  19748. res.set_content("ok", "text/plain");
  19749. });
  19750. auto port = svr.bind_to_any_port(HOST);
  19751. thread t = thread([&] { svr.listen_after_bind(); });
  19752. auto se = detail::scope_exit([&] {
  19753. svr.stop();
  19754. t.join();
  19755. ASSERT_FALSE(svr.is_running());
  19756. });
  19757. svr.wait_until_ready();
  19758. auto status_line = [&](const std::string &host_lines) {
  19759. std::string res;
  19760. send_request(
  19761. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19762. &res, port);
  19763. return res.substr(0, res.find("\r\n"));
  19764. };
  19765. const char *accepted[] = {
  19766. "Host: localhost\r\n",
  19767. "Host: a.example:8080\r\n",
  19768. "Host: my_service\r\n",
  19769. "Host: [::1]:8080\r\n",
  19770. "Host: [fe80::1%25eth0]\r\n",
  19771. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19772. };
  19773. for (auto host_lines : accepted) {
  19774. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19775. }
  19776. const char *rejected[] = {
  19777. "Host: a.example\r\nHost: b.example\r\n",
  19778. "Host: a.example\r\nHost: a.example\r\n",
  19779. "Host: a@b.example\r\n",
  19780. "Host: a.example/b\r\n",
  19781. "Host: a.example\\b\r\n",
  19782. "Host: a.example?b\r\n",
  19783. "Host: a.example#b\r\n",
  19784. "Host: a.example b.example\r\n",
  19785. };
  19786. for (auto host_lines : rejected) {
  19787. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19788. << host_lines;
  19789. }
  19790. }
  19791. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19792. Server svr;
  19793. svr.Get("/", [](const Request &req, Response &res) {
  19794. EXPECT_EQ(2U, req.trailers.size());
  19795. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19796. // Denied
  19797. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19798. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19799. // Accepted
  19800. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19801. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19802. EXPECT_TRUE(req.has_trailer("X-World"));
  19803. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19804. res.set_content("ok", "text/plain");
  19805. });
  19806. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19807. auto se = detail::scope_exit([&] {
  19808. svr.stop();
  19809. t.join();
  19810. ASSERT_FALSE(svr.is_running());
  19811. });
  19812. svr.wait_until_ready();
  19813. const std::string req = "GET / HTTP/1.1\r\n"
  19814. "Transfer-Encoding: chunked\r\n"
  19815. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19816. "\r\n"
  19817. "0\r\n"
  19818. "Content-Length: 10\r\n"
  19819. "Host: internal.local\r\n"
  19820. "Content-Type: malicious/content\r\n"
  19821. "Cookie: any\r\n"
  19822. "Set-Cookie: any\r\n"
  19823. "X-Forwarded-For: attacker.com\r\n"
  19824. "X-Real-Ip: 1.1.1.1\r\n"
  19825. "X-Hello: hello\r\n"
  19826. "X-World: world\r\n"
  19827. "\r\n";
  19828. std::string res;
  19829. ASSERT_TRUE(send_request(1, req, &res));
  19830. }
  19831. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19832. // several field lines, and the combined value is what has to be parsed. A
  19833. // Trailer field split across lines therefore declares every name it lists;
  19834. // reading only the first line silently drops the trailers the later lines
  19835. // declare. The prohibited-trailer filter still applies to every line.
  19836. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19837. Server svr;
  19838. size_t observed_trailer_count = 0;
  19839. std::string observed_hello;
  19840. std::string observed_world;
  19841. bool observed_content_length = true;
  19842. svr.Get("/", [&](const Request &req, Response &res) {
  19843. observed_trailer_count = req.trailers.size();
  19844. observed_hello = req.get_trailer_value("X-Hello");
  19845. observed_world = req.get_trailer_value("X-World");
  19846. observed_content_length = req.has_trailer("Content-Length");
  19847. res.set_content("ok", "text/plain");
  19848. });
  19849. auto port = svr.bind_to_any_port(HOST);
  19850. thread t = thread([&]() { svr.listen_after_bind(); });
  19851. auto se = detail::scope_exit([&] {
  19852. svr.stop();
  19853. t.join();
  19854. ASSERT_FALSE(svr.is_running());
  19855. });
  19856. svr.wait_until_ready();
  19857. const std::string req = "GET / HTTP/1.1\r\n"
  19858. "Host: localhost\r\n"
  19859. "Transfer-Encoding: chunked\r\n"
  19860. "Trailer: X-Hello\r\n"
  19861. "Trailer: X-World, Content-Length\r\n"
  19862. "\r\n"
  19863. "0\r\n"
  19864. "X-Hello: hello\r\n"
  19865. "X-World: world\r\n"
  19866. "Content-Length: 10\r\n"
  19867. "\r\n";
  19868. std::string res;
  19869. ASSERT_TRUE(send_request(1, req, &res, port));
  19870. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19871. // Accepted: both field lines contribute to the declared set
  19872. EXPECT_EQ(2U, observed_trailer_count);
  19873. EXPECT_EQ(observed_hello, "hello");
  19874. EXPECT_EQ(observed_world, "world");
  19875. // Denied: a prohibited name stays prohibited on a later field line
  19876. EXPECT_FALSE(observed_content_length);
  19877. }
  19878. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19879. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19880. // unbounded run of fields that are never declared, because the counter would
  19881. // only advance for declared fields.
  19882. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19883. Server svr;
  19884. bool handler_called = false;
  19885. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19886. handler_called = true;
  19887. res.set_content("ok", "text/plain");
  19888. });
  19889. auto port = svr.bind_to_any_port(HOST);
  19890. thread t = thread([&]() { svr.listen_after_bind(); });
  19891. auto se = detail::scope_exit([&] {
  19892. svr.stop();
  19893. t.join();
  19894. ASSERT_FALSE(svr.is_running());
  19895. });
  19896. svr.wait_until_ready();
  19897. // Declare nothing, then send far more undeclared trailer fields than the
  19898. // header-count limit. Parsing must stop and reject the request rather than
  19899. // read every line.
  19900. std::string req = "GET / HTTP/1.1\r\n"
  19901. "Transfer-Encoding: chunked\r\n"
  19902. "\r\n"
  19903. "0\r\n";
  19904. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19905. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19906. }
  19907. req += "\r\n";
  19908. std::string res;
  19909. ASSERT_TRUE(send_request(1, req, &res, port));
  19910. // The request is rejected before the handler runs.
  19911. EXPECT_FALSE(handler_called);
  19912. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19913. }
  19914. // The set of declared trailer names is capped so a peer cannot grow it without
  19915. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19916. // declared past the cap is not honored, even if the field is actually sent.
  19917. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19918. Server svr;
  19919. // One name inside the cap and one past it, so the test tracks the cap rather
  19920. // than a fixed count.
  19921. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19922. const std::string within_cap_name = "X-T-0";
  19923. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19924. bool observed_within_cap = false;
  19925. bool observed_past_cap = false;
  19926. svr.Get("/", [&](const Request &req, Response &res) {
  19927. observed_within_cap = req.has_trailer(within_cap_name);
  19928. observed_past_cap = req.has_trailer(past_cap_name);
  19929. res.set_content("ok", "text/plain");
  19930. });
  19931. auto port = svr.bind_to_any_port(HOST);
  19932. thread t = thread([&]() { svr.listen_after_bind(); });
  19933. auto se = detail::scope_exit([&] {
  19934. svr.stop();
  19935. t.join();
  19936. ASSERT_FALSE(svr.is_running());
  19937. });
  19938. svr.wait_until_ready();
  19939. // Declare more trailer names than the cap in a single Trailer field, then
  19940. // actually send the first (within the cap) and the last (past it).
  19941. std::string trailer_decl = "Trailer: ";
  19942. for (int i = 0; i < declared_count; i++) {
  19943. if (i != 0) { trailer_decl += ", "; }
  19944. trailer_decl += "X-T-" + std::to_string(i);
  19945. }
  19946. trailer_decl += "\r\n";
  19947. const std::string req = "GET / HTTP/1.1\r\n"
  19948. "Host: localhost\r\n"
  19949. "Transfer-Encoding: chunked\r\n" +
  19950. trailer_decl +
  19951. "\r\n"
  19952. "0\r\n" +
  19953. within_cap_name + ": a\r\n" + past_cap_name +
  19954. ": b\r\n"
  19955. "\r\n";
  19956. std::string res;
  19957. ASSERT_TRUE(send_request(1, req, &res, port));
  19958. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19959. // A name within the cap is honored; one declared past the cap is dropped.
  19960. EXPECT_TRUE(observed_within_cap);
  19961. EXPECT_FALSE(observed_past_cap);
  19962. }
  19963. // A direct client that is not listed in trusted_proxies must not be able to
  19964. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19965. // the peer address on the actual TCP connection determines whether the
  19966. // header is honored.
  19967. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19968. Server svr;
  19969. // Deliberately does NOT include the loopback address the test client
  19970. // actually connects from, so the direct connection is not a trusted proxy.
  19971. svr.set_trusted_proxies({"203.0.113.66"});
  19972. std::string observed_remote_addr;
  19973. svr.Get("/ip", [&](const Request &req, Response &res) {
  19974. observed_remote_addr = req.remote_addr;
  19975. res.set_content("ok", "text/plain");
  19976. });
  19977. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19978. auto se = detail::scope_exit([&] {
  19979. svr.stop();
  19980. t.join();
  19981. ASSERT_FALSE(svr.is_running());
  19982. });
  19983. svr.wait_until_ready();
  19984. Client cli(HOST, PORT);
  19985. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19987. EXPECT_EQ(StatusCode::OK_200, res->status);
  19988. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19989. // ignored entirely and the real connection-level address retained.
  19990. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19991. observed_remote_addr == "127.0.0.1");
  19992. }
  19993. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19994. Server svr;
  19995. std::string observed_remote_addr;
  19996. std::string observed_xff;
  19997. svr.Get("/ip", [&](const Request &req, Response &res) {
  19998. observed_remote_addr = req.remote_addr;
  19999. observed_xff = req.get_header_value("X-Forwarded-For");
  20000. res.set_content("ok", "text/plain");
  20001. });
  20002. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20003. auto se = detail::scope_exit([&] {
  20004. svr.stop();
  20005. t.join();
  20006. ASSERT_FALSE(svr.is_running());
  20007. });
  20008. svr.wait_until_ready();
  20009. Client cli(HOST, PORT);
  20010. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  20011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20012. EXPECT_EQ(StatusCode::OK_200, res->status);
  20013. EXPECT_EQ(observed_xff, "203.0.113.66");
  20014. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20015. observed_remote_addr == "127.0.0.1");
  20016. }
  20017. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  20018. Server svr;
  20019. svr.set_trusted_proxies({"203.0.113.66"});
  20020. std::string observed_remote_addr;
  20021. std::string observed_xff;
  20022. svr.Get("/ip", [&](const Request &req, Response &res) {
  20023. observed_remote_addr = req.remote_addr;
  20024. observed_xff = req.get_header_value("X-Forwarded-For");
  20025. res.set_content("ok", "text/plain");
  20026. });
  20027. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20028. auto se = detail::scope_exit([&] {
  20029. svr.stop();
  20030. t.join();
  20031. ASSERT_FALSE(svr.is_running());
  20032. });
  20033. svr.wait_until_ready();
  20034. Client cli(HOST, PORT);
  20035. auto res = cli.Get("/ip");
  20036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20037. EXPECT_EQ(StatusCode::OK_200, res->status);
  20038. EXPECT_EQ(observed_xff, "");
  20039. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20040. observed_remote_addr == "127.0.0.1");
  20041. }
  20042. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  20043. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  20044. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  20045. Server svr;
  20046. svr.set_trusted_proxies({"127.0.0.1"});
  20047. svr.Get("/ip", [](const Request &req, Response &res) {
  20048. res.set_content(req.remote_addr, "text/plain");
  20049. });
  20050. auto port = svr.bind_to_any_port("::");
  20051. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  20052. thread t = thread([&] { svr.listen_after_bind(); });
  20053. auto se = detail::scope_exit([&] {
  20054. svr.stop();
  20055. t.join();
  20056. ASSERT_FALSE(svr.is_running());
  20057. });
  20058. svr.wait_until_ready();
  20059. Client cli("127.0.0.1", port);
  20060. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  20061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20062. EXPECT_EQ("198.51.100.23", res->body);
  20063. }
  20064. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  20065. Server svr;
  20066. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20067. svr.Get("/ip", [](const Request &req, Response &res) {
  20068. res.set_content(req.remote_addr, "text/plain");
  20069. });
  20070. auto port = svr.bind_to_any_port(HOST);
  20071. ASSERT_GT(port, 0);
  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. Client cli(HOST, port);
  20080. auto res = cli.Get(
  20081. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20083. EXPECT_EQ("198.51.100.23", res->body);
  20084. }
  20085. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20086. Server svr;
  20087. // Include the loopback address the test client actually connects from, so
  20088. // the direct connection itself is recognized as the trusted proxy hop.
  20089. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20090. std::string observed_remote_addr;
  20091. std::string observed_xff;
  20092. svr.Get("/ip", [&](const Request &req, Response &res) {
  20093. observed_remote_addr = req.remote_addr;
  20094. observed_xff = req.get_header_value("X-Forwarded-For");
  20095. res.set_content("ok", "text/plain");
  20096. });
  20097. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20098. auto se = detail::scope_exit([&] {
  20099. svr.stop();
  20100. t.join();
  20101. ASSERT_FALSE(svr.is_running());
  20102. });
  20103. svr.wait_until_ready();
  20104. Client cli(HOST, PORT);
  20105. auto res = cli.Get(
  20106. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20108. EXPECT_EQ(StatusCode::OK_200, res->status);
  20109. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20110. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20111. }
  20112. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20113. Server svr;
  20114. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20115. std::string observed_remote_addr;
  20116. std::string observed_xff;
  20117. svr.Get("/ip", [&](const Request &req, Response &res) {
  20118. observed_remote_addr = req.remote_addr;
  20119. observed_xff = req.get_header_value("X-Forwarded-For");
  20120. res.set_content("ok", "text/plain");
  20121. });
  20122. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20123. auto se = detail::scope_exit([&] {
  20124. svr.stop();
  20125. t.join();
  20126. ASSERT_FALSE(svr.is_running());
  20127. });
  20128. svr.wait_until_ready();
  20129. Client cli(HOST, PORT);
  20130. auto res = cli.Get(
  20131. "/ip",
  20132. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20134. EXPECT_EQ(StatusCode::OK_200, res->status);
  20135. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20136. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20137. }
  20138. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20139. Server svr;
  20140. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20141. std::string observed_remote_addr;
  20142. std::string observed_xff;
  20143. svr.Get("/ip", [&](const Request &req, Response &res) {
  20144. observed_remote_addr = req.remote_addr;
  20145. observed_xff = req.get_header_value("X-Forwarded-For");
  20146. res.set_content("ok", "text/plain");
  20147. });
  20148. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20149. auto se = detail::scope_exit([&] {
  20150. svr.stop();
  20151. t.join();
  20152. ASSERT_FALSE(svr.is_running());
  20153. });
  20154. svr.wait_until_ready();
  20155. Client cli(HOST, PORT);
  20156. auto res = cli.Get(
  20157. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20159. EXPECT_EQ(StatusCode::OK_200, res->status);
  20160. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20161. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20162. // and must not be selected.
  20163. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20164. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20165. }
  20166. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20167. Server svr;
  20168. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20169. std::string observed_remote_addr;
  20170. svr.Get("/ip", [&](const Request &req, Response &res) {
  20171. observed_remote_addr = req.remote_addr;
  20172. res.set_content("ok", "text/plain");
  20173. });
  20174. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20175. auto se = detail::scope_exit([&] {
  20176. svr.stop();
  20177. t.join();
  20178. ASSERT_FALSE(svr.is_running());
  20179. });
  20180. svr.wait_until_ready();
  20181. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20182. // a forged address and the trusted proxy's own address; the forged value must
  20183. // not win over the address the trusted proxy actually recorded.
  20184. Client cli(HOST, PORT);
  20185. auto res = cli.Get(
  20186. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20188. EXPECT_EQ(StatusCode::OK_200, res->status);
  20189. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20190. }
  20191. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20192. Server svr;
  20193. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20194. std::string observed_remote_addr;
  20195. std::string observed_xff;
  20196. svr.Get("/ip", [&](const Request &req, Response &res) {
  20197. observed_remote_addr = req.remote_addr;
  20198. observed_xff = req.get_header_value("X-Forwarded-For");
  20199. res.set_content("ok", "text/plain");
  20200. });
  20201. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20202. auto se = detail::scope_exit([&] {
  20203. svr.stop();
  20204. t.join();
  20205. ASSERT_FALSE(svr.is_running());
  20206. });
  20207. svr.wait_until_ready();
  20208. Client cli(HOST, PORT);
  20209. auto res = cli.Get(
  20210. "/ip",
  20211. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20213. EXPECT_EQ(StatusCode::OK_200, res->status);
  20214. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20215. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20216. }
  20217. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20218. Server svr;
  20219. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20220. std::string observed_remote_addr;
  20221. std::string observed_xff;
  20222. svr.Get("/ip", [&](const Request &req, Response &res) {
  20223. observed_remote_addr = req.remote_addr;
  20224. observed_xff = req.get_header_value("X-Forwarded-For");
  20225. res.set_content("ok", "text/plain");
  20226. });
  20227. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20228. auto se = detail::scope_exit([&] {
  20229. svr.stop();
  20230. t.join();
  20231. ASSERT_FALSE(svr.is_running());
  20232. });
  20233. svr.wait_until_ready();
  20234. std::string raw_req =
  20235. "GET /ip HTTP/1.1\r\n"
  20236. "Host: localhost\r\n"
  20237. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20238. "Connection: close\r\n"
  20239. "\r\n";
  20240. std::string out;
  20241. ASSERT_TRUE(send_request(5, raw_req, &out));
  20242. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20243. // Header parser trims surrounding whitespace of the header value
  20244. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20245. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20246. }
  20247. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20248. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20249. // their own X-Forwarded-For as a separate field line rather than extending the
  20250. // one the client sent, so every occurrence has to be taken into account.
  20251. // Reading only the first one hands back the address the client chose.
  20252. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20253. Server svr;
  20254. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20255. std::string observed_remote_addr;
  20256. size_t observed_xff_count = 0;
  20257. svr.Get("/ip", [&](const Request &req, Response &res) {
  20258. observed_remote_addr = req.remote_addr;
  20259. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20260. res.set_content("ok", "text/plain");
  20261. });
  20262. auto port = svr.bind_to_any_port(HOST);
  20263. thread t = thread([&]() { svr.listen_after_bind(); });
  20264. auto se = detail::scope_exit([&] {
  20265. svr.stop();
  20266. t.join();
  20267. ASSERT_FALSE(svr.is_running());
  20268. });
  20269. svr.wait_until_ready();
  20270. // The client supplies the first field line; the trusted proxy appends the
  20271. // address it observed as a second one.
  20272. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20273. "Host: localhost\r\n"
  20274. "X-Forwarded-For: 1.2.3.4\r\n"
  20275. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20276. "Connection: close\r\n"
  20277. "\r\n";
  20278. std::string out;
  20279. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20280. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20281. EXPECT_EQ(observed_xff_count, 2U);
  20282. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20283. // The same chain spread over one field line per hop derives the same client
  20284. // address, i.e. the split and the comma-joined representations agree.
  20285. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20286. "Host: localhost\r\n"
  20287. "X-Forwarded-For: 1.2.3.4\r\n"
  20288. "X-Forwarded-For: 198.51.100.23\r\n"
  20289. "X-Forwarded-For: 192.0.2.45\r\n"
  20290. "Connection: close\r\n"
  20291. "\r\n";
  20292. out.clear();
  20293. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20294. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20295. EXPECT_EQ(observed_xff_count, 3U);
  20296. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20297. }
  20298. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20299. // crash the server (it used to call front() on an empty vector inside
  20300. // get_client_ip). The connection-level remote address must be retained instead.
  20301. static void run_malformed_xff_test(const std::string &xff_value) {
  20302. Server svr;
  20303. svr.set_trusted_proxies({"192.0.2.45"});
  20304. std::string observed_remote_addr;
  20305. svr.Get("/ip", [&](const Request &req, Response &res) {
  20306. observed_remote_addr = req.remote_addr;
  20307. res.set_content("ok", "text/plain");
  20308. });
  20309. int port = 0;
  20310. thread t = thread([&]() {
  20311. port = svr.bind_to_any_port(HOST);
  20312. svr.listen_after_bind();
  20313. });
  20314. auto se = detail::scope_exit([&] {
  20315. svr.stop();
  20316. t.join();
  20317. ASSERT_FALSE(svr.is_running());
  20318. });
  20319. svr.wait_until_ready();
  20320. Client cli(HOST, port);
  20321. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20323. EXPECT_EQ(StatusCode::OK_200, res->status);
  20324. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20325. observed_remote_addr == "127.0.0.1");
  20326. }
  20327. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20328. run_malformed_xff_test("");
  20329. }
  20330. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20331. run_malformed_xff_test(",");
  20332. }
  20333. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20334. run_malformed_xff_test(", , ,");
  20335. }
  20336. // The same rule applies to Accept: a request whose acceptable types are spread
  20337. // over several field lines must be negotiated against all of them.
  20338. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20339. // case-insensitive connection options. Comparing the whole field value against
  20340. // one option misses a client that sends several of them, and misses every
  20341. // casing but the one written in the comparison.
  20342. //
  20343. // Sends req, reads the response, then reuses the same socket for a second
  20344. // request to find out whether the server kept the connection.
  20345. static void probe_connection_reuse(int port, const std::string &req,
  20346. bool *announced_close, bool *reusable) {
  20347. auto error = Error::Success;
  20348. auto sock = detail::create_client_socket(
  20349. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20350. /*connection_timeout_sec=*/5, 0,
  20351. /*read_timeout_sec=*/1, 0,
  20352. /*write_timeout_sec=*/5, 0, std::string(), error);
  20353. ASSERT_NE(sock, INVALID_SOCKET);
  20354. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20355. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20356. "Host: localhost\r\n"
  20357. "Connection: close\r\n"
  20358. "\r\n";
  20359. std::string first_response;
  20360. std::string second_response;
  20361. detail::process_client_socket(
  20362. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20363. [&](Stream &strm) {
  20364. if (strm.write(req.data(), req.size()) !=
  20365. static_cast<ssize_t>(req.size())) {
  20366. return false;
  20367. }
  20368. char buf[512];
  20369. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20370. // Headers plus the two-byte body of the handler below
  20371. while (reader.getline()) {
  20372. first_response += reader.ptr();
  20373. if (first_response.find("ok") != std::string::npos) { break; }
  20374. }
  20375. if (strm.write(second.data(), second.size()) !=
  20376. static_cast<ssize_t>(second.size())) {
  20377. return true;
  20378. }
  20379. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20380. while (reader2.getline()) {
  20381. second_response += reader2.ptr();
  20382. if (second_response.find("ok") != std::string::npos) { break; }
  20383. }
  20384. return true;
  20385. });
  20386. *announced_close =
  20387. first_response.find("Connection: close") != std::string::npos;
  20388. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20389. }
  20390. class ConnectionTokenTest : public ::testing::Test {
  20391. protected:
  20392. void SetUp() override {
  20393. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20394. res.set_content("ok", "text/plain");
  20395. });
  20396. port_ = svr_.bind_to_any_port(HOST);
  20397. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20398. svr_.wait_until_ready();
  20399. }
  20400. void TearDown() override {
  20401. svr_.stop();
  20402. if (thread_.joinable()) { thread_.join(); }
  20403. }
  20404. Server svr_;
  20405. int port_ = 0;
  20406. thread thread_;
  20407. };
  20408. // "close" alongside another option still closes the connection, and the
  20409. // response says so rather than leaving the peer to discover it.
  20410. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20411. bool announced_close = false;
  20412. bool reusable = true;
  20413. probe_connection_reuse(port_,
  20414. "GET /keepalive HTTP/1.1\r\n"
  20415. "Host: localhost\r\n"
  20416. "Connection: keep-alive, close\r\n"
  20417. "\r\n",
  20418. &announced_close, &reusable);
  20419. EXPECT_TRUE(announced_close);
  20420. EXPECT_FALSE(reusable);
  20421. }
  20422. // "close" split over two field lines is the same list, so it is honored too.
  20423. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20424. bool announced_close = false;
  20425. bool reusable = true;
  20426. probe_connection_reuse(port_,
  20427. "GET /keepalive HTTP/1.1\r\n"
  20428. "Host: localhost\r\n"
  20429. "Connection: keep-alive\r\n"
  20430. "Connection: close\r\n"
  20431. "\r\n",
  20432. &announced_close, &reusable);
  20433. EXPECT_TRUE(announced_close);
  20434. EXPECT_FALSE(reusable);
  20435. }
  20436. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20437. // keep-alive in the spelling everyone actually sends keeps its connection.
  20438. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20439. bool announced_close = false;
  20440. bool reusable = false;
  20441. probe_connection_reuse(port_,
  20442. "GET /keepalive HTTP/1.0\r\n"
  20443. "Host: localhost\r\n"
  20444. "Connection: keep-alive\r\n"
  20445. "\r\n",
  20446. &announced_close, &reusable);
  20447. EXPECT_FALSE(announced_close);
  20448. EXPECT_TRUE(reusable);
  20449. }
  20450. // A token the value merely contains is not the token itself.
  20451. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20452. bool announced_close = false;
  20453. bool reusable = false;
  20454. probe_connection_reuse(port_,
  20455. "GET /keepalive HTTP/1.1\r\n"
  20456. "Host: localhost\r\n"
  20457. "Connection: notclose\r\n"
  20458. "\r\n",
  20459. &announced_close, &reusable);
  20460. EXPECT_FALSE(announced_close);
  20461. EXPECT_TRUE(reusable);
  20462. }
  20463. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20464. Server svr;
  20465. std::vector<std::string> observed_types;
  20466. svr.Get("/", [&](const Request &req, Response &res) {
  20467. observed_types = req.accept_content_types;
  20468. res.set_content("ok", "text/plain");
  20469. });
  20470. auto port = svr.bind_to_any_port(HOST);
  20471. thread t = thread([&]() { svr.listen_after_bind(); });
  20472. auto se = detail::scope_exit([&] {
  20473. svr.stop();
  20474. t.join();
  20475. ASSERT_FALSE(svr.is_running());
  20476. });
  20477. svr.wait_until_ready();
  20478. Client cli(HOST, port);
  20479. Headers headers;
  20480. headers.emplace("Accept", "text/plain;q=0.5");
  20481. headers.emplace("Accept", "application/json");
  20482. auto res = cli.Get("/", headers);
  20483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20484. EXPECT_EQ(StatusCode::OK_200, res->status);
  20485. // Sorted by q-value, so the second field line's type comes first
  20486. ASSERT_EQ(2U, observed_types.size());
  20487. EXPECT_EQ("application/json", observed_types[0]);
  20488. EXPECT_EQ("text/plain", observed_types[1]);
  20489. }
  20490. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20491. // empty field line must not contribute a bare comma to the combined value.
  20492. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20493. Server svr;
  20494. std::vector<std::string> observed_types;
  20495. svr.Get("/", [&](const Request &req, Response &res) {
  20496. observed_types = req.accept_content_types;
  20497. res.set_content("ok", "text/plain");
  20498. });
  20499. auto port = svr.bind_to_any_port(HOST);
  20500. thread t = thread([&]() { svr.listen_after_bind(); });
  20501. auto se = detail::scope_exit([&] {
  20502. svr.stop();
  20503. t.join();
  20504. ASSERT_FALSE(svr.is_running());
  20505. });
  20506. svr.wait_until_ready();
  20507. // Empty first field line, then a real one
  20508. std::string raw_req = "GET / HTTP/1.1\r\n"
  20509. "Host: localhost\r\n"
  20510. "Accept:\r\n"
  20511. "Accept: application/json\r\n"
  20512. "Connection: close\r\n"
  20513. "\r\n";
  20514. std::string out;
  20515. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20516. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20517. ASSERT_EQ(1U, observed_types.size());
  20518. EXPECT_EQ("application/json", observed_types[0]);
  20519. }
  20520. // The skip in get_combined_header_value() is what keeps an empty field line
  20521. // from contributing a bare comma. Only a trailing empty field line exercises
  20522. // it: a leading one is already covered by the "combined is still empty" check,
  20523. // and parse_accept_header() now ignores the empty element either way, so the
  20524. // request-level test above can no longer tell the two apart.
  20525. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20526. Headers headers;
  20527. headers.emplace("Accept", "text/html");
  20528. headers.emplace("Accept", "");
  20529. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20530. headers.clear();
  20531. headers.emplace("Accept", "");
  20532. headers.emplace("Accept", "application/json");
  20533. EXPECT_EQ("application/json",
  20534. detail::get_combined_header_value(headers, "Accept"));
  20535. }
  20536. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20537. // An encoding offered on a later Accept-Encoding field line is still offered.
  20538. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20539. Server svr;
  20540. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20541. res.set_content(std::string(1024, 'x'), "text/plain");
  20542. });
  20543. auto port = svr.bind_to_any_port(HOST);
  20544. thread t = thread([&]() { svr.listen_after_bind(); });
  20545. auto se = detail::scope_exit([&] {
  20546. svr.stop();
  20547. t.join();
  20548. ASSERT_FALSE(svr.is_running());
  20549. });
  20550. svr.wait_until_ready();
  20551. Client cli(HOST, port);
  20552. cli.set_decompress(false);
  20553. Headers headers;
  20554. headers.emplace("Accept-Encoding", "identity");
  20555. headers.emplace("Accept-Encoding", "gzip");
  20556. auto res = cli.Get("/", headers);
  20557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20558. EXPECT_EQ(StatusCode::OK_200, res->status);
  20559. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20560. }
  20561. #endif
  20562. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20563. // Transfer-Encoding is not its body.
  20564. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20565. Server svr;
  20566. svr.set_payload_max_length(8);
  20567. svr.Post("/test", [](const Request &, Response &res) {
  20568. res.set_content("ok", "text/plain");
  20569. });
  20570. auto port = svr.bind_to_any_port(HOST);
  20571. ASSERT_GT(port, 0);
  20572. thread t = thread([&] { svr.listen_after_bind(); });
  20573. auto se = detail::scope_exit([&] {
  20574. svr.stop();
  20575. t.join();
  20576. ASSERT_FALSE(svr.is_running());
  20577. });
  20578. svr.wait_until_ready();
  20579. std::string resp;
  20580. ASSERT_TRUE(send_request(1,
  20581. "POST /test HTTP/1.1\r\n"
  20582. "Host: localhost\r\n"
  20583. "Connection: close\r\n"
  20584. "\r\n" +
  20585. std::string(16, 'X'),
  20586. &resp, port));
  20587. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20588. }
  20589. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20590. Server svr;
  20591. svr.Post("/post", [&](const Request &req, Response &res) {
  20592. res.set_content(req.body, "text/plain");
  20593. });
  20594. svr.Put("/put", [&](const Request &req, Response &res) {
  20595. res.set_content(req.body, "text/plain");
  20596. });
  20597. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20598. res.set_content(req.body, "text/plain");
  20599. });
  20600. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20601. res.set_content(req.body, "text/plain");
  20602. });
  20603. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20604. auto se = detail::scope_exit([&] {
  20605. svr.stop();
  20606. t.join();
  20607. ASSERT_FALSE(svr.is_running());
  20608. });
  20609. svr.wait_until_ready();
  20610. std::string resp;
  20611. // POST without Content-Length
  20612. ASSERT_TRUE(send_request(5,
  20613. "POST /post HTTP/1.1\r\n"
  20614. "Host: localhost\r\n"
  20615. "Connection: close\r\n"
  20616. "\r\n",
  20617. &resp));
  20618. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20619. // PUT without Content-Length
  20620. resp.clear();
  20621. ASSERT_TRUE(send_request(5,
  20622. "PUT /put HTTP/1.1\r\n"
  20623. "Host: localhost\r\n"
  20624. "Connection: close\r\n"
  20625. "\r\n",
  20626. &resp));
  20627. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20628. // PATCH without Content-Length
  20629. resp.clear();
  20630. ASSERT_TRUE(send_request(5,
  20631. "PATCH /patch HTTP/1.1\r\n"
  20632. "Host: localhost\r\n"
  20633. "Connection: close\r\n"
  20634. "\r\n",
  20635. &resp));
  20636. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20637. // DELETE without Content-Length
  20638. resp.clear();
  20639. ASSERT_TRUE(send_request(5,
  20640. "DELETE /delete HTTP/1.1\r\n"
  20641. "Host: localhost\r\n"
  20642. "Connection: close\r\n"
  20643. "\r\n",
  20644. &resp));
  20645. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20646. }
  20647. //==============================================================================
  20648. // open_stream() Tests
  20649. //==============================================================================
  20650. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20651. std::string result;
  20652. char buf[8192];
  20653. ssize_t n;
  20654. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20655. result.append(buf, static_cast<size_t>(n));
  20656. }
  20657. return result;
  20658. }
  20659. // Mock stream for unit tests
  20660. class MockStream : public Stream {
  20661. public:
  20662. std::string data;
  20663. size_t pos = 0;
  20664. ssize_t error_after = -1; // -1 = no error
  20665. explicit MockStream(const std::string &d, ssize_t err = -1)
  20666. : data(d), error_after(err) {}
  20667. bool is_readable() const override { return true; }
  20668. bool wait_readable() const override { return true; }
  20669. bool wait_writable() const override { return true; }
  20670. ssize_t read(char *ptr, size_t size) override {
  20671. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20672. if (pos >= data.size()) return 0;
  20673. size_t limit =
  20674. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20675. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20676. std::memcpy(ptr, data.data() + pos, to_read);
  20677. pos += to_read;
  20678. return static_cast<ssize_t>(to_read);
  20679. }
  20680. ssize_t write(const char *, size_t) override { return -1; }
  20681. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20682. ip = "127.0.0.1";
  20683. port = 0;
  20684. }
  20685. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20686. ip = "127.0.0.1";
  20687. port = 0;
  20688. }
  20689. socket_t socket() const override { return INVALID_SOCKET; }
  20690. time_t duration() const override { return 0; }
  20691. };
  20692. TEST(StreamHandleTest, Basic) {
  20693. ClientImpl::StreamHandle handle;
  20694. EXPECT_FALSE(handle.is_valid());
  20695. handle.response = detail::make_unique<Response>();
  20696. handle.error = Error::Connection;
  20697. EXPECT_FALSE(handle.is_valid());
  20698. handle.error = Error::Success;
  20699. EXPECT_TRUE(handle.is_valid());
  20700. }
  20701. TEST(BodyReaderTest, Basic) {
  20702. MockStream stream("Hello, World!");
  20703. detail::BodyReader reader;
  20704. reader.stream = &stream;
  20705. reader.content_length = 13;
  20706. char buf[32];
  20707. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20708. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20709. EXPECT_TRUE(reader.eof);
  20710. }
  20711. TEST(BodyReaderTest, NoStream) {
  20712. detail::BodyReader reader;
  20713. char buf[32];
  20714. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20715. EXPECT_EQ(Error::Connection, reader.last_error);
  20716. }
  20717. TEST(BodyReaderTest, Error) {
  20718. MockStream stream("Hello, World!", 5);
  20719. detail::BodyReader reader;
  20720. reader.stream = &stream;
  20721. reader.content_length = 13;
  20722. char buf[32];
  20723. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20724. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20725. EXPECT_EQ(Error::Read, reader.last_error);
  20726. }
  20727. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20728. // Mock-based StreamHandle tests relying on private internals are removed.
  20729. class OpenStreamTest : public ::testing::Test {
  20730. protected:
  20731. void SetUp() override {
  20732. svr_.Get("/hello", [](const Request &, Response &res) {
  20733. res.set_content("Hello World!", "text/plain");
  20734. });
  20735. svr_.Get("/large", [](const Request &, Response &res) {
  20736. res.set_content(std::string(10000, 'X'), "text/plain");
  20737. });
  20738. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20739. res.set_content("Hello World!", "image/jpeg");
  20740. res.set_header("Content-Encoding", "UTF-8");
  20741. });
  20742. svr_.Get("/chunked", [](const Request &, Response &res) {
  20743. res.set_chunked_content_provider("text/plain",
  20744. [](size_t offset, DataSink &sink) {
  20745. if (offset < 15) {
  20746. sink.write("chunk", 5);
  20747. return true;
  20748. }
  20749. sink.done();
  20750. return true;
  20751. });
  20752. });
  20753. svr_.Get("/compressible", [](const Request &, Response &res) {
  20754. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20755. DataSink &sink) {
  20756. if (offset < 100 * 1024) {
  20757. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20758. sink.write(chunk.data(), chunk.size());
  20759. return true;
  20760. }
  20761. sink.done();
  20762. return true;
  20763. });
  20764. });
  20765. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20766. [](const Request & /*req*/, Response &res) {
  20767. auto i = new int(0);
  20768. res.set_header("Trailer", "Content-Length, X-Allowed");
  20769. res.set_chunked_content_provider(
  20770. "text/plain",
  20771. [i](size_t /*offset*/, DataSink &sink) {
  20772. switch (*i) {
  20773. case 0: sink.os << "123"; break;
  20774. case 1: sink.os << "456"; break;
  20775. case 2: sink.os << "789"; break;
  20776. case 3: {
  20777. sink.done_with_trailer(
  20778. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20779. } break;
  20780. }
  20781. (*i)++;
  20782. return true;
  20783. },
  20784. [i](bool success) {
  20785. EXPECT_TRUE(success);
  20786. delete i;
  20787. });
  20788. });
  20789. // Echo headers endpoint for header-related tests
  20790. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20791. std::string body;
  20792. for (const auto &h : req.headers) {
  20793. body.append(h.first);
  20794. body.push_back(':');
  20795. body.append(h.second);
  20796. body.push_back('\n');
  20797. }
  20798. res.set_content(body, "text/plain");
  20799. });
  20800. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20801. std::string body;
  20802. for (const auto &h : req.headers) {
  20803. body.append(h.first);
  20804. body.push_back(':');
  20805. body.append(h.second);
  20806. body.push_back('\n');
  20807. }
  20808. res.set_content(body, "text/plain");
  20809. });
  20810. port_ = svr_.bind_to_any_port("127.0.0.1");
  20811. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20812. svr_.wait_until_ready();
  20813. }
  20814. void TearDown() override {
  20815. svr_.stop();
  20816. if (thread_.joinable()) thread_.join();
  20817. }
  20818. Server svr_;
  20819. std::thread thread_;
  20820. int port_ = 0;
  20821. };
  20822. TEST_F(OpenStreamTest, Basic) {
  20823. Client cli("127.0.0.1", port_);
  20824. auto handle = cli.open_stream("GET", "/hello");
  20825. EXPECT_TRUE(handle.is_valid());
  20826. EXPECT_EQ("Hello World!", read_all(handle));
  20827. }
  20828. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20829. Client cli("127.0.0.1", port_);
  20830. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20831. ASSERT_TRUE(handle.is_valid());
  20832. EXPECT_EQ("Hello World!", read_all(handle));
  20833. }
  20834. TEST_F(OpenStreamTest, SmallBuffer) {
  20835. Client cli("127.0.0.1", port_);
  20836. auto handle = cli.open_stream("GET", "/hello");
  20837. std::string result;
  20838. char buf[4];
  20839. ssize_t n;
  20840. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20841. result.append(buf, static_cast<size_t>(n));
  20842. EXPECT_EQ("Hello World!", result);
  20843. }
  20844. TEST_F(OpenStreamTest, DefaultHeaders) {
  20845. Client cli("127.0.0.1", port_);
  20846. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20847. {
  20848. auto handle = cli.open_stream("GET", "/echo-headers");
  20849. ASSERT_TRUE(handle.is_valid());
  20850. auto body = read_all(handle);
  20851. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20852. std::string::npos);
  20853. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20854. std::string::npos);
  20855. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20856. }
  20857. // open_stream POST with body and no explicit content_type should NOT add
  20858. // text/plain Content-Type (behavior differs from non-streaming path), but
  20859. // should include Content-Length
  20860. {
  20861. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20862. ASSERT_TRUE(handle.is_valid());
  20863. auto body = read_all(handle);
  20864. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20865. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20866. }
  20867. // open_stream POST with explicit Content-Type should preserve it
  20868. {
  20869. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20870. {{"Content-Type", "application/custom"}},
  20871. "{}", "application/custom");
  20872. ASSERT_TRUE(handle.is_valid());
  20873. auto body = read_all(handle);
  20874. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20875. }
  20876. // User-specified User-Agent must not be overwritten for stream API
  20877. {
  20878. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20879. {{"User-Agent", "MyAgent/1.2"}});
  20880. ASSERT_TRUE(handle.is_valid());
  20881. auto body = read_all(handle);
  20882. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20883. }
  20884. }
  20885. TEST_F(OpenStreamTest, Large) {
  20886. Client cli("127.0.0.1", port_);
  20887. auto handle = cli.open_stream("GET", "/large");
  20888. EXPECT_EQ(10000u, read_all(handle).size());
  20889. }
  20890. TEST_F(OpenStreamTest, ConnectionError) {
  20891. Client cli("127.0.0.1", 9999);
  20892. auto handle = cli.open_stream("GET", "/hello");
  20893. EXPECT_FALSE(handle.is_valid());
  20894. }
  20895. TEST_F(OpenStreamTest, Chunked) {
  20896. Client cli("127.0.0.1", port_);
  20897. auto handle = cli.open_stream("GET", "/chunked");
  20898. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20899. "Transfer-Encoding") == "chunked");
  20900. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20901. }
  20902. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20903. Client cli("127.0.0.1", port_);
  20904. auto handle =
  20905. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20906. ASSERT_TRUE(handle.is_valid());
  20907. // Consume body to allow trailers to be received/parsed
  20908. auto body = read_all(handle);
  20909. // Explicitly parse trailers (ensure trailers are available for assertion)
  20910. handle.parse_trailers_if_needed();
  20911. EXPECT_EQ(std::string("123456789"), body);
  20912. // The response should include a Trailer header declaring both names
  20913. ASSERT_TRUE(handle.response);
  20914. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20915. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20916. handle.response->get_header_value("Trailer"));
  20917. // Prohibited trailer must not be present
  20918. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20919. // Allowed trailer should be present
  20920. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20921. EXPECT_EQ(std::string("yes"),
  20922. handle.response->get_trailer_value("X-Allowed"));
  20923. // Verify trailers are NOT present as regular headers
  20924. EXPECT_EQ(std::string(""),
  20925. handle.response->get_header_value("Content-Length"));
  20926. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20927. }
  20928. // Accepts one connection on an OS-assigned port, which it hands over through
  20929. // port_promise, reads the request head and sends back response. after_send,
  20930. // if given, runs on the connection before it is closed.
  20931. static std::thread
  20932. serve_single_response(std::promise<int> &port_promise,
  20933. const std::string &response,
  20934. std::function<void(socket_t)> after_send = nullptr) {
  20935. return std::thread([&port_promise, response, after_send] {
  20936. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20937. default_socket_options(srv);
  20938. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20939. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20940. sockaddr_in addr{};
  20941. addr.sin_family = AF_INET;
  20942. addr.sin_port = htons(0); // Let OS assign a free port
  20943. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20944. int opt = 1;
  20945. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20946. #ifdef _WIN32
  20947. reinterpret_cast<const char *>(&opt),
  20948. #else
  20949. &opt,
  20950. #endif
  20951. sizeof(opt));
  20952. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20953. ::listen(srv, 1) != 0) {
  20954. port_promise.set_value(-1);
  20955. detail::close_socket(srv);
  20956. return;
  20957. }
  20958. socklen_t addr_len = sizeof(addr);
  20959. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20960. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20961. sockaddr_in cli_addr{};
  20962. socklen_t cli_len = sizeof(cli_addr);
  20963. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20964. if (cli != INVALID_SOCKET) {
  20965. // Read the complete HTTP request (until the blank line that terminates
  20966. // headers) before sending the response. If the server closes the socket
  20967. // while the client's request data is still unread in the kernel receive
  20968. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20969. // connection on both sides: it discards the client's receive buffer
  20970. // (which already holds our response) and causes any in-progress write on
  20971. // the client to fail with ECONNRESET. Reading all request data first
  20972. // ensures close() emits a graceful FIN.
  20973. {
  20974. char rbuf[256];
  20975. std::string req;
  20976. while (req.find("\r\n\r\n") == std::string::npos) {
  20977. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20978. if (n <= 0) { break; }
  20979. req.append(rbuf, static_cast<size_t>(n));
  20980. }
  20981. }
  20982. ::send(cli,
  20983. #ifdef _WIN32
  20984. static_cast<const char *>(response.c_str()),
  20985. static_cast<int>(response.size()),
  20986. #else
  20987. response.c_str(), response.size(),
  20988. #endif
  20989. 0);
  20990. if (after_send) { after_send(cli); }
  20991. detail::close_socket(cli);
  20992. }
  20993. detail::close_socket(srv);
  20994. });
  20995. }
  20996. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20997. #ifndef _WIN32
  20998. signal(SIGPIPE, SIG_IGN);
  20999. #endif
  21000. std::promise<int> port_promise;
  21001. auto port_future = port_promise.get_future();
  21002. auto server_thread =
  21003. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  21004. "Content-Type: text/plain\r\n"
  21005. "Content-Length: not-a-number\r\n"
  21006. "Connection: close\r\n"
  21007. "\r\n"
  21008. "hello");
  21009. auto port = port_future.get();
  21010. ASSERT_GT(port, 0);
  21011. Client cli("127.0.0.1", port);
  21012. auto handle = cli.open_stream("GET", "/");
  21013. EXPECT_FALSE(handle.is_valid());
  21014. server_thread.join();
  21015. }
  21016. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  21017. #ifndef _WIN32
  21018. signal(SIGPIPE, SIG_IGN);
  21019. #endif
  21020. std::promise<int> port_promise;
  21021. auto port_future = port_promise.get_future();
  21022. auto server_thread = serve_single_response(
  21023. port_promise, "HTTP/1.1 200 OK\r\n"
  21024. "Content-Type: text/plain\r\n"
  21025. "Content-Length: 99999999999999999999999999\r\n"
  21026. "Connection: close\r\n"
  21027. "\r\n"
  21028. "hello");
  21029. auto port = port_future.get();
  21030. ASSERT_GT(port, 0);
  21031. // Historically std::stoull would throw std::out_of_range here and crash
  21032. // the process, then parsing silently clamped to a bogus framing length and
  21033. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  21034. // so the stream fails to open, matching the not-a-number case above. The
  21035. // process still must NOT terminate.
  21036. Client cli("127.0.0.1", port);
  21037. auto handle = cli.open_stream("GET", "/");
  21038. EXPECT_FALSE(handle.is_valid());
  21039. server_thread.join();
  21040. }
  21041. #ifndef _WIN32
  21042. // As above for the body of a streamed request: a send() cut short by the write
  21043. // timeout must not leave the rest of the body unsent.
  21044. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  21045. signal(SIGPIPE, SIG_IGN);
  21046. Server svr;
  21047. svr.set_socket_options([](socket_t sock) {
  21048. int size = 8192;
  21049. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  21050. reinterpret_cast<const char *>(&size), sizeof(size));
  21051. });
  21052. svr.Post("/size", [](const Request &, Response &res,
  21053. const ContentReader &content_reader) {
  21054. // Outlast the client's write timeout before reading the body.
  21055. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  21056. size_t received = 0;
  21057. content_reader([&](const char *, size_t len) {
  21058. received += len;
  21059. return true;
  21060. });
  21061. res.set_content(std::to_string(received), "text/plain");
  21062. });
  21063. auto port = svr.bind_to_any_port(HOST);
  21064. std::thread t([&]() { svr.listen_after_bind(); });
  21065. auto se = detail::scope_exit([&] {
  21066. svr.stop();
  21067. t.join();
  21068. });
  21069. svr.wait_until_ready();
  21070. Client cli(HOST, port);
  21071. cli.set_write_timeout(0, 500000);
  21072. cli.set_socket_options([](socket_t sock) {
  21073. int size = 8192;
  21074. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21075. reinterpret_cast<const char *>(&size), sizeof(size));
  21076. });
  21077. const std::string body(4 * 1024 * 1024, 'A');
  21078. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21079. "application/octet-stream");
  21080. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21081. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21082. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21083. }
  21084. #endif
  21085. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21086. std::promise<void> slow_started;
  21087. auto slow_started_future = slow_started.get_future();
  21088. Server svr;
  21089. svr.Get("/slow", [&](const Request &, Response &res) {
  21090. slow_started.set_value();
  21091. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21092. res.set_content("slow", "text/plain");
  21093. });
  21094. svr.Get("/fast", [](const Request &, Response &res) {
  21095. res.set_content("fast", "text/plain");
  21096. });
  21097. auto port = svr.bind_to_any_port(HOST);
  21098. std::thread t([&]() { svr.listen_after_bind(); });
  21099. auto se = detail::scope_exit([&] {
  21100. svr.stop();
  21101. t.join();
  21102. });
  21103. svr.wait_until_ready();
  21104. Client cli(HOST, port);
  21105. std::string slow_body;
  21106. std::thread slow_thread([&] {
  21107. auto res = cli.Get("/slow");
  21108. if (res) { slow_body = res->body; }
  21109. });
  21110. slow_started_future.wait();
  21111. auto result = stream::Get(cli, "/fast");
  21112. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21113. slow_thread.join();
  21114. EXPECT_EQ("slow", slow_body);
  21115. EXPECT_EQ("fast", fast_body);
  21116. }
  21117. // Serves `response` to the single request `fn` makes with a fresh client.
  21118. template <typename Fn>
  21119. static void with_single_response(const std::string &response, Fn fn) {
  21120. #ifndef _WIN32
  21121. signal(SIGPIPE, SIG_IGN);
  21122. #endif
  21123. std::promise<int> port_promise;
  21124. auto port_future = port_promise.get_future();
  21125. auto server_thread = serve_single_response(port_promise, response);
  21126. auto se = detail::scope_exit([&] { server_thread.join(); });
  21127. auto port = port_future.get();
  21128. ASSERT_GT(port, 0);
  21129. Client cli("127.0.0.1", port);
  21130. fn(cli);
  21131. }
  21132. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21133. // too, also in a build without the decoder for the advertised coding.
  21134. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21135. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21136. const auto response = "HTTP/1.1 200 OK\r\n"
  21137. "Content-Encoding: gzip\r\n"
  21138. "Content-Length: " +
  21139. std::to_string(gzipped.size()) +
  21140. "\r\n"
  21141. "Connection: close\r\n\r\n" +
  21142. gzipped;
  21143. with_single_response(response, [&](Client &cli) {
  21144. cli.set_decompress(false);
  21145. auto handle = cli.open_stream("GET", "/");
  21146. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21147. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21148. EXPECT_EQ(gzipped, read_all(handle));
  21149. EXPECT_FALSE(handle.has_read_error());
  21150. });
  21151. with_single_response(response, [&](Client &cli) {
  21152. cli.set_decompress(false);
  21153. auto res = stream::Get(cli, "/", 7);
  21154. ASSERT_TRUE(res) << to_string(res.error());
  21155. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21156. EXPECT_EQ(gzipped, res.read_all());
  21157. EXPECT_FALSE(res.has_read_error());
  21158. });
  21159. }
  21160. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21161. // Neither Content-Length nor chunked: the body ends at the close
  21162. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21163. "Connection: close\r\n"
  21164. "\r\n"
  21165. "hello";
  21166. with_single_response(close_delimited, [](Client &cli) {
  21167. auto handle = cli.open_stream("GET", "/");
  21168. ASSERT_TRUE(handle.is_valid());
  21169. EXPECT_EQ("hello", read_all(handle));
  21170. EXPECT_FALSE(handle.has_read_error());
  21171. });
  21172. // A close before the end of the Content-Length is still an error
  21173. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21174. "Content-Length: 10\r\n"
  21175. "\r\n"
  21176. "hello";
  21177. with_single_response(short_content_length, [](Client &cli) {
  21178. auto handle = cli.open_stream("GET", "/");
  21179. ASSERT_TRUE(handle.is_valid());
  21180. read_all(handle);
  21181. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21182. });
  21183. // So is a close before the last chunk
  21184. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21185. "Transfer-Encoding: chunked\r\n"
  21186. "\r\n"
  21187. "5\r\nhello\r\n";
  21188. with_single_response(short_chunked, [](Client &cli) {
  21189. auto handle = cli.open_stream("GET", "/");
  21190. ASSERT_TRUE(handle.is_valid());
  21191. read_all(handle);
  21192. EXPECT_TRUE(handle.has_read_error());
  21193. });
  21194. }
  21195. #ifdef CPPHTTPLIB_SSL_ENABLED
  21196. // Serves `response` to one request, then closes with or without a close_notify
  21197. template <typename Fn>
  21198. static void with_single_tls_response(const std::string &response,
  21199. bool close_notify, Fn fn) {
  21200. #ifndef _WIN32
  21201. signal(SIGPIPE, SIG_IGN);
  21202. #endif
  21203. std::promise<int> port_promise;
  21204. auto port_future = port_promise.get_future();
  21205. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21206. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21207. default_socket_options(srv);
  21208. sockaddr_in addr{};
  21209. addr.sin_family = AF_INET;
  21210. addr.sin_port = htons(0);
  21211. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21212. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21213. ::listen(srv, 1) != 0) {
  21214. port_promise.set_value(-1);
  21215. detail::close_socket(srv);
  21216. return;
  21217. }
  21218. socklen_t addr_len = sizeof(addr);
  21219. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21220. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21221. auto cli = ::accept(srv, nullptr, nullptr);
  21222. if (cli != INVALID_SOCKET) {
  21223. auto ctx = tls::create_server_context();
  21224. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21225. nullptr);
  21226. auto session = tls::create_session(ctx, cli);
  21227. tls::TlsError err;
  21228. if (tls::accept_nonblocking(session, cli, 5, 0, &err)) {
  21229. // The request head first, so that closing the socket sends a FIN
  21230. // rather than an RST for the unread bytes.
  21231. std::string req;
  21232. char buf[256];
  21233. while (req.find("\r\n\r\n") == std::string::npos) {
  21234. auto n = tls::read(session, buf, sizeof(buf), err);
  21235. if (n <= 0) { break; }
  21236. req.append(buf, static_cast<size_t>(n));
  21237. }
  21238. size_t sent = 0;
  21239. while (sent < response.size()) {
  21240. auto n = tls::write(session, response.data() + sent,
  21241. response.size() - sent, err);
  21242. if (n <= 0) { break; }
  21243. sent += static_cast<size_t>(n);
  21244. }
  21245. if (close_notify) { tls::shutdown(session, true); }
  21246. }
  21247. tls::free_session(session);
  21248. detail::close_socket(cli);
  21249. tls::free_context(ctx);
  21250. }
  21251. detail::close_socket(srv);
  21252. });
  21253. auto se = detail::scope_exit([&] { server_thread.join(); });
  21254. auto port = port_future.get();
  21255. ASSERT_GT(port, 0);
  21256. SSLClient cli("127.0.0.1", port);
  21257. cli.enable_server_certificate_verification(false);
  21258. fn(cli);
  21259. }
  21260. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21261. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21262. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21263. "Connection: close\r\n"
  21264. "\r\n"
  21265. "hello";
  21266. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21267. auto res = cli.Get("/");
  21268. ASSERT_TRUE(res) << to_string(res.error());
  21269. EXPECT_EQ("hello", res->body);
  21270. });
  21271. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21272. auto res = cli.Get("/");
  21273. ASSERT_FALSE(res);
  21274. EXPECT_EQ(Error::Read, res.error());
  21275. });
  21276. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21277. auto handle = cli.open_stream("GET", "/");
  21278. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21279. read_all(handle);
  21280. EXPECT_TRUE(handle.has_read_error());
  21281. });
  21282. // A framed body ends where its framing says, with or without the alert
  21283. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21284. "Content-Length: 5\r\n"
  21285. "Connection: close\r\n"
  21286. "\r\n"
  21287. "hello";
  21288. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21289. auto res = cli.Get("/");
  21290. ASSERT_TRUE(res) << to_string(res.error());
  21291. EXPECT_EQ("hello", res->body);
  21292. });
  21293. }
  21294. #endif
  21295. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21296. const char *responses[] = {
  21297. "HTTP/1.1 103 Early Hints\r\n"
  21298. "Link: </style.css>; rel=preload\r\n"
  21299. "\r\n"
  21300. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21301. "HTTP/1.1 100 Continue\r\n"
  21302. "X-Note: interim\r\n"
  21303. "\r\n"
  21304. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21305. };
  21306. for (auto response : responses) {
  21307. with_single_response(response, [](Client &cli) {
  21308. auto res = cli.Get("/");
  21309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21310. EXPECT_EQ(StatusCode::OK_200, res->status);
  21311. EXPECT_EQ("ok", res->body);
  21312. });
  21313. }
  21314. }
  21315. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21316. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21317. const std::string final_response =
  21318. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21319. std::string interims;
  21320. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21321. interims += interim;
  21322. }
  21323. with_single_response(interims + final_response, [](Client &cli) {
  21324. auto res = cli.Get("/");
  21325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21326. EXPECT_EQ("ok", res->body);
  21327. });
  21328. with_single_response(interims + interim + final_response, [](Client &cli) {
  21329. auto res = cli.Get("/");
  21330. ASSERT_FALSE(res);
  21331. EXPECT_EQ(Error::Read, res.error());
  21332. });
  21333. }
  21334. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21335. #ifndef _WIN32
  21336. signal(SIGPIPE, SIG_IGN);
  21337. #endif
  21338. // The server answers the head without asking for the body. Bytes it then
  21339. // reads on the connection would be taken for the body the request declared.
  21340. auto closed_by_client = false;
  21341. std::promise<int> port_promise;
  21342. auto server_thread = serve_single_response(
  21343. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21344. [&](socket_t sock) {
  21345. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21346. char buf[256];
  21347. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21348. });
  21349. Client cli("127.0.0.1", port_promise.get_future().get());
  21350. cli.set_keep_alive(true);
  21351. cli.set_read_timeout(1, 0);
  21352. // Long enough for the client to send Expect: 100-continue.
  21353. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21355. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21356. cli.Get("/second");
  21357. server_thread.join();
  21358. EXPECT_TRUE(closed_by_client);
  21359. }
  21360. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21361. // Long enough for the client to send Expect: 100-continue
  21362. with_single_response(
  21363. "HTTP/1.1 103 Early Hints\r\n"
  21364. "Link: </style.css>; rel=preload\r\n"
  21365. "\r\n"
  21366. "HTTP/1.1 401 Unauthorized\r\n"
  21367. "Content-Length: 0\r\n\r\n",
  21368. [](Client &cli) {
  21369. cli.set_read_timeout(2, 0);
  21370. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21372. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21373. });
  21374. }
  21375. #ifdef CPPHTTPLIB_SSL_ENABLED
  21376. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21377. #ifndef _WIN32
  21378. signal(SIGPIPE, SIG_IGN);
  21379. #endif
  21380. auto reused = false;
  21381. std::promise<int> port_promise;
  21382. auto server_thread = serve_single_response(
  21383. port_promise,
  21384. "HTTP/1.1 401 Unauthorized\r\n"
  21385. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21386. "Content-Length: 0\r\n\r\n",
  21387. [&](socket_t sock) {
  21388. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21389. char buf[256];
  21390. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21391. });
  21392. Client cli("127.0.0.1", port_promise.get_future().get());
  21393. cli.set_keep_alive(true);
  21394. cli.set_digest_auth("user", "pass");
  21395. cli.set_read_timeout(1, 0);
  21396. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21397. server_thread.join();
  21398. EXPECT_FALSE(reused);
  21399. }
  21400. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21401. // Any other answer to CONNECT would read as the origin's response.
  21402. struct {
  21403. const char *response;
  21404. bool passed_on;
  21405. } cases[] = {
  21406. {"HTTP/1.1 201 Created\r\n"
  21407. "Set-Cookie: session=from-proxy\r\n"
  21408. "Content-Length: 0\r\n\r\n",
  21409. false},
  21410. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21411. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21412. "Content-Length: 0\r\n\r\n",
  21413. true},
  21414. };
  21415. for (const auto &c : cases) {
  21416. std::promise<int> port_promise;
  21417. auto server_thread = serve_single_response(port_promise, c.response);
  21418. SSLClient cli("example.com", 443);
  21419. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21420. auto res = cli.Get("/");
  21421. server_thread.join();
  21422. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21423. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21424. if (res) {
  21425. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21426. }
  21427. }
  21428. }
  21429. #endif
  21430. // Records the client's error logger calls as "error METHOD path", or
  21431. // "error null" for a call without a request
  21432. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21433. return [&log](const Error &err, const Request *req) {
  21434. log.push_back(to_string(err) + " " +
  21435. (req ? req->method + " " + req->path : "null"));
  21436. };
  21437. }
  21438. // A failed request is reported once, with the request the caller made
  21439. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21440. Server svr;
  21441. svr.Get("/big", [](const Request &, Response &res) {
  21442. res.set_content(std::string(100000, 'b'), "text/plain");
  21443. });
  21444. auto port = svr.bind_to_any_port(HOST);
  21445. std::thread t([&]() { svr.listen_after_bind(); });
  21446. auto se = detail::scope_exit([&] {
  21447. svr.stop();
  21448. t.join();
  21449. });
  21450. svr.wait_until_ready();
  21451. Client cli(HOST, port);
  21452. std::vector<std::string> log;
  21453. cli.set_error_logger(record_errors(log));
  21454. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21455. cli.Get("/big", [](const char *, size_t) { return false; });
  21456. EXPECT_EQ(expected, log);
  21457. log.clear();
  21458. cli.Get("/big", [](size_t, size_t) { return false; });
  21459. EXPECT_EQ(expected, log);
  21460. }
  21461. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21462. // Fails while the body is read
  21463. auto broken = [](const Request &, Response &res) {
  21464. res.set_content_provider(10, "text/plain",
  21465. [](size_t, size_t, DataSink &) { return false; });
  21466. };
  21467. Server other;
  21468. other.Get("/broken", broken);
  21469. auto other_port = other.bind_to_any_port(HOST);
  21470. std::thread other_t([&]() { other.listen_after_bind(); });
  21471. auto other_se = detail::scope_exit([&] {
  21472. other.stop();
  21473. other_t.join();
  21474. });
  21475. other.wait_until_ready();
  21476. Server svr;
  21477. svr.Get("/broken", broken);
  21478. svr.Get("/same-origin",
  21479. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21480. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21481. res.set_redirect("http://" + std::string(HOST) + ":" +
  21482. std::to_string(other_port) + "/broken");
  21483. });
  21484. auto port = svr.bind_to_any_port(HOST);
  21485. std::thread t([&]() { svr.listen_after_bind(); });
  21486. auto se = detail::scope_exit([&] {
  21487. svr.stop();
  21488. t.join();
  21489. });
  21490. svr.wait_until_ready();
  21491. Client cli(HOST, port);
  21492. cli.set_follow_location(true);
  21493. std::vector<std::string> log;
  21494. cli.set_error_logger(record_errors(log));
  21495. for (auto path : {"/same-origin", "/cross-origin"}) {
  21496. log.clear();
  21497. auto res = cli.Get(path);
  21498. ASSERT_FALSE(res);
  21499. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21500. log);
  21501. }
  21502. }
  21503. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21504. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21505. std::vector<std::string> log;
  21506. cli.set_error_logger(record_errors(log));
  21507. auto handle = cli.open_stream("GET", "/x");
  21508. EXPECT_FALSE(handle.is_valid());
  21509. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21510. log);
  21511. });
  21512. }
  21513. #ifdef CPPHTTPLIB_SSL_ENABLED
  21514. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21515. // Not a TLS server, so the handshake fails. It waits for a request line in
  21516. // the handshake bytes, so a short read timeout lets it close quickly.
  21517. Server svr;
  21518. svr.set_read_timeout(0, 100000);
  21519. svr.Get("/x", [](const Request &, Response &res) {
  21520. res.set_content("x", "text/plain");
  21521. });
  21522. auto port = svr.bind_to_any_port(HOST);
  21523. std::thread t([&]() { svr.listen_after_bind(); });
  21524. auto se = detail::scope_exit([&] {
  21525. svr.stop();
  21526. t.join();
  21527. });
  21528. svr.wait_until_ready();
  21529. std::vector<std::string> log;
  21530. SSLClient cli(HOST, port);
  21531. cli.enable_server_certificate_verification(false);
  21532. cli.set_error_logger(record_errors(log));
  21533. auto res = cli.Get("/x");
  21534. ASSERT_FALSE(res);
  21535. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21536. log.clear();
  21537. auto handle = cli.open_stream("GET", "/x");
  21538. EXPECT_FALSE(handle.is_valid());
  21539. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21540. log.clear();
  21541. SSLClient no_ca(HOST, port);
  21542. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21543. no_ca.set_error_logger(record_errors(log));
  21544. res = no_ca.Get("/x");
  21545. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21546. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21547. }
  21548. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21549. #ifndef _WIN32
  21550. signal(SIGPIPE, SIG_IGN);
  21551. #endif
  21552. // Refused, answered with a challenge, or closed without an answer
  21553. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21554. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21555. "Content-Length: 0\r\n\r\n",
  21556. ""}) {
  21557. std::promise<int> port_promise;
  21558. auto server_thread = serve_single_response(port_promise, response);
  21559. SSLClient cli("example.com", 443);
  21560. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21561. std::vector<std::string> log;
  21562. cli.set_error_logger(record_errors(log));
  21563. auto res = cli.Get("/");
  21564. server_thread.join();
  21565. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21566. << response;
  21567. }
  21568. }
  21569. #endif
  21570. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21571. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21572. // the chunked coding and drop Content-Length, so a front-end that trusts
  21573. // Content-Length would disagree about where the body ends (response
  21574. // smuggling). The client must reject such a response.
  21575. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21576. for (const char *te : {"chunked", "gzip, chunked"}) {
  21577. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21578. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21579. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21580. "5\r\nhello\r\n0\r\n\r\n";
  21581. with_single_response(response, [&](Client &cli) {
  21582. auto res = cli.Get("/");
  21583. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21584. EXPECT_EQ(Error::Read, res.error()) << te;
  21585. });
  21586. with_single_response(response, [&](Client &cli) {
  21587. auto handle = cli.open_stream("GET", "/");
  21588. EXPECT_FALSE(handle.is_valid()) << te;
  21589. EXPECT_EQ(Error::Read, handle.error) << te;
  21590. });
  21591. }
  21592. }
  21593. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21594. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21595. // closing the connection (unlike a request, which must be rejected).
  21596. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21597. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21598. "Transfer-Encoding: chunked\r\n"
  21599. "Connection: close\r\n"
  21600. "\r\n"
  21601. "5\r\nhello\r\n0\r\n\r\n",
  21602. "HTTP/1.1 200 OK\r\n"
  21603. "Transfer-Encoding: gzip\r\n"
  21604. "Connection: close\r\n"
  21605. "\r\n"
  21606. "hello"}) {
  21607. with_single_response(response, [&](Client &cli) {
  21608. auto res = cli.Get("/");
  21609. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21610. EXPECT_EQ("hello", res->body);
  21611. });
  21612. with_single_response(response, [&](Client &cli) {
  21613. auto handle = cli.open_stream("GET", "/");
  21614. ASSERT_TRUE(handle.is_valid()) << response;
  21615. EXPECT_EQ("hello", read_all(handle));
  21616. });
  21617. }
  21618. }
  21619. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21620. // framing headers describe nothing to read and must not be rejected.
  21621. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21622. const std::string framing = "Content-Length: 5\r\n"
  21623. "Transfer-Encoding: chunked\r\n"
  21624. "Connection: close\r\n"
  21625. "\r\n";
  21626. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21627. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21628. });
  21629. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21630. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21631. });
  21632. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21633. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21634. with_single_response(response, [&](Client &cli) {
  21635. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21636. });
  21637. with_single_response(response, [&](Client &cli) {
  21638. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21639. });
  21640. }
  21641. }
  21642. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21643. // header section, so a stream opened on one has nothing to read, whatever
  21644. // framing or coding headers it carries.
  21645. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21646. struct Case {
  21647. const char *method;
  21648. const char *status;
  21649. };
  21650. // A reader of the declared body reports an early close when nothing
  21651. // follows, and hands back what does.
  21652. struct Framing {
  21653. const char *headers;
  21654. const char *after;
  21655. };
  21656. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21657. Case{"GET", "304 Not Modified"}}) {
  21658. for (const auto &f :
  21659. {Framing{"Content-Length: 5\r\n", ""},
  21660. Framing{"Content-Length: 5\r\n", "hello"},
  21661. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21662. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21663. // Not decoded, so a build without Brotli opens it too
  21664. Framing{"Content-Encoding: br\r\n", ""}}) {
  21665. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21666. "Connection: close\r\n"
  21667. "\r\n" +
  21668. f.after;
  21669. with_single_response(response, [&](Client &cli) {
  21670. auto handle = cli.open_stream(c.method, "/");
  21671. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21672. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21673. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21674. });
  21675. }
  21676. }
  21677. }
  21678. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21679. // response, is faulty framing, so the connection is not reused after it.
  21680. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21681. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21682. "Content-Length: 0\r\n"
  21683. "Transfer-Encoding: chunked\r\n"
  21684. "\r\n"
  21685. "5\r\nhello\r\n0\r\n\r\n",
  21686. "HTTP/1.0 200 Connection established\r\n"
  21687. "Connection: keep-alive\r\n"
  21688. "Transfer-Encoding: chunked\r\n"
  21689. "\r\n"
  21690. "5\r\nhello\r\n0\r\n\r\n"}) {
  21691. with_single_response(response, [&](Client &cli) {
  21692. cli.set_keep_alive(true);
  21693. auto res = cli.Get("/");
  21694. ASSERT_TRUE(res) << response;
  21695. EXPECT_EQ("hello", res->body);
  21696. EXPECT_FALSE(cli.is_socket_open()) << response;
  21697. });
  21698. }
  21699. }
  21700. // A payload max length of 0 means no limit, however the body is framed.
  21701. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21702. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21703. "Transfer-Encoding: chunked\r\n"
  21704. "\r\n"
  21705. "5\r\nhello\r\n0\r\n\r\n",
  21706. "HTTP/1.1 200 OK\r\n"
  21707. "Connection: close\r\n"
  21708. "\r\n"
  21709. "hello"}) {
  21710. with_single_response(response, [&](Client &cli) {
  21711. cli.set_payload_max_length(0);
  21712. auto res = cli.Get("/");
  21713. ASSERT_TRUE(res) << response;
  21714. EXPECT_EQ("hello", res->body) << response;
  21715. });
  21716. }
  21717. }
  21718. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21719. Server svr;
  21720. svr.set_payload_max_length(0);
  21721. svr.Post("/echo", [](const Request &req, Response &res) {
  21722. res.set_content(req.body, "text/plain");
  21723. });
  21724. auto port = svr.bind_to_any_port(HOST);
  21725. thread t = thread([&] { svr.listen_after_bind(); });
  21726. auto se = detail::scope_exit([&] {
  21727. svr.stop();
  21728. t.join();
  21729. ASSERT_FALSE(svr.is_running());
  21730. });
  21731. svr.wait_until_ready();
  21732. Client cli(HOST, port);
  21733. auto res = cli.Post(
  21734. "/echo",
  21735. [](size_t /*offset*/, DataSink &sink) {
  21736. sink.write("hello", 5);
  21737. sink.done();
  21738. return true;
  21739. },
  21740. "text/plain");
  21741. ASSERT_TRUE(res);
  21742. EXPECT_EQ(StatusCode::OK_200, res->status);
  21743. EXPECT_EQ("hello", res->body);
  21744. }
  21745. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21746. TEST_F(OpenStreamTest, Gzip) {
  21747. Client cli("127.0.0.1", port_);
  21748. auto handle = cli.open_stream("GET", "/compressible", {},
  21749. {{"Accept-Encoding", "gzip"}});
  21750. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21751. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21752. }
  21753. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21754. Client cli("127.0.0.1", port_);
  21755. auto handle =
  21756. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21757. {{"Accept-Encoding", "gzip"}});
  21758. ASSERT_TRUE(handle.is_valid());
  21759. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21760. EXPECT_EQ("123456789", read_all(handle));
  21761. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21762. }
  21763. #endif
  21764. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21765. TEST_F(OpenStreamTest, Brotli) {
  21766. Client cli("127.0.0.1", port_);
  21767. auto handle =
  21768. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21769. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21770. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21771. }
  21772. #endif
  21773. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21774. TEST_F(OpenStreamTest, Zstd) {
  21775. Client cli("127.0.0.1", port_);
  21776. auto handle = cli.open_stream("GET", "/compressible", {},
  21777. {{"Accept-Encoding", "zstd"}});
  21778. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21779. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21780. }
  21781. #endif
  21782. #ifdef CPPHTTPLIB_SSL_ENABLED
  21783. class SSLOpenStreamTest : public ::testing::Test {
  21784. protected:
  21785. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21786. void SetUp() override {
  21787. svr_.Get("/hello", [](const Request &, Response &res) {
  21788. res.set_content("Hello SSL World!", "text/plain");
  21789. });
  21790. svr_.Get("/chunked", [](const Request &, Response &res) {
  21791. res.set_chunked_content_provider("text/plain",
  21792. [](size_t offset, DataSink &sink) {
  21793. if (offset < 15) {
  21794. sink.write("chunk", 5);
  21795. return true;
  21796. }
  21797. sink.done();
  21798. return true;
  21799. });
  21800. });
  21801. svr_.Post("/echo", [](const Request &req, Response &res) {
  21802. res.set_content(req.body, req.get_header_value("Content-Type"));
  21803. });
  21804. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21805. std::string body = req.body;
  21806. res.set_chunked_content_provider(
  21807. "text/plain", [body](size_t offset, DataSink &sink) {
  21808. if (offset < body.size()) {
  21809. sink.write(body.data() + offset, body.size() - offset);
  21810. }
  21811. sink.done();
  21812. return true;
  21813. });
  21814. });
  21815. port_ = svr_.bind_to_any_port("127.0.0.1");
  21816. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21817. svr_.wait_until_ready();
  21818. }
  21819. void TearDown() override {
  21820. svr_.stop();
  21821. if (thread_.joinable()) thread_.join();
  21822. }
  21823. SSLServer svr_;
  21824. std::thread thread_;
  21825. int port_ = 0;
  21826. };
  21827. TEST_F(SSLOpenStreamTest, Basic) {
  21828. SSLClient cli("127.0.0.1", port_);
  21829. cli.enable_server_certificate_verification(false);
  21830. auto handle = cli.open_stream("GET", "/hello");
  21831. ASSERT_TRUE(handle.is_valid());
  21832. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21833. }
  21834. TEST_F(SSLOpenStreamTest, Chunked) {
  21835. SSLClient cli("127.0.0.1", port_);
  21836. cli.enable_server_certificate_verification(false);
  21837. auto handle = cli.open_stream("GET", "/chunked");
  21838. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21839. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21840. "Transfer-Encoding") == "chunked");
  21841. auto body = read_all(handle);
  21842. EXPECT_EQ("chunkchunkchunk", body);
  21843. }
  21844. TEST_F(SSLOpenStreamTest, Post) {
  21845. SSLClient cli("127.0.0.1", port_);
  21846. cli.enable_server_certificate_verification(false);
  21847. auto handle =
  21848. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21849. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21850. EXPECT_EQ(200, handle.response->status);
  21851. auto body = read_all(handle);
  21852. EXPECT_EQ("Hello SSL POST", body);
  21853. }
  21854. TEST_F(SSLOpenStreamTest, PostChunked) {
  21855. SSLClient cli("127.0.0.1", port_);
  21856. cli.enable_server_certificate_verification(false);
  21857. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21858. "Chunked SSL Data", "text/plain");
  21859. ASSERT_TRUE(handle.is_valid());
  21860. EXPECT_EQ(200, handle.response->status);
  21861. auto body = read_all(handle);
  21862. EXPECT_EQ("Chunked SSL Data", body);
  21863. }
  21864. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21865. // Content-Length is terminated by the server closing the connection. When the
  21866. // SSL peer sends a close_notify after the body, the client must treat it as a
  21867. // clean EOF and return a successful response rather than an error.
  21868. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21870. ASSERT_TRUE(svr.is_valid());
  21871. svr.set_keep_alive_max_count(1);
  21872. const std::string expected_body = "Hello from connection-close response!";
  21873. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21874. res.set_content_provider("text/plain",
  21875. [&](size_t offset, DataSink &sink) -> bool {
  21876. if (offset < expected_body.size()) {
  21877. sink.write(expected_body.data() + offset,
  21878. expected_body.size() - offset);
  21879. }
  21880. sink.done();
  21881. return true;
  21882. });
  21883. });
  21884. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21885. auto se = detail::scope_exit([&] {
  21886. svr.stop();
  21887. listen_thread.join();
  21888. ASSERT_FALSE(svr.is_running());
  21889. });
  21890. svr.wait_until_ready();
  21891. SSLClient cli(HOST, PORT);
  21892. cli.enable_server_certificate_verification(false);
  21893. auto res = cli.Get("/no-content-length");
  21894. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21895. EXPECT_EQ(StatusCode::OK_200, res->status);
  21896. EXPECT_EQ(expected_body, res->body);
  21897. }
  21898. // Without Content-Length, the full buffer size reaches tls::read().
  21899. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21900. if (sizeof(size_t) <= sizeof(int)) {
  21901. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21902. }
  21903. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21904. ASSERT_TRUE(svr.is_valid());
  21905. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21906. res.set_content_provider("text/plain",
  21907. [&](size_t offset, DataSink &sink) -> bool {
  21908. if (offset == 0) { sink.write("Hello", 5); }
  21909. sink.done();
  21910. return true;
  21911. });
  21912. });
  21913. auto port = svr.bind_to_any_port(HOST);
  21914. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21915. auto se = detail::scope_exit([&] {
  21916. svr.stop();
  21917. listen_thread.join();
  21918. });
  21919. svr.wait_until_ready();
  21920. SSLClient cli(HOST, port);
  21921. cli.enable_server_certificate_verification(false);
  21922. auto handle = cli.open_stream("GET", "/no-content-length");
  21923. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21924. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21925. std::unique_ptr<char[]> buf(new char[len]);
  21926. std::string body;
  21927. ssize_t n;
  21928. while ((n = handle.read(buf.get(), len)) > 0) {
  21929. body.append(buf.get(), static_cast<size_t>(n));
  21930. }
  21931. EXPECT_EQ(0, n);
  21932. EXPECT_EQ("Hello", body);
  21933. }
  21934. #endif // CPPHTTPLIB_SSL_ENABLED
  21935. //==============================================================================
  21936. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21937. // results for various scenarios.
  21938. //==============================================================================
  21939. TEST(ParityTest, GetVsOpenStream) {
  21940. Server svr;
  21941. const std::string path = "/parity";
  21942. const std::string content = "Parity test content: hello world";
  21943. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21944. res.set_content(content, "text/plain");
  21945. });
  21946. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21947. auto se = detail::scope_exit([&] {
  21948. svr.stop();
  21949. t.join();
  21950. ASSERT_FALSE(svr.is_running());
  21951. });
  21952. svr.wait_until_ready();
  21953. Client cli(HOST, PORT);
  21954. // Non-stream path
  21955. auto r1 = cli.Get(path);
  21956. ASSERT_TRUE(r1);
  21957. EXPECT_EQ(StatusCode::OK_200, r1->status);
  21958. // Stream path
  21959. auto h = cli.open_stream("GET", path);
  21960. ASSERT_TRUE(h.is_valid());
  21961. EXPECT_EQ(r1->body, read_all(h));
  21962. }
  21963. // Helper to compress data with provided compressor type T
  21964. template <typename Compressor>
  21965. static std::string compress_payload_for_parity(const std::string &in) {
  21966. std::string out;
  21967. Compressor compressor;
  21968. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  21969. [&](const char *data, size_t n) {
  21970. out.append(data, n);
  21971. return true;
  21972. });
  21973. EXPECT_TRUE(ok);
  21974. return out;
  21975. }
  21976. // Helper function for compression parity tests
  21977. template <typename Compressor>
  21978. static void test_compression_parity(const std::string &original,
  21979. const std::string &path,
  21980. const std::string &encoding) {
  21981. const std::string compressed =
  21982. compress_payload_for_parity<Compressor>(original);
  21983. Server svr;
  21984. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21985. res.set_content(compressed, "application/octet-stream");
  21986. res.set_header("Content-Encoding", encoding);
  21987. });
  21988. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  21989. auto se = detail::scope_exit([&] {
  21990. svr.stop();
  21991. t.join();
  21992. ASSERT_FALSE(svr.is_running());
  21993. });
  21994. svr.wait_until_ready();
  21995. Client cli(HOST, PORT);
  21996. // Non-streaming
  21997. {
  21998. auto res = cli.Get(path);
  21999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22000. EXPECT_EQ(StatusCode::OK_200, res->status);
  22001. EXPECT_EQ(original, res->body);
  22002. }
  22003. // Streaming
  22004. {
  22005. auto h = cli.open_stream("GET", path);
  22006. ASSERT_TRUE(h.is_valid());
  22007. EXPECT_EQ(original, read_all(h));
  22008. }
  22009. }
  22010. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22011. TEST(ParityTest, Gzip) {
  22012. test_compression_parity<detail::gzip_compressor>(
  22013. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  22014. }
  22015. #endif
  22016. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22017. TEST(ParityTest, Brotli) {
  22018. test_compression_parity<detail::brotli_compressor>(
  22019. "Hello, brotli parity test payload", "/parity-br", "br");
  22020. }
  22021. #endif
  22022. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22023. TEST(ParityTest, Zstd) {
  22024. test_compression_parity<detail::zstd_compressor>(
  22025. "Zstandard parity test payload", "/parity-zstd", "zstd");
  22026. }
  22027. #endif
  22028. //==============================================================================
  22029. // New Stream API Tests
  22030. //==============================================================================
  22031. inline std::string read_body(httplib::stream::Result &result) {
  22032. std::string body;
  22033. while (result.next()) {
  22034. body.append(result.data(), result.size());
  22035. }
  22036. return body;
  22037. }
  22038. TEST(ClientConnectionTest, Basic) {
  22039. httplib::ClientConnection conn;
  22040. EXPECT_FALSE(conn.is_open());
  22041. conn.sock = 1;
  22042. EXPECT_TRUE(conn.is_open());
  22043. httplib::ClientConnection conn2(std::move(conn));
  22044. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  22045. conn2.sock = INVALID_SOCKET;
  22046. }
  22047. // Unified test server for all stream::* tests
  22048. class StreamApiTest : public ::testing::Test {
  22049. protected:
  22050. void SetUp() override {
  22051. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22052. res.set_content("Hello World!", "text/plain");
  22053. });
  22054. svr_.Get("/echo-params",
  22055. [](const httplib::Request &req, httplib::Response &res) {
  22056. std::string r;
  22057. for (const auto &p : req.params) {
  22058. if (!r.empty()) r += "&";
  22059. r += p.first + "=" + p.second;
  22060. }
  22061. res.set_content(r, "text/plain");
  22062. });
  22063. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22064. res.set_content(req.body, req.get_header_value("Content-Type"));
  22065. });
  22066. svr_.Post("/echo-headers",
  22067. [](const httplib::Request &req, httplib::Response &res) {
  22068. std::string r;
  22069. for (const auto &h : req.headers)
  22070. r += h.first + ": " + h.second + "\n";
  22071. res.set_content(r, "text/plain");
  22072. });
  22073. svr_.Post("/echo-params",
  22074. [](const httplib::Request &req, httplib::Response &res) {
  22075. std::string r = "params:";
  22076. for (const auto &p : req.params)
  22077. r += p.first + "=" + p.second + ";";
  22078. res.set_content(r + " body:" + req.body, "text/plain");
  22079. });
  22080. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22081. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22082. });
  22083. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22084. res.set_content("PUT:" + req.body, "text/plain");
  22085. });
  22086. svr_.Patch("/echo",
  22087. [](const httplib::Request &req, httplib::Response &res) {
  22088. res.set_content("PATCH:" + req.body, "text/plain");
  22089. });
  22090. svr_.Delete(
  22091. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22092. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22093. "text/plain");
  22094. });
  22095. svr_.Get("/head-test",
  22096. [](const httplib::Request &, httplib::Response &res) {
  22097. res.set_content("body for HEAD", "text/plain");
  22098. });
  22099. svr_.Options("/options",
  22100. [](const httplib::Request &, httplib::Response &res) {
  22101. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22102. });
  22103. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22104. svr_.wait_until_ready();
  22105. }
  22106. void TearDown() override {
  22107. svr_.stop();
  22108. if (thread_.joinable()) thread_.join();
  22109. }
  22110. httplib::Server svr_;
  22111. std::thread thread_;
  22112. };
  22113. // stream::Get tests
  22114. TEST_F(StreamApiTest, GetBasic) {
  22115. httplib::Client cli(HOST, PORT);
  22116. auto result = httplib::stream::Get(cli, "/hello");
  22117. ASSERT_TRUE(result.is_valid());
  22118. EXPECT_EQ(200, result.status());
  22119. EXPECT_EQ("Hello World!", read_body(result));
  22120. }
  22121. TEST_F(StreamApiTest, GetWithParams) {
  22122. httplib::Client cli(HOST, PORT);
  22123. httplib::Params params{{"foo", "bar"}};
  22124. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22125. ASSERT_TRUE(result.is_valid());
  22126. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22127. }
  22128. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22129. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22130. httplib::Client cli(HOST, PORT);
  22131. cli.set_payload_max_length(0);
  22132. auto result = httplib::stream::Get(cli, "/hello");
  22133. ASSERT_TRUE(result.is_valid());
  22134. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22135. EXPECT_EQ("Hello World!", read_body(result));
  22136. }
  22137. #endif
  22138. TEST_F(StreamApiTest, GetConnectionError) {
  22139. httplib::Client cli(HOST, 9999);
  22140. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22141. }
  22142. TEST_F(StreamApiTest, Get404) {
  22143. httplib::Client cli(HOST, PORT);
  22144. auto result = httplib::stream::Get(cli, "/nonexistent");
  22145. EXPECT_TRUE(result.is_valid());
  22146. EXPECT_EQ(404, result.status());
  22147. }
  22148. // stream::Post tests
  22149. TEST_F(StreamApiTest, PostBasic) {
  22150. httplib::Client cli(HOST, PORT);
  22151. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22152. "application/json");
  22153. ASSERT_TRUE(result.is_valid());
  22154. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22155. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22156. }
  22157. TEST_F(StreamApiTest, PostWithHeaders) {
  22158. httplib::Client cli(HOST, PORT);
  22159. httplib::Headers headers{{"X-Custom", "value"}};
  22160. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22161. "text/plain");
  22162. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22163. }
  22164. TEST_F(StreamApiTest, PostWithParams) {
  22165. httplib::Client cli(HOST, PORT);
  22166. httplib::Params params{{"k", "v"}};
  22167. auto result =
  22168. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22169. auto body = read_body(result);
  22170. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22171. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22172. }
  22173. TEST_F(StreamApiTest, PostLarge) {
  22174. httplib::Client cli(HOST, PORT);
  22175. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22176. size_t total = 0;
  22177. while (result.next()) {
  22178. total += result.size();
  22179. }
  22180. EXPECT_EQ(100u * 1024u, total);
  22181. }
  22182. // stream::Put/Patch tests
  22183. TEST_F(StreamApiTest, PutAndPatch) {
  22184. httplib::Client cli(HOST, PORT);
  22185. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22186. EXPECT_EQ("PUT:test", read_body(put));
  22187. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22188. EXPECT_EQ("PATCH:test", read_body(patch));
  22189. }
  22190. // stream::Delete tests
  22191. TEST_F(StreamApiTest, Delete) {
  22192. httplib::Client cli(HOST, PORT);
  22193. auto del1 = httplib::stream::Delete(cli, "/resource");
  22194. EXPECT_EQ("Deleted", read_body(del1));
  22195. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22196. EXPECT_EQ("Deleted:data", read_body(del2));
  22197. }
  22198. // stream::Head/Options tests
  22199. TEST_F(StreamApiTest, HeadAndOptions) {
  22200. httplib::Client cli(HOST, PORT);
  22201. auto head = httplib::stream::Head(cli, "/head-test");
  22202. EXPECT_TRUE(head.is_valid());
  22203. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22204. auto opts = httplib::stream::Options(cli, "/options");
  22205. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22206. }
  22207. // SSL stream::* tests
  22208. #ifdef CPPHTTPLIB_SSL_ENABLED
  22209. class SSLStreamApiTest : public ::testing::Test {
  22210. protected:
  22211. void SetUp() override {
  22212. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22213. res.set_content("Hello SSL!", "text/plain");
  22214. });
  22215. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22216. res.set_content(req.body, "text/plain");
  22217. });
  22218. port_ = svr_.bind_to_any_port("127.0.0.1");
  22219. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22220. svr_.wait_until_ready();
  22221. }
  22222. void TearDown() override {
  22223. svr_.stop();
  22224. if (thread_.joinable()) thread_.join();
  22225. }
  22226. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22227. std::thread thread_;
  22228. int port_ = 0;
  22229. };
  22230. TEST_F(SSLStreamApiTest, GetAndPost) {
  22231. httplib::SSLClient cli("127.0.0.1", port_);
  22232. cli.enable_server_certificate_verification(false);
  22233. auto get = httplib::stream::Get(cli, "/hello");
  22234. EXPECT_EQ("Hello SSL!", read_body(get));
  22235. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22236. EXPECT_EQ("test", read_body(post));
  22237. }
  22238. #endif
  22239. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22240. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22241. // BodyReader
  22242. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22243. // Test that read timeout during streaming is detected
  22244. // Use a large content-length response where server delays mid-stream
  22245. Server svr;
  22246. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22247. // Send a large response with delay in the middle
  22248. res.set_content_provider(
  22249. 1000, // content_length
  22250. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22251. if (offset < 100) {
  22252. // Send first 100 bytes immediately
  22253. std::string data(100, 'A');
  22254. sink.write(data.c_str(), data.size());
  22255. return true;
  22256. }
  22257. // Then delay longer than client timeout
  22258. std::this_thread::sleep_for(std::chrono::seconds(3));
  22259. std::string data(900, 'B');
  22260. sink.write(data.c_str(), data.size());
  22261. return true;
  22262. });
  22263. });
  22264. auto port = 8091;
  22265. std::thread t([&]() { svr.listen("localhost", port); });
  22266. svr.wait_until_ready();
  22267. Client cli("localhost", port);
  22268. cli.set_read_timeout(1, 0); // 1 second timeout
  22269. auto handle = cli.open_stream("GET", "/slow-stream");
  22270. ASSERT_TRUE(handle.is_valid());
  22271. char buf[256];
  22272. ssize_t total = 0;
  22273. ssize_t n;
  22274. bool got_error = false;
  22275. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22276. total += n;
  22277. }
  22278. if (n < 0) {
  22279. got_error = true;
  22280. // Should be timeout or read error
  22281. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22282. handle.get_read_error() == Error::Read)
  22283. << "Actual error: " << to_string(handle.get_read_error());
  22284. }
  22285. // Either we got an error, or we got less data than expected
  22286. EXPECT_TRUE(got_error || total < 1000)
  22287. << "Expected timeout but got all " << total << " bytes";
  22288. svr.stop();
  22289. t.join();
  22290. }
  22291. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22292. // Test connection closed detection via BodyReader
  22293. Server svr;
  22294. std::atomic<bool> close_now{false};
  22295. svr.Get("/will-close", [&](const Request &, Response &res) {
  22296. res.set_content_provider(
  22297. 10000, // Large content_length that we won't fully send
  22298. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22299. if (offset < 100) {
  22300. std::string data(100, 'X');
  22301. sink.write(data.c_str(), data.size());
  22302. return true;
  22303. }
  22304. // Wait for signal then abort
  22305. while (!close_now) {
  22306. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22307. }
  22308. return false; // Abort - server will close connection
  22309. });
  22310. });
  22311. auto port = 8092;
  22312. std::thread t([&]() { svr.listen("localhost", port); });
  22313. svr.wait_until_ready();
  22314. Client cli("localhost", port);
  22315. auto handle = cli.open_stream("GET", "/will-close");
  22316. ASSERT_TRUE(handle.is_valid());
  22317. char buf[256];
  22318. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22319. EXPECT_GT(n, 0) << "First read should succeed";
  22320. // Signal server to close
  22321. close_now = true;
  22322. // Keep reading until error or EOF
  22323. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22324. // Keep reading
  22325. }
  22326. // Should get an error since content_length wasn't satisfied
  22327. if (n < 0) {
  22328. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22329. handle.get_read_error() == Error::Read)
  22330. << "Actual error: " << to_string(handle.get_read_error());
  22331. }
  22332. svr.stop();
  22333. t.join();
  22334. }
  22335. #ifdef CPPHTTPLIB_SSL_ENABLED
  22336. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22337. // Test that read timeout during SSL streaming is detected
  22338. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22339. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22340. res.set_content_provider(
  22341. 1000, "text/plain",
  22342. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22343. if (offset < 100) {
  22344. std::string data(100, 'A');
  22345. sink.write(data.c_str(), data.size());
  22346. return true;
  22347. }
  22348. std::this_thread::sleep_for(std::chrono::seconds(3));
  22349. std::string data(900, 'B');
  22350. sink.write(data.c_str(), data.size());
  22351. return true;
  22352. });
  22353. });
  22354. auto port = 8093;
  22355. std::thread t([&]() { svr.listen("localhost", port); });
  22356. svr.wait_until_ready();
  22357. SSLClient cli("localhost", port);
  22358. cli.enable_server_certificate_verification(false);
  22359. cli.set_read_timeout(1, 0); // 1 second timeout
  22360. auto handle = cli.open_stream("GET", "/slow-stream");
  22361. ASSERT_TRUE(handle.is_valid());
  22362. char buf[256];
  22363. ssize_t total = 0;
  22364. ssize_t n;
  22365. bool got_error = false;
  22366. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22367. total += n;
  22368. }
  22369. if (n < 0) {
  22370. got_error = true;
  22371. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22372. handle.get_read_error() == Error::Read)
  22373. << "Actual error: " << to_string(handle.get_read_error());
  22374. }
  22375. EXPECT_TRUE(got_error || total < 1000)
  22376. << "Expected timeout but got all " << total << " bytes";
  22377. svr.stop();
  22378. t.join();
  22379. }
  22380. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22381. // Test SSL connection closed detection
  22382. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22383. std::atomic<bool> close_now{false};
  22384. svr.Get("/will-close", [&](const Request &, Response &res) {
  22385. res.set_content_provider(
  22386. 10000, "text/plain",
  22387. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22388. if (offset < 100) {
  22389. std::string data(100, 'X');
  22390. sink.write(data.c_str(), data.size());
  22391. return true;
  22392. }
  22393. while (!close_now) {
  22394. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22395. }
  22396. return false;
  22397. });
  22398. });
  22399. auto port = 8094;
  22400. std::thread t([&]() { svr.listen("localhost", port); });
  22401. svr.wait_until_ready();
  22402. SSLClient cli("localhost", port);
  22403. cli.enable_server_certificate_verification(false);
  22404. auto handle = cli.open_stream("GET", "/will-close");
  22405. ASSERT_TRUE(handle.is_valid());
  22406. char buf[256];
  22407. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22408. EXPECT_GT(n, 0);
  22409. // Signal server to close
  22410. close_now = true;
  22411. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22412. // Keep reading
  22413. }
  22414. if (n < 0) {
  22415. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22416. handle.get_read_error() == Error::Read)
  22417. << "Actual error: " << to_string(handle.get_read_error());
  22418. }
  22419. svr.stop();
  22420. t.join();
  22421. }
  22422. #endif
  22423. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22424. using namespace httplib;
  22425. // Create a test file
  22426. const char *fname = "etag_testfile.txt";
  22427. const char *content = "etag-content";
  22428. {
  22429. std::ofstream ofs(fname);
  22430. ofs << content;
  22431. ASSERT_TRUE(ofs.good());
  22432. }
  22433. Server svr;
  22434. svr.set_mount_point("/static", ".");
  22435. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22436. svr.wait_until_ready();
  22437. Client cli(HOST, PORT);
  22438. // First request: should get 200 with ETag header
  22439. auto res1 = cli.Get("/static/etag_testfile.txt");
  22440. ASSERT_TRUE(res1);
  22441. ASSERT_EQ(200, res1->status);
  22442. ASSERT_TRUE(res1->has_header("ETag"));
  22443. std::string etag = res1->get_header_value("ETag");
  22444. EXPECT_FALSE(etag.empty());
  22445. // Verify ETag format: W/"hex-hex"
  22446. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22447. EXPECT_EQ('W', etag[0]);
  22448. EXPECT_EQ('/', etag[1]);
  22449. EXPECT_EQ('"', etag[2]);
  22450. EXPECT_EQ('"', etag.back());
  22451. // Exact match: expect 304 Not Modified
  22452. Headers h2 = {{"If-None-Match", etag}};
  22453. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22454. ASSERT_TRUE(res2);
  22455. EXPECT_EQ(304, res2->status);
  22456. // Wildcard match: expect 304 Not Modified
  22457. Headers h3 = {{"If-None-Match", "*"}};
  22458. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22459. ASSERT_TRUE(res3);
  22460. EXPECT_EQ(304, res3->status);
  22461. // Non-matching ETag: expect 200
  22462. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22463. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22464. ASSERT_TRUE(res4);
  22465. EXPECT_EQ(200, res4->status);
  22466. // Multiple ETags with one matching: expect 304
  22467. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22468. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22469. ASSERT_TRUE(res5);
  22470. EXPECT_EQ(304, res5->status);
  22471. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22472. // that equivalent to the single comma-separated list above, so the match on
  22473. // the second line must still be found.
  22474. Headers h6;
  22475. h6.emplace("If-None-Match", "W/\"other\"");
  22476. h6.emplace("If-None-Match", etag);
  22477. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22478. ASSERT_TRUE(res6);
  22479. EXPECT_EQ(304, res6->status);
  22480. svr.stop();
  22481. t.join();
  22482. std::remove(fname);
  22483. }
  22484. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22485. using namespace httplib;
  22486. Server svr;
  22487. svr.set_mount_point("/static", ".");
  22488. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22489. svr.wait_until_ready();
  22490. Client cli(HOST, PORT);
  22491. // Send If-None-Match: * to a non-existent file
  22492. Headers h = {{"If-None-Match", "*"}};
  22493. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22495. EXPECT_EQ(404, res->status);
  22496. svr.stop();
  22497. t.join();
  22498. }
  22499. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22500. using namespace httplib;
  22501. // Create a test file
  22502. const char *fname = "etag_boundary_testfile.txt";
  22503. const char *content = "boundary-test";
  22504. {
  22505. std::ofstream ofs(fname);
  22506. ofs << content;
  22507. ASSERT_TRUE(ofs.good());
  22508. }
  22509. Server svr;
  22510. svr.set_mount_point("/static", ".");
  22511. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22512. svr.wait_until_ready();
  22513. Client cli(HOST, PORT);
  22514. // Get the actual ETag
  22515. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22516. ASSERT_TRUE(res1);
  22517. ASSERT_EQ(200, res1->status);
  22518. ASSERT_TRUE(res1->has_header("ETag"));
  22519. std::string etag = res1->get_header_value("ETag");
  22520. // Test 1: Very long ETag value (longer than actual ETag)
  22521. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22522. Headers h1 = {{"If-None-Match", "W/"
  22523. "\"very-long-etag-value-that-is-much-longer-"
  22524. "than-the-actual-etag-value\""}};
  22525. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22526. ASSERT_TRUE(res2);
  22527. EXPECT_EQ(200, res2->status); // Should not match
  22528. // Test 2: Long string followed by wildcard
  22529. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22530. // string)
  22531. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22532. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22533. ASSERT_TRUE(res3);
  22534. EXPECT_EQ(304, res3->status); // Should match on "*"
  22535. // Test 3: Wildcard followed by long string
  22536. // Should match on "*" immediately and return 304
  22537. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22538. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22539. ASSERT_TRUE(res4);
  22540. EXPECT_EQ(304, res4->status); // Should match on "*"
  22541. // Test 4: Multiple long non-matching values
  22542. // Should NOT match and return 200 (test that all comparisons are safe)
  22543. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22544. "W/\"second-long-non-matching-value\", "
  22545. "W/\"third-long-non-matching-value\""}};
  22546. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22547. ASSERT_TRUE(res5);
  22548. EXPECT_EQ(200, res5->status); // Should not match
  22549. // Test 5: Single character that is not "*" (edge case)
  22550. Headers h5 = {{"If-None-Match", "X"}};
  22551. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22552. ASSERT_TRUE(res6);
  22553. EXPECT_EQ(200, res6->status); // Should not match
  22554. svr.stop();
  22555. t.join();
  22556. std::remove(fname);
  22557. }
  22558. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22559. using namespace httplib;
  22560. // Create a test file
  22561. const char *fname = "ims_testfile.txt";
  22562. const char *content = "if-modified-since-test";
  22563. {
  22564. std::ofstream ofs(fname);
  22565. ofs << content;
  22566. ASSERT_TRUE(ofs.good());
  22567. }
  22568. Server svr;
  22569. svr.set_mount_point("/static", ".");
  22570. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22571. svr.wait_until_ready();
  22572. Client cli(HOST, PORT);
  22573. // First request: should get 200 with Last-Modified header
  22574. auto res1 = cli.Get("/static/ims_testfile.txt");
  22575. ASSERT_TRUE(res1);
  22576. ASSERT_EQ(200, res1->status);
  22577. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22578. std::string last_modified = res1->get_header_value("Last-Modified");
  22579. EXPECT_FALSE(last_modified.empty());
  22580. // If-Modified-Since with same time: expect 304
  22581. Headers h2 = {{"If-Modified-Since", last_modified}};
  22582. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22583. ASSERT_TRUE(res2);
  22584. EXPECT_EQ(304, res2->status);
  22585. // If-Modified-Since with future time: expect 304
  22586. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22587. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22588. ASSERT_TRUE(res3);
  22589. EXPECT_EQ(304, res3->status);
  22590. // If-Modified-Since with past time: expect 200
  22591. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22592. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22593. ASSERT_TRUE(res4);
  22594. EXPECT_EQ(200, res4->status);
  22595. // If-None-Match takes precedence over If-Modified-Since
  22596. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22597. ASSERT_TRUE(res1->has_header("ETag"));
  22598. std::string etag = res1->get_header_value("ETag");
  22599. Headers h5 = {{"If-None-Match", etag},
  22600. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22601. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22602. ASSERT_TRUE(res5);
  22603. EXPECT_EQ(304, res5->status);
  22604. svr.stop();
  22605. t.join();
  22606. std::remove(fname);
  22607. }
  22608. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22609. using namespace httplib;
  22610. Server svr;
  22611. // Endpoint that returns compressible content
  22612. svr.Get("/compressible", [](const Request &, Response &res) {
  22613. // Return a large enough body to trigger compression
  22614. std::string body(1000, 'a');
  22615. res.set_content(body, "text/plain");
  22616. });
  22617. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22618. svr.wait_until_ready();
  22619. Client cli(HOST, PORT);
  22620. // Request with gzip support: should get Vary header when compressed
  22621. cli.set_compress(true);
  22622. auto res1 = cli.Get("/compressible");
  22623. ASSERT_TRUE(res1);
  22624. EXPECT_EQ(200, res1->status);
  22625. // If Content-Encoding is set, Vary should also be set
  22626. if (res1->has_header("Content-Encoding")) {
  22627. EXPECT_TRUE(res1->has_header("Vary"));
  22628. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22629. }
  22630. // Request without Accept-Encoding header: should not have compression
  22631. Headers h_no_compress;
  22632. auto res2 = cli.Get("/compressible", h_no_compress);
  22633. ASSERT_TRUE(res2);
  22634. EXPECT_EQ(200, res2->status);
  22635. // Verify Vary header is present when compression is applied
  22636. // (the exact behavior depends on server configuration)
  22637. svr.stop();
  22638. t.join();
  22639. }
  22640. TEST(ETagTest, IfRangeWithETag) {
  22641. using namespace httplib;
  22642. // Create a test file with known content
  22643. const char *fname = "if_range_testfile.txt";
  22644. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22645. {
  22646. std::ofstream ofs(fname);
  22647. ofs << content;
  22648. ASSERT_TRUE(ofs.good());
  22649. }
  22650. Server svr;
  22651. svr.set_mount_point("/static", ".");
  22652. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22653. svr.wait_until_ready();
  22654. Client cli(HOST, PORT);
  22655. // First request: get ETag
  22656. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22657. ASSERT_TRUE(res1);
  22658. ASSERT_EQ(200, res1->status);
  22659. ASSERT_TRUE(res1->has_header("ETag"));
  22660. std::string etag = res1->get_header_value("ETag");
  22661. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22662. // Since our server generates weak ETags (W/"..."), If-Range with our
  22663. // ETag should NOT result in partial content - it should return full content.
  22664. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22665. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22666. ASSERT_TRUE(res2);
  22667. // Weak ETag in If-Range -> full content (200), not partial (206)
  22668. EXPECT_EQ(200, res2->status);
  22669. EXPECT_EQ(content, res2->body);
  22670. EXPECT_FALSE(res2->has_header("Content-Range"));
  22671. // Range request with non-matching If-Range (ETag): should get 200 (full
  22672. // content)
  22673. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22674. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22675. ASSERT_TRUE(res3);
  22676. EXPECT_EQ(200, res3->status);
  22677. EXPECT_EQ(content, res3->body);
  22678. EXPECT_FALSE(res3->has_header("Content-Range"));
  22679. // Range request with strong ETag (hypothetical - our server doesn't generate
  22680. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22681. // should return full content)
  22682. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22683. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22684. ASSERT_TRUE(res4);
  22685. EXPECT_EQ(200, res4->status);
  22686. EXPECT_EQ(content, res4->body);
  22687. EXPECT_FALSE(res4->has_header("Content-Range"));
  22688. svr.stop();
  22689. t.join();
  22690. std::remove(fname);
  22691. }
  22692. TEST(ETagTest, IfRangeWithDate) {
  22693. using namespace httplib;
  22694. // Create a test file
  22695. const char *fname = "if_range_date_testfile.txt";
  22696. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22697. {
  22698. std::ofstream ofs(fname);
  22699. ofs << content;
  22700. ASSERT_TRUE(ofs.good());
  22701. }
  22702. Server svr;
  22703. svr.set_mount_point("/static", ".");
  22704. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22705. svr.wait_until_ready();
  22706. Client cli(HOST, PORT);
  22707. // First request: get Last-Modified
  22708. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22709. ASSERT_TRUE(res1);
  22710. ASSERT_EQ(200, res1->status);
  22711. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22712. std::string last_modified = res1->get_header_value("Last-Modified");
  22713. // Range request with matching If-Range (date): should get 206
  22714. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22715. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22716. ASSERT_TRUE(res2);
  22717. EXPECT_EQ(206, res2->status);
  22718. EXPECT_EQ("FGHIJ", res2->body);
  22719. // Range request with old If-Range date: should get 200 (full content)
  22720. Headers h3 = {{"Range", "bytes=5-9"},
  22721. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22722. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22723. ASSERT_TRUE(res3);
  22724. EXPECT_EQ(200, res3->status);
  22725. EXPECT_EQ(content, res3->body);
  22726. // Range request with future If-Range date: should get 206
  22727. Headers h4 = {{"Range", "bytes=0-4"},
  22728. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22729. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22730. ASSERT_TRUE(res4);
  22731. EXPECT_EQ(206, res4->status);
  22732. EXPECT_EQ("ABCDE", res4->body);
  22733. svr.stop();
  22734. t.join();
  22735. std::remove(fname);
  22736. }
  22737. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22738. using namespace httplib;
  22739. const char *fname = "etag_malformed.txt";
  22740. const char *content = "malformed-etag";
  22741. {
  22742. std::ofstream ofs(fname);
  22743. ofs << content;
  22744. ASSERT_TRUE(ofs.good());
  22745. }
  22746. Server svr;
  22747. svr.set_mount_point("/static", ".");
  22748. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22749. svr.wait_until_ready();
  22750. Client cli(HOST, PORT);
  22751. // baseline: should get 200 and an ETag
  22752. auto res1 = cli.Get("/static/etag_malformed.txt");
  22753. ASSERT_TRUE(res1);
  22754. ASSERT_EQ(200, res1->status);
  22755. ASSERT_TRUE(res1->has_header("ETag"));
  22756. // Malformed ETag value (missing quotes) should be treated as non-matching
  22757. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22758. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22759. ASSERT_TRUE(res_bad);
  22760. EXPECT_EQ(200, res_bad->status);
  22761. // Whitespace-only header value should be considered invalid / non-matching
  22762. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22763. "Host: localhost\r\n"
  22764. "If-None-Match: \r\n"
  22765. "Connection: close\r\n"
  22766. "\r\n";
  22767. std::string out;
  22768. ASSERT_TRUE(send_request(5, raw_req, &out));
  22769. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22770. svr.stop();
  22771. t.join();
  22772. std::remove(fname);
  22773. }
  22774. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22775. using namespace httplib;
  22776. const char *fname = "ims_invalid_format.txt";
  22777. const char *content = "ims-bad-format";
  22778. {
  22779. std::ofstream ofs(fname);
  22780. ofs << content;
  22781. ASSERT_TRUE(ofs.good());
  22782. }
  22783. Server svr;
  22784. svr.set_mount_point("/static", ".");
  22785. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22786. svr.wait_until_ready();
  22787. Client cli(HOST, PORT);
  22788. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22789. ASSERT_TRUE(res1);
  22790. ASSERT_EQ(200, res1->status);
  22791. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22792. // If-Modified-Since with invalid format should not result in 304
  22793. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22794. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22795. ASSERT_TRUE(res_bad);
  22796. EXPECT_EQ(200, res_bad->status);
  22797. // If-Range with invalid date format should be treated as mismatch -> full
  22798. // content (200)
  22799. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22800. {"If-Range", "invalid-date"}};
  22801. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22802. ASSERT_TRUE(res_ifrange);
  22803. EXPECT_EQ(200, res_ifrange->status);
  22804. svr.stop();
  22805. t.join();
  22806. std::remove(fname);
  22807. }
  22808. TEST(ETagTest, IfRangeWithMalformedETag) {
  22809. using namespace httplib;
  22810. const char *fname = "ifrange_malformed.txt";
  22811. const std::string content = "0123456789";
  22812. {
  22813. std::ofstream ofs(fname);
  22814. ofs << content;
  22815. ASSERT_TRUE(ofs.good());
  22816. }
  22817. Server svr;
  22818. svr.set_mount_point("/static", ".");
  22819. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22820. svr.wait_until_ready();
  22821. Client cli(HOST, PORT);
  22822. // First request: get ETag
  22823. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22824. ASSERT_TRUE(res1);
  22825. ASSERT_EQ(200, res1->status);
  22826. ASSERT_TRUE(res1->has_header("ETag"));
  22827. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22828. // full content (200)
  22829. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22830. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22831. ASSERT_TRUE(res2);
  22832. EXPECT_EQ(200, res2->status);
  22833. EXPECT_EQ(content, res2->body);
  22834. svr.stop();
  22835. t.join();
  22836. std::remove(fname);
  22837. }
  22838. TEST(ETagTest, ExtremeLargeDateValues) {
  22839. using namespace httplib;
  22840. const char *fname = "ims_extreme_date.txt";
  22841. const char *content = "ims-extreme-date";
  22842. {
  22843. std::ofstream ofs(fname);
  22844. ofs << content;
  22845. ASSERT_TRUE(ofs.good());
  22846. }
  22847. Server svr;
  22848. svr.set_mount_point("/static", ".");
  22849. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22850. svr.wait_until_ready();
  22851. Client cli(HOST, PORT);
  22852. auto res1 = cli.Get(std::string("/static/") + fname);
  22853. ASSERT_TRUE(res1);
  22854. ASSERT_EQ(200, res1->status);
  22855. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22856. // Extremely large year that may overflow date parsing routines.
  22857. Headers h_large_date = {
  22858. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22859. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22860. ASSERT_TRUE(res_bad);
  22861. // Expect server to treat this as invalid/mismatch and return full content
  22862. EXPECT_EQ(200, res_bad->status);
  22863. // If-Range with extremely large date should be treated as mismatch -> full
  22864. // content (200)
  22865. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22866. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22867. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22868. ASSERT_TRUE(res_ifrange);
  22869. EXPECT_EQ(200, res_ifrange->status);
  22870. svr.stop();
  22871. t.join();
  22872. std::remove(fname);
  22873. }
  22874. TEST(ETagTest, NegativeFileModificationTime) {
  22875. using namespace httplib;
  22876. const char *fname = "ims_negative_mtime.txt";
  22877. const std::string content = "negative-mtime";
  22878. {
  22879. std::ofstream ofs(fname);
  22880. ofs << content;
  22881. ASSERT_TRUE(ofs.good());
  22882. }
  22883. // Try to set file mtime to a negative value. This may fail on some
  22884. // platforms/filesystems; if it fails, the test will still verify server
  22885. // behaves safely by performing a regular conditional request.
  22886. #if defined(__APPLE__) || defined(__linux__)
  22887. bool set_negative = false;
  22888. do {
  22889. struct timeval times[2];
  22890. // access time: now
  22891. times[0].tv_sec = time(nullptr);
  22892. times[0].tv_usec = 0;
  22893. // modification time: negative (e.g., -1)
  22894. times[1].tv_sec = -1;
  22895. times[1].tv_usec = 0;
  22896. if (utimes(fname, times) == 0) { set_negative = true; }
  22897. } while (0);
  22898. #else
  22899. bool set_negative = false;
  22900. #endif
  22901. Server svr;
  22902. svr.set_mount_point("/static", ".");
  22903. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22904. svr.wait_until_ready();
  22905. Client cli(HOST, PORT);
  22906. auto res1 = cli.Get(std::string("/static/") + fname);
  22907. ASSERT_TRUE(res1);
  22908. ASSERT_EQ(200, res1->status);
  22909. bool has_last_modified = res1->has_header("Last-Modified");
  22910. std::string last_modified;
  22911. if (has_last_modified) {
  22912. last_modified = res1->get_header_value("Last-Modified");
  22913. }
  22914. if (set_negative) {
  22915. // If we successfully set a negative mtime, ensure server returns a
  22916. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22917. // with an old date and ensure server handles it without crash.
  22918. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22919. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22920. ASSERT_TRUE(res2);
  22921. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22922. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22923. } else {
  22924. // Could not set negative mtime on this platform; fall back to verifying
  22925. // that normal invalid/malformed dates are treated safely (non-304).
  22926. Headers h_bad_date = {
  22927. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22928. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22929. ASSERT_TRUE(res_bad);
  22930. EXPECT_EQ(200, res_bad->status);
  22931. }
  22932. svr.stop();
  22933. t.join();
  22934. std::remove(fname);
  22935. }
  22936. //==============================================================================
  22937. // Integration Tests with Server
  22938. //==============================================================================
  22939. class SSEIntegrationTest : public ::testing::Test {
  22940. protected:
  22941. void SetUp() override {
  22942. stop_server_.store(false);
  22943. events_.clear();
  22944. server_ = httplib::detail::make_unique<Server>();
  22945. setup_server();
  22946. start_server();
  22947. }
  22948. void TearDown() override {
  22949. stop_server_.store(true);
  22950. event_cv_.notify_all();
  22951. server_->stop();
  22952. if (server_thread_.joinable()) { server_thread_.join(); }
  22953. }
  22954. void setup_server() {
  22955. // Simple SSE endpoint
  22956. server_->Get("/events", [this](const Request &req, Response &res) {
  22957. auto last_id = req.get_header_value("Last-Event-ID");
  22958. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  22959. res.set_chunked_content_provider(
  22960. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  22961. std::unique_lock<std::mutex> lock(event_mutex_);
  22962. if (event_cv_.wait_for(
  22963. lock, std::chrono::milliseconds(200), [this] {
  22964. return !events_.empty() || stop_server_.load();
  22965. })) {
  22966. if (stop_server_.load()) { return false; }
  22967. if (!events_.empty()) {
  22968. std::string event = events_.front();
  22969. events_.erase(events_.begin());
  22970. sink.write(event.data(), event.size());
  22971. return true;
  22972. }
  22973. }
  22974. return !stop_server_.load();
  22975. });
  22976. });
  22977. // Endpoint that returns error
  22978. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  22979. res.status = 500;
  22980. res.set_content("Internal Server Error", "text/plain");
  22981. });
  22982. // Endpoint for custom event types
  22983. server_->Get("/custom-events", [](const Request &, Response &res) {
  22984. res.set_chunked_content_provider(
  22985. "text/event-stream", [](size_t offset, DataSink &sink) {
  22986. if (offset == 0) {
  22987. std::string event = "event: update\ndata: updated\n\n"
  22988. "event: delete\ndata: deleted\n\n";
  22989. sink.write(event.data(), event.size());
  22990. }
  22991. return false; // End stream after sending
  22992. });
  22993. });
  22994. }
  22995. void start_server() {
  22996. port_ = server_->bind_to_any_port(HOST);
  22997. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22998. // Wait for server to start
  22999. while (!server_->is_running()) {
  23000. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23001. }
  23002. }
  23003. int get_port() const { return port_; }
  23004. void send_event(const std::string &event) {
  23005. std::lock_guard<std::mutex> lock(event_mutex_);
  23006. events_.push_back(event);
  23007. event_cv_.notify_all();
  23008. }
  23009. std::unique_ptr<Server> server_;
  23010. std::thread server_thread_;
  23011. std::mutex event_mutex_;
  23012. std::condition_variable event_cv_;
  23013. std::vector<std::string> events_;
  23014. std::atomic<bool> stop_server_{false};
  23015. std::string last_received_event_id_;
  23016. int port_ = 0;
  23017. };
  23018. //==============================================================================
  23019. // SSE Parser Tests
  23020. //==============================================================================
  23021. struct SSEParseResult {
  23022. std::vector<sse::SSEMessage> events;
  23023. std::vector<std::string> ids;
  23024. std::vector<int> retries;
  23025. bool ok = true;
  23026. std::string trace; // Every handler call in order
  23027. };
  23028. static SSEParseResult
  23029. sse_parse(const std::vector<std::string> &chunks,
  23030. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  23031. SSEParseResult r;
  23032. detail::SSEParser parser(
  23033. [&](const sse::SSEMessage &msg) {
  23034. r.events.push_back(msg);
  23035. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  23036. },
  23037. [&](const std::string &id) {
  23038. r.ids.push_back(id);
  23039. r.trace += "id[" + id + "]";
  23040. },
  23041. [&](int retry_ms) {
  23042. r.retries.push_back(retry_ms);
  23043. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  23044. },
  23045. max_event_length);
  23046. for (const auto &chunk : chunks) {
  23047. if (!parser.parse(chunk.data(), chunk.size())) {
  23048. r.ok = false;
  23049. break;
  23050. }
  23051. }
  23052. return r;
  23053. }
  23054. static SSEParseResult sse_parse(const std::string &stream) {
  23055. return sse_parse(std::vector<std::string>{stream});
  23056. }
  23057. TEST(SSEParserTest, SingleLineData) {
  23058. auto r = sse_parse("data: hello\n\n");
  23059. ASSERT_EQ(r.events.size(), 1u);
  23060. EXPECT_EQ(r.events[0].data, "hello");
  23061. EXPECT_EQ(r.events[0].event, "message");
  23062. }
  23063. TEST(SSEParserTest, MultiLineData) {
  23064. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  23065. ASSERT_EQ(r.events.size(), 1u);
  23066. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23067. }
  23068. TEST(SSEParserTest, CustomEventType) {
  23069. auto r = sse_parse("event: update\ndata: payload\n\n");
  23070. ASSERT_EQ(r.events.size(), 1u);
  23071. EXPECT_EQ(r.events[0].event, "update");
  23072. EXPECT_EQ(r.events[0].data, "payload");
  23073. }
  23074. TEST(SSEParserTest, EventIdHandling) {
  23075. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23076. ASSERT_EQ(r.events.size(), 1u);
  23077. EXPECT_EQ(r.events[0].id, "12345");
  23078. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23079. }
  23080. TEST(SSEParserTest, EmptyEventId) {
  23081. auto r = sse_parse("id:\ndata: test\n\n");
  23082. ASSERT_EQ(r.events.size(), 1u);
  23083. EXPECT_EQ(r.events[0].id, "");
  23084. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23085. }
  23086. TEST(SSEParserTest, CommentsIgnored) {
  23087. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23088. ASSERT_EQ(r.events.size(), 1u);
  23089. EXPECT_EQ(r.events[0].data, "hello");
  23090. EXPECT_EQ(r.events[0].event, "message");
  23091. }
  23092. TEST(SSEParserTest, ColonInValue) {
  23093. auto r = sse_parse("data: hello:world:test\n\n");
  23094. ASSERT_EQ(r.events.size(), 1u);
  23095. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23096. }
  23097. TEST(SSEParserTest, FieldNameOnly) {
  23098. // A line without a colon is a field name with an empty value
  23099. auto r = sse_parse("data\n\n");
  23100. ASSERT_EQ(r.events.size(), 1u);
  23101. EXPECT_EQ(r.events[0].data, "");
  23102. }
  23103. TEST(SSEParserTest, TrailingCarriageReturn) {
  23104. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23105. ASSERT_EQ(r.events.size(), 1u);
  23106. EXPECT_EQ(r.events[0].event, "update");
  23107. EXPECT_EQ(r.events[0].data, "hello");
  23108. }
  23109. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23110. auto r = sse_parse("data\r\n\r\n");
  23111. ASSERT_EQ(r.events.size(), 1u);
  23112. EXPECT_EQ(r.events[0].data, "");
  23113. }
  23114. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23115. auto r = sse_parse("event: update\rdata: hello\r\r");
  23116. ASSERT_EQ(r.events.size(), 1u);
  23117. EXPECT_EQ(r.events[0].event, "update");
  23118. EXPECT_EQ(r.events[0].data, "hello");
  23119. }
  23120. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23121. // Chunk boundaries fall inside every \r\n and right before the first one
  23122. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23123. "\ndata: hello\r", "\n\r", "\n"});
  23124. ASSERT_EQ(r.events.size(), 1u);
  23125. EXPECT_EQ(r.events[0].event, "update");
  23126. EXPECT_EQ(r.events[0].data, "hello");
  23127. }
  23128. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23129. // Only a BOM at the start of the stream is ignored
  23130. auto r = sse_parse("\xEF\xBB\xBF"
  23131. "data: first\n\n"
  23132. "\xEF\xBB\xBF"
  23133. "data: second\n\n");
  23134. ASSERT_EQ(r.events.size(), 1u);
  23135. EXPECT_EQ(r.events[0].data, "first");
  23136. }
  23137. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23138. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23139. ASSERT_EQ(r.events.size(), 1u);
  23140. EXPECT_EQ(r.events[0].data, "hello");
  23141. EXPECT_EQ(r.events[0].event, "message");
  23142. }
  23143. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23144. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23145. ASSERT_EQ(r.events.size(), 2u);
  23146. EXPECT_EQ(r.events[0].data, "hello");
  23147. EXPECT_EQ(r.events[1].data, "hello");
  23148. }
  23149. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23150. // An event without data is not dispatched, and its type must not leak
  23151. // into the next event
  23152. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23153. ASSERT_EQ(r.events.size(), 1u);
  23154. EXPECT_EQ(r.events[0].event, "message");
  23155. EXPECT_EQ(r.events[0].data, "hello");
  23156. }
  23157. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23158. // Also when the empty field replaces an earlier type
  23159. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23160. ASSERT_EQ(r.events.size(), 2u);
  23161. EXPECT_EQ(r.events[0].event, "message");
  23162. EXPECT_EQ(r.events[1].event, "message");
  23163. }
  23164. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23165. auto r = sse_parse("id: 42\n\n");
  23166. EXPECT_TRUE(r.events.empty());
  23167. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23168. }
  23169. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23170. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23171. ASSERT_EQ(r.events.size(), 2u);
  23172. EXPECT_EQ(r.events[0].id, "1");
  23173. EXPECT_EQ(r.events[1].id, "");
  23174. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23175. }
  23176. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23177. // Ids that cannot be carried in a Last-Event-ID header
  23178. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23179. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23180. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23181. }
  23182. TEST(SSEParserTest, RetryDigitsOnly) {
  23183. auto r = sse_parse("retry: 1000\n");
  23184. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23185. // A value that is not all ASCII digits, or does not fit, is ignored
  23186. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23187. EXPECT_TRUE(r.retries.empty());
  23188. }
  23189. TEST(SSEParserTest, CompleteEventParsing) {
  23190. auto r = sse_parse("event: notification\nid: evt-42\n"
  23191. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23192. ASSERT_EQ(r.events.size(), 1u);
  23193. EXPECT_EQ(r.events[0].event, "notification");
  23194. EXPECT_EQ(r.events[0].id, "evt-42");
  23195. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23196. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23197. }
  23198. TEST(SSEParserTest, IncompleteEventNotReported) {
  23199. // An event still waiting for its blank line when the stream ends is
  23200. // discarded per the SSE spec
  23201. auto r = sse_parse("id: 1\ndata: x\n");
  23202. EXPECT_TRUE(r.events.empty());
  23203. EXPECT_TRUE(r.ids.empty());
  23204. }
  23205. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23206. const std::vector<std::string> streams = {
  23207. "\xEF\xBB\xBF"
  23208. "data: bom\r\n\r\n",
  23209. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23210. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23211. };
  23212. for (const auto &stream : streams) {
  23213. auto expected = sse_parse(stream).trace;
  23214. ASSERT_FALSE(expected.empty());
  23215. for (size_t i = 0; i <= stream.size(); i++) {
  23216. auto r = sse_parse(
  23217. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23218. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23219. }
  23220. std::vector<std::string> bytes;
  23221. for (auto c : stream) {
  23222. bytes.emplace_back(1, c);
  23223. }
  23224. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23225. }
  23226. }
  23227. TEST(SSEParserTest, MaxEventLength) {
  23228. // A line still waiting for its end
  23229. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23230. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23231. // Data accumulated over the lines of one event
  23232. EXPECT_TRUE(
  23233. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23234. EXPECT_FALSE(
  23235. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23236. // 0 means no limit
  23237. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23238. // Events completed in the same chunk are still reported
  23239. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23240. EXPECT_FALSE(r.ok);
  23241. ASSERT_EQ(r.events.size(), 1u);
  23242. EXPECT_EQ(r.events[0].data, "a");
  23243. }
  23244. TEST(SSEMessageTest, Clear) {
  23245. sse::SSEMessage msg;
  23246. msg.event = "custom";
  23247. msg.data = "some data";
  23248. msg.id = "123";
  23249. msg.clear();
  23250. EXPECT_EQ(msg.event, "message");
  23251. EXPECT_EQ(msg.data, "");
  23252. EXPECT_EQ(msg.id, "");
  23253. }
  23254. //==============================================================================
  23255. // SSE Integration Tests
  23256. //==============================================================================
  23257. // Test: Successful connection and on_open callback
  23258. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23259. // Add a simple endpoint that sends one event and closes
  23260. server_->Get("/simple-event", [](const Request &, Response &res) {
  23261. res.set_chunked_content_provider(
  23262. "text/event-stream", [](size_t offset, DataSink &sink) {
  23263. if (offset == 0) {
  23264. std::string event = "data: hello\n\n";
  23265. sink.write(event.data(), event.size());
  23266. }
  23267. return false; // Close stream after sending
  23268. });
  23269. });
  23270. Client client("localhost", get_port());
  23271. sse::SSEClient sse(client, "/simple-event");
  23272. std::atomic<bool> open_called{false};
  23273. std::atomic<bool> message_received{false};
  23274. sse.on_open([&open_called]() { open_called.store(true); });
  23275. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23276. if (msg.data == "hello") { message_received.store(true); }
  23277. });
  23278. sse.set_reconnect_interval(100);
  23279. sse.set_max_reconnect_attempts(1);
  23280. // Start async
  23281. sse.start_async();
  23282. // Wait for message to be processed
  23283. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23284. sse.stop();
  23285. EXPECT_TRUE(open_called.load());
  23286. EXPECT_TRUE(message_received.load());
  23287. }
  23288. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23289. // A data line that never ends.
  23290. server_->Get("/endless-line", [](const Request &, Response &res) {
  23291. res.set_chunked_content_provider(
  23292. "text/event-stream", [](size_t offset, DataSink &sink) {
  23293. if (offset == 0) { sink.write("data: ", 6); }
  23294. std::string chunk(64 * 1024, 'A');
  23295. return sink.write(chunk.data(), chunk.size());
  23296. });
  23297. });
  23298. Client client("localhost", get_port());
  23299. sse::SSEClient sse(client, "/endless-line");
  23300. std::atomic<bool> too_long{false};
  23301. sse.on_error([&](Error err) {
  23302. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23303. });
  23304. sse.set_max_reconnect_attempts(1);
  23305. sse.start_async();
  23306. for (int i = 0; i < 500 && !too_long; i++) {
  23307. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23308. }
  23309. sse.stop();
  23310. EXPECT_TRUE(too_long);
  23311. }
  23312. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23313. // Far more in all than the client's payload limit below.
  23314. server_->Get("/many-events", [](const Request &, Response &res) {
  23315. res.set_chunked_content_provider(
  23316. "text/event-stream", [](size_t offset, DataSink &sink) {
  23317. if (offset == 0) {
  23318. std::string events;
  23319. for (int i = 0; i < 1000; i++) {
  23320. events += "data: message\n\n";
  23321. }
  23322. sink.write(events.data(), events.size());
  23323. }
  23324. return false;
  23325. });
  23326. });
  23327. Client client("localhost", get_port());
  23328. client.set_payload_max_length(1024);
  23329. sse::SSEClient sse(client, "/many-events");
  23330. std::atomic<int> messages{0};
  23331. std::atomic<bool> too_large{false};
  23332. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23333. sse.on_error([&](Error err) {
  23334. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23335. });
  23336. sse.set_max_reconnect_attempts(1);
  23337. sse.start_async();
  23338. for (int i = 0; i < 500 && messages < 1000; i++) {
  23339. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23340. }
  23341. sse.stop();
  23342. EXPECT_GE(messages.load(), 1000);
  23343. EXPECT_FALSE(too_large);
  23344. }
  23345. // Test: on_message callback
  23346. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23347. // Endpoint that sends multiple events then closes
  23348. server_->Get("/multi-event", [](const Request &, Response &res) {
  23349. res.set_chunked_content_provider(
  23350. "text/event-stream", [](size_t offset, DataSink &sink) {
  23351. if (offset == 0) {
  23352. std::string events = "data: message1\n\ndata: message2\n\n";
  23353. sink.write(events.data(), events.size());
  23354. }
  23355. return false;
  23356. });
  23357. });
  23358. Client client("localhost", get_port());
  23359. sse::SSEClient sse(client, "/multi-event");
  23360. std::vector<std::string> received_messages;
  23361. std::mutex messages_mutex;
  23362. sse.on_message([&](const sse::SSEMessage &msg) {
  23363. std::lock_guard<std::mutex> lock(messages_mutex);
  23364. received_messages.push_back(msg.data);
  23365. });
  23366. sse.set_reconnect_interval(100);
  23367. sse.set_max_reconnect_attempts(1);
  23368. sse.start_async();
  23369. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23370. sse.stop();
  23371. std::lock_guard<std::mutex> lock(messages_mutex);
  23372. EXPECT_GE(received_messages.size(), 2u);
  23373. if (received_messages.size() >= 2) {
  23374. EXPECT_EQ(received_messages[0], "message1");
  23375. EXPECT_EQ(received_messages[1], "message2");
  23376. }
  23377. }
  23378. // Test: on_event for specific types
  23379. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23380. Client client("localhost", get_port());
  23381. sse::SSEClient sse(client, "/custom-events");
  23382. std::atomic<bool> update_received{false};
  23383. std::atomic<bool> delete_received{false};
  23384. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23385. if (msg.data == "updated") { update_received.store(true); }
  23386. });
  23387. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23388. if (msg.data == "deleted") { delete_received.store(true); }
  23389. });
  23390. sse.set_max_reconnect_attempts(1);
  23391. sse.start_async();
  23392. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23393. sse.stop();
  23394. EXPECT_TRUE(update_received.load());
  23395. EXPECT_TRUE(delete_received.load());
  23396. }
  23397. // Test: on_error callback on connection failure
  23398. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23399. // Connect to a non-existent port
  23400. Client client("localhost", 59999);
  23401. sse::SSEClient sse(client, "/events");
  23402. std::atomic<bool> error_called{false};
  23403. Error received_error = Error::Success;
  23404. sse.on_error([&](Error err) {
  23405. error_called.store(true);
  23406. received_error = err;
  23407. });
  23408. sse.set_reconnect_interval(50);
  23409. sse.set_max_reconnect_attempts(1);
  23410. sse.start_async();
  23411. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23412. sse.stop();
  23413. EXPECT_TRUE(error_called.load());
  23414. EXPECT_NE(received_error, Error::Success);
  23415. }
  23416. // Test: Last-Event-ID header sent on reconnect
  23417. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23418. // Endpoint that sends event with ID
  23419. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23420. res.set_chunked_content_provider(
  23421. "text/event-stream", [](size_t offset, DataSink &sink) {
  23422. if (offset == 0) {
  23423. std::string event = "id: evt-123\ndata: test\n\n";
  23424. sink.write(event.data(), event.size());
  23425. }
  23426. return false;
  23427. });
  23428. });
  23429. Client client("localhost", get_port());
  23430. sse::SSEClient sse(client, "/event-with-id");
  23431. std::atomic<bool> id_received{false};
  23432. sse.on_message([&](const sse::SSEMessage &msg) {
  23433. if (!msg.id.empty()) { id_received.store(true); }
  23434. });
  23435. sse.set_reconnect_interval(100);
  23436. sse.set_max_reconnect_attempts(1);
  23437. sse.start_async();
  23438. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23439. sse.stop();
  23440. EXPECT_TRUE(id_received.load());
  23441. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23442. }
  23443. // Test: last_event_id() read from another thread while start_async() runs
  23444. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23445. // Ids of every length up to 200, so the stored id keeps changing size
  23446. server_->Get("/many-ids", [](const Request &, Response &res) {
  23447. res.set_chunked_content_provider(
  23448. "text/event-stream", [](size_t offset, DataSink &sink) {
  23449. if (offset == 0) {
  23450. std::string events;
  23451. for (size_t i = 0; i < 2000; i++) {
  23452. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23453. events += "data: x\n\n";
  23454. }
  23455. events += "id: end\ndata: x\n\n";
  23456. sink.write(events.data(), events.size());
  23457. }
  23458. return false;
  23459. });
  23460. });
  23461. Client client("localhost", get_port());
  23462. sse::SSEClient sse(client, "/many-ids");
  23463. // Wait out the rest of the test rather than replay the stream
  23464. sse.set_reconnect_interval(10000);
  23465. sse.set_max_reconnect_attempts(1);
  23466. sse.start_async();
  23467. auto well_formed = true;
  23468. std::string id;
  23469. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23470. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23471. id = sse.last_event_id();
  23472. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23473. well_formed = false;
  23474. }
  23475. }
  23476. sse.stop();
  23477. EXPECT_TRUE(well_formed);
  23478. EXPECT_EQ(sse.last_event_id(), "end");
  23479. }
  23480. // Test: Manual stop
  23481. TEST_F(SSEIntegrationTest, ManualStop) {
  23482. // Endpoint that sends one event and stays open briefly. The server outlives
  23483. // this test body, so the provider uses the fixture's flag, not a local.
  23484. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23485. res.set_chunked_content_provider(
  23486. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23487. if (offset == 0) {
  23488. std::string event = "data: connected\n\n";
  23489. sink.write(event.data(), event.size());
  23490. }
  23491. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23492. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23493. }
  23494. return false;
  23495. });
  23496. });
  23497. Client client("localhost", get_port());
  23498. sse::SSEClient sse(client, "/stay-open");
  23499. std::atomic<bool> connected{false};
  23500. sse.on_open([&connected]() { connected.store(true); });
  23501. sse.set_reconnect_interval(100);
  23502. sse.set_max_reconnect_attempts(1);
  23503. sse.start_async();
  23504. // Wait for connection to establish
  23505. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23506. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23507. }
  23508. EXPECT_TRUE(connected.load());
  23509. EXPECT_TRUE(sse.is_connected());
  23510. // Signal handler to stop
  23511. stop_server_.store(true);
  23512. // Stop SSE client
  23513. sse.stop();
  23514. EXPECT_FALSE(sse.is_connected());
  23515. }
  23516. // Sends one event, then nothing until stop is set
  23517. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23518. return [&stop](const Request &, Response &res) {
  23519. res.set_chunked_content_provider(
  23520. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23521. if (offset == 0) {
  23522. std::string event = "data: hello\n\n";
  23523. sink.write(event.data(), event.size());
  23524. }
  23525. while (!stop.load()) {
  23526. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23527. }
  23528. return false;
  23529. });
  23530. };
  23531. }
  23532. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23533. static void check_stop_interrupts_blocked_read(Client &client) {
  23534. client.set_read_timeout(30, 0);
  23535. for (auto by_destructor : {false, true}) {
  23536. std::atomic<bool> received{false};
  23537. std::chrono::steady_clock::time_point start;
  23538. {
  23539. sse::SSEClient sse(client, "/idle-stream");
  23540. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23541. sse.start_async();
  23542. for (int i = 0; i < 500 && !received.load(); ++i) {
  23543. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23544. }
  23545. ASSERT_TRUE(received.load());
  23546. // Let the client block in the next read
  23547. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23548. start = std::chrono::steady_clock::now();
  23549. if (!by_destructor) { sse.stop(); }
  23550. }
  23551. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23552. std::chrono::seconds(2));
  23553. }
  23554. }
  23555. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23556. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23557. Client client("localhost", get_port());
  23558. check_stop_interrupts_blocked_read(client);
  23559. }
  23560. #ifdef CPPHTTPLIB_SSL_ENABLED
  23561. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23562. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23563. std::atomic<bool> done{false};
  23564. svr.Get("/idle-stream", idle_event_stream(done));
  23565. auto port = svr.bind_to_any_port(HOST);
  23566. std::thread t([&] { svr.listen_after_bind(); });
  23567. auto se = detail::scope_exit([&] {
  23568. done.store(true);
  23569. svr.stop();
  23570. t.join();
  23571. });
  23572. svr.wait_until_ready();
  23573. Client client("https://localhost:" + std::to_string(port));
  23574. client.enable_server_certificate_verification(false);
  23575. check_stop_interrupts_blocked_read(client);
  23576. }
  23577. #endif
  23578. // Test: SSEClient with custom headers
  23579. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23580. // Setup a server endpoint that checks for custom header
  23581. std::atomic<bool> header_received{false};
  23582. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23583. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23584. header_received.store(true);
  23585. }
  23586. res.set_chunked_content_provider("text/event-stream",
  23587. [](size_t, DataSink &) { return false; });
  23588. });
  23589. Client client("localhost", get_port());
  23590. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23591. sse::SSEClient sse(client, "/header-check", headers);
  23592. sse.set_max_reconnect_attempts(1);
  23593. sse.start_async();
  23594. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23595. sse.stop();
  23596. EXPECT_TRUE(header_received.load());
  23597. }
  23598. // Test: Reconnect interval configuration
  23599. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23600. Client client("localhost", get_port());
  23601. sse::SSEClient sse(client, "/events");
  23602. auto &result = sse.set_reconnect_interval(500);
  23603. // Builder pattern should return reference to self
  23604. EXPECT_EQ(&result, &sse);
  23605. }
  23606. // Test: Max reconnect attempts
  23607. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23608. // Connect to non-existent port to force reconnects
  23609. Client client("localhost", 59998);
  23610. sse::SSEClient sse(client, "/events");
  23611. std::atomic<int> error_count{0};
  23612. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23613. sse.set_reconnect_interval(50);
  23614. sse.set_max_reconnect_attempts(2);
  23615. auto start = std::chrono::steady_clock::now();
  23616. sse.start(); // Blocking call
  23617. auto end = std::chrono::steady_clock::now();
  23618. // Should have stopped after 2 failed attempts
  23619. EXPECT_GE(error_count.load(), 2);
  23620. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23621. auto duration =
  23622. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23623. #ifdef _WIN32
  23624. // Windows is much slower for socket connection failures
  23625. EXPECT_LT(duration.count(), 7000);
  23626. #else
  23627. EXPECT_LT(duration.count(), 1000);
  23628. #endif
  23629. }
  23630. // Test: Multi-line data in integration
  23631. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23632. // Endpoint with multi-line data
  23633. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23634. res.set_chunked_content_provider(
  23635. "text/event-stream", [](size_t offset, DataSink &sink) {
  23636. if (offset == 0) {
  23637. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23638. sink.write(event.data(), event.size());
  23639. }
  23640. return false;
  23641. });
  23642. });
  23643. Client client("localhost", get_port());
  23644. sse::SSEClient sse(client, "/multiline-data");
  23645. std::string received_data;
  23646. std::mutex data_mutex;
  23647. sse.on_message([&](const sse::SSEMessage &msg) {
  23648. std::lock_guard<std::mutex> lock(data_mutex);
  23649. received_data = msg.data;
  23650. });
  23651. sse.set_reconnect_interval(100);
  23652. sse.set_max_reconnect_attempts(1);
  23653. sse.start_async();
  23654. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23655. sse.stop();
  23656. std::lock_guard<std::mutex> lock(data_mutex);
  23657. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23658. }
  23659. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23660. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23661. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23662. DataSink &sink) {
  23663. if (offset == 0) {
  23664. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23665. sink.write(events.data(), events.size());
  23666. }
  23667. return false;
  23668. });
  23669. });
  23670. Client client("localhost", get_port());
  23671. sse::SSEClient sse(client, "/empty-data-lines");
  23672. std::mutex mutex;
  23673. std::condition_variable cv;
  23674. std::vector<std::string> received;
  23675. sse.on_message([&](const sse::SSEMessage &msg) {
  23676. std::lock_guard<std::mutex> lock(mutex);
  23677. received.push_back(msg.data);
  23678. cv.notify_all();
  23679. });
  23680. sse.set_max_reconnect_attempts(1);
  23681. sse.start_async();
  23682. {
  23683. std::unique_lock<std::mutex> lock(mutex);
  23684. cv.wait_for(lock, std::chrono::seconds(2),
  23685. [&] { return received.size() >= 3; });
  23686. }
  23687. sse.stop();
  23688. ASSERT_GE(received.size(), 3u);
  23689. EXPECT_EQ(received[0], "");
  23690. EXPECT_EQ(received[1], "\nhello");
  23691. EXPECT_EQ(received[2], "");
  23692. }
  23693. // Test: Auto-reconnect after server disconnection
  23694. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23695. std::atomic<int> connection_count{0};
  23696. std::atomic<int> message_count{0};
  23697. // Endpoint that sends one event and closes, forcing reconnect
  23698. server_->Get("/reconnect-test",
  23699. [&connection_count](const Request &, Response &res) {
  23700. connection_count.fetch_add(1);
  23701. res.set_chunked_content_provider(
  23702. "text/event-stream", [](size_t offset, DataSink &sink) {
  23703. if (offset == 0) {
  23704. std::string event = "data: hello\n\n";
  23705. sink.write(event.data(), event.size());
  23706. }
  23707. return false; // Close connection after sending
  23708. });
  23709. });
  23710. Client client("localhost", get_port());
  23711. sse::SSEClient sse(client, "/reconnect-test");
  23712. sse.on_message([&message_count](const sse::SSEMessage &) {
  23713. message_count.fetch_add(1);
  23714. });
  23715. sse.set_reconnect_interval(100);
  23716. sse.set_max_reconnect_attempts(3);
  23717. sse.start_async();
  23718. // Wait long enough for multiple reconnects
  23719. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23720. sse.stop();
  23721. // Should have connected multiple times (initial + reconnects)
  23722. EXPECT_GE(connection_count.load(), 2);
  23723. // Should have received messages from multiple connections
  23724. EXPECT_GE(message_count.load(), 2);
  23725. }
  23726. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23727. std::atomic<int> connection_count{0};
  23728. // Neither Content-Length nor chunked: the close ends the stream
  23729. server_->Get("/close-delimited",
  23730. [&connection_count](const Request &, Response &res) {
  23731. connection_count.fetch_add(1);
  23732. res.set_content_provider(
  23733. "text/event-stream", [](size_t offset, DataSink &sink) {
  23734. if (offset == 0) {
  23735. std::string event = "data: hello\n\n";
  23736. sink.write(event.data(), event.size());
  23737. } else {
  23738. sink.done();
  23739. }
  23740. return true;
  23741. });
  23742. });
  23743. Client client("localhost", get_port());
  23744. sse::SSEClient sse(client, "/close-delimited");
  23745. std::atomic<int> error_count{0};
  23746. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23747. sse.set_reconnect_interval(100);
  23748. sse.start_async();
  23749. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23750. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23751. }
  23752. sse.stop();
  23753. // Reconnects as after any end of the stream, but reports no error
  23754. EXPECT_GE(connection_count.load(), 2);
  23755. EXPECT_EQ(0, error_count.load());
  23756. }
  23757. // Test: A retry field of all ASCII digits sets the reconnection time
  23758. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23759. std::mutex mutex;
  23760. std::condition_variable cv;
  23761. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23762. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23763. {
  23764. std::lock_guard<std::mutex> lock(mutex);
  23765. connected_at.push_back(std::chrono::steady_clock::now());
  23766. cv.notify_all();
  23767. }
  23768. res.set_chunked_content_provider(
  23769. "text/event-stream", [](size_t offset, DataSink &sink) {
  23770. if (offset == 0) {
  23771. std::string event = "retry: 0\ndata: hello\n\n";
  23772. sink.write(event.data(), event.size());
  23773. }
  23774. return false;
  23775. });
  23776. });
  23777. Client client("localhost", get_port());
  23778. sse::SSEClient sse(client, "/zero-retry");
  23779. sse.set_reconnect_interval(10000);
  23780. sse.start_async();
  23781. {
  23782. std::unique_lock<std::mutex> lock(mutex);
  23783. cv.wait_for(lock, std::chrono::seconds(5),
  23784. [&] { return connected_at.size() >= 2; });
  23785. }
  23786. sse.stop();
  23787. // The server-supplied interval is applied, but never below 100ms, so
  23788. // "retry: 0" does not cause a busy reconnect loop
  23789. std::lock_guard<std::mutex> lock(mutex);
  23790. ASSERT_GE(connected_at.size(), 2u);
  23791. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23792. connected_at[1] - connected_at[0])
  23793. .count();
  23794. EXPECT_GE(interval_ms, 100);
  23795. }
  23796. // Test: Last-Event-ID sent on reconnect
  23797. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23798. std::atomic<int> connection_count{0};
  23799. std::vector<std::string> received_last_event_ids;
  23800. std::mutex id_mutex;
  23801. // Endpoint that checks Last-Event-ID header and sends event with ID
  23802. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23803. int conn = connection_count.fetch_add(1);
  23804. // Capture the Last-Event-ID header from each connection
  23805. {
  23806. std::lock_guard<std::mutex> lock(id_mutex);
  23807. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23808. }
  23809. res.set_chunked_content_provider(
  23810. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23811. if (offset == 0) {
  23812. std::string event =
  23813. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23814. sink.write(event.data(), event.size());
  23815. }
  23816. return false;
  23817. });
  23818. });
  23819. Client client("localhost", get_port());
  23820. sse::SSEClient sse(client, "/reconnect-with-id");
  23821. sse.set_reconnect_interval(100);
  23822. sse.set_max_reconnect_attempts(3);
  23823. sse.start_async();
  23824. // Wait for at least 2 connections
  23825. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23826. sse.stop();
  23827. // Verify behavior
  23828. std::lock_guard<std::mutex> lock(id_mutex);
  23829. EXPECT_GE(received_last_event_ids.size(), 2u);
  23830. // First connection should have no Last-Event-ID
  23831. if (!received_last_event_ids.empty()) {
  23832. EXPECT_EQ(received_last_event_ids[0], "");
  23833. }
  23834. // Second connection should have Last-Event-ID from first connection
  23835. if (received_last_event_ids.size() >= 2) {
  23836. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23837. }
  23838. }
  23839. // Test: set_headers updates headers used on reconnect
  23840. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23841. std::vector<std::string> received_tokens;
  23842. std::mutex token_mutex;
  23843. // Endpoint that captures Authorization header
  23844. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23845. {
  23846. std::lock_guard<std::mutex> lock(token_mutex);
  23847. received_tokens.push_back(req.get_header_value("Authorization"));
  23848. }
  23849. res.set_chunked_content_provider(
  23850. "text/event-stream", [](size_t offset, DataSink &sink) {
  23851. if (offset == 0) {
  23852. std::string event = "data: hello\n\n";
  23853. sink.write(event.data(), event.size());
  23854. }
  23855. return false; // Close connection to trigger reconnect
  23856. });
  23857. });
  23858. Client client("localhost", get_port());
  23859. Headers headers = {{"Authorization", "Bearer old-token"}};
  23860. sse::SSEClient sse(client, "/auth-check", headers);
  23861. // Update headers on each successful connection
  23862. sse.on_open(
  23863. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23864. sse.set_reconnect_interval(100);
  23865. sse.set_max_reconnect_attempts(3);
  23866. sse.start_async();
  23867. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23868. sse.stop();
  23869. std::lock_guard<std::mutex> lock(token_mutex);
  23870. ASSERT_GE(received_tokens.size(), 2u);
  23871. // First connection uses original header
  23872. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23873. // Second connection uses updated header from set_headers
  23874. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23875. }
  23876. // Test: 401 allows reconnection (so on_error can refresh headers)
  23877. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23878. std::atomic<int> connection_count{0};
  23879. // Endpoint: returns 401 on first attempt, 200 on second
  23880. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23881. int conn = connection_count.fetch_add(1);
  23882. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23883. res.status = StatusCode::Unauthorized_401;
  23884. res.set_content("Unauthorized", "text/plain");
  23885. return;
  23886. }
  23887. res.set_chunked_content_provider(
  23888. "text/event-stream", [](size_t offset, DataSink &sink) {
  23889. if (offset == 0) {
  23890. std::string event = "data: authenticated\n\n";
  23891. sink.write(event.data(), event.size());
  23892. }
  23893. return false;
  23894. });
  23895. });
  23896. Client client("localhost", get_port());
  23897. Headers headers = {{"Authorization", "Bearer expired"}};
  23898. sse::SSEClient sse(client, "/auth-retry", headers);
  23899. std::atomic<bool> message_received{false};
  23900. // Refresh token on error
  23901. sse.on_error(
  23902. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23903. sse.on_message([&](const sse::SSEMessage &msg) {
  23904. if (msg.data == "authenticated") { message_received.store(true); }
  23905. });
  23906. sse.set_reconnect_interval(100);
  23907. sse.set_max_reconnect_attempts(3);
  23908. sse.start_async();
  23909. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23910. sse.stop();
  23911. // Should have reconnected after 401 and succeeded with new token
  23912. EXPECT_GE(connection_count.load(), 2);
  23913. EXPECT_TRUE(message_received.load());
  23914. }
  23915. TEST(Issue2318Test, EmptyHostString) {
  23916. {
  23917. httplib::Client cli_empty("", PORT);
  23918. auto res = cli_empty.Get("/");
  23919. ASSERT_FALSE(res);
  23920. EXPECT_EQ(httplib::Error::Connection, res.error());
  23921. }
  23922. {
  23923. httplib::Client cli(" ", PORT);
  23924. auto res = cli.Get("/");
  23925. ASSERT_FALSE(res);
  23926. EXPECT_EQ(httplib::Error::Connection, res.error());
  23927. }
  23928. }
  23929. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23930. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23931. Server svr;
  23932. // Set a small payload limit (1KB)
  23933. svr.set_payload_max_length(1024);
  23934. svr.Post("/test", [&](const Request &req, Response &res) {
  23935. res.set_content("Body size: " + std::to_string(req.body.size()),
  23936. "text/plain");
  23937. });
  23938. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23939. auto se = detail::scope_exit([&] {
  23940. svr.stop();
  23941. listen_thread.join();
  23942. });
  23943. svr.wait_until_ready();
  23944. // Create data that compresses well but exceeds limit when decompressed
  23945. // 8KB of repeated null bytes compresses to a very small size
  23946. std::string original_data(8 * 1024, '\0');
  23947. // Compress the data using gzip
  23948. std::string compressed_data;
  23949. detail::gzip_compressor compressor;
  23950. compressor.compress(original_data.data(), original_data.size(), true,
  23951. [&](const char *data, size_t size) {
  23952. compressed_data.append(data, size);
  23953. return true;
  23954. });
  23955. // Verify compression worked (compressed should be much smaller)
  23956. ASSERT_LT(compressed_data.size(), original_data.size());
  23957. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  23958. // Send compressed data with Content-Encoding: gzip
  23959. Client cli(HOST, PORT);
  23960. Headers headers = {{"Content-Encoding", "gzip"}};
  23961. auto res =
  23962. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  23963. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  23964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23965. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  23966. }
  23967. #endif
  23968. // ============================================================================
  23969. // OpenSSL-Specific Tests
  23970. // ============================================================================
  23971. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  23972. X509 *readCertificate(const std::string &strFileName) {
  23973. std::ifstream inStream(strFileName);
  23974. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  23975. std::istreambuf_iterator<char>());
  23976. if (strCertPEM.empty()) return (nullptr);
  23977. BIO *pbCert = BIO_new(BIO_s_mem());
  23978. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  23979. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  23980. BIO_free(pbCert);
  23981. return (pCert);
  23982. }
  23983. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  23984. std::ifstream inStream(strFileName);
  23985. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  23986. std::istreambuf_iterator<char>());
  23987. if (strPrivateKeyPEM.empty()) return (nullptr);
  23988. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  23989. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  23990. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  23991. BIO_free(pbPrivKey);
  23992. return (pPrivateKey);
  23993. }
  23994. TEST(BindServerTest, UpdateCerts) {
  23995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  23996. int port = svr.bind_to_any_port("0.0.0.0");
  23997. ASSERT_TRUE(svr.is_valid());
  23998. ASSERT_TRUE(port > 0);
  23999. X509 *cert = readCertificate(SERVER_CERT_FILE);
  24000. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  24001. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  24002. ASSERT_TRUE(cert != nullptr);
  24003. ASSERT_TRUE(ca_cert != nullptr);
  24004. ASSERT_TRUE(key != nullptr);
  24005. X509_STORE *cert_store = X509_STORE_new();
  24006. X509_STORE_add_cert(cert_store, ca_cert);
  24007. // svr.update_certs(cert, key, cert_store); // deprecated
  24008. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  24009. CLIENT_CA_CERT_FILE);
  24010. ASSERT_TRUE(svr.is_valid());
  24011. svr.stop();
  24012. X509_STORE_free(cert_store);
  24013. X509_free(cert);
  24014. X509_free(ca_cert);
  24015. EVP_PKEY_free(key);
  24016. }
  24017. // Test that update_certs() updates client CA list correctly
  24018. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  24019. // Start with file-based constructor
  24020. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24021. ASSERT_TRUE(svr.is_valid());
  24022. // Initially no client CA list should be set
  24023. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24024. ASSERT_TRUE(ssl_ctx != nullptr);
  24025. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  24026. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  24027. // Now update with client CA (PEM string)
  24028. std::string cert_pem, key_pem, ca_pem;
  24029. read_file(SERVER_CERT_FILE, cert_pem);
  24030. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  24031. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  24032. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  24033. ASSERT_TRUE(svr.is_valid());
  24034. // Now client CA list should be set
  24035. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  24036. ASSERT_TRUE(ca_list_after != nullptr);
  24037. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  24038. }
  24039. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  24040. // Test that the file-path SSLServer constructor properly sets the client CA
  24041. // list that is sent to clients during the TLS handshake (CertificateRequest)
  24042. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24043. ASSERT_TRUE(svr.is_valid());
  24044. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24045. ASSERT_TRUE(ssl_ctx != nullptr);
  24046. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  24047. ASSERT_TRUE(ca_list != nullptr);
  24048. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  24049. }
  24050. #endif
  24051. // ============================================================================
  24052. // MbedTLS-Specific Tests
  24053. // ============================================================================
  24054. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  24055. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  24056. using namespace httplib::tls;
  24057. // Track if callback was invoked
  24058. bool callback_invoked = false;
  24059. // The callback receives void* ctx which is actually MbedTlsContext*
  24060. // We can access the mbedtls_ssl_config via the context
  24061. auto setup_callback = [&callback_invoked](void *ctx) {
  24062. callback_invoked = true;
  24063. // Cast to MbedTlsContext* to access the ssl config
  24064. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  24065. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24066. // Use static variables to hold certificate data (simplified for test)
  24067. static mbedtls_x509_crt own_cert;
  24068. static mbedtls_pk_context own_key;
  24069. static mbedtls_x509_crt ca_chain;
  24070. static bool initialized = false;
  24071. if (!initialized) {
  24072. mbedtls_x509_crt_init(&own_cert);
  24073. mbedtls_pk_init(&own_key);
  24074. mbedtls_x509_crt_init(&ca_chain);
  24075. // Load server certificate
  24076. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24077. return false;
  24078. }
  24079. // Load server private key.
  24080. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24081. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24082. #if MBEDTLS_VERSION_MAJOR == 3
  24083. ,
  24084. mbedtls_ctr_drbg_random, nullptr
  24085. #endif
  24086. ) != 0) {
  24087. return false;
  24088. }
  24089. // Load CA chain for client verification
  24090. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24091. return false;
  24092. }
  24093. initialized = true;
  24094. }
  24095. // Configure the SSL config
  24096. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24097. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24098. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24099. // Set minimum TLS version using mbedTLS native API
  24100. #if MBEDTLS_VERSION_MAJOR >= 3
  24101. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24102. #else
  24103. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24104. MBEDTLS_SSL_MINOR_VERSION_3);
  24105. #endif
  24106. return true;
  24107. };
  24108. SSLServer svr(setup_callback);
  24109. ASSERT_TRUE(svr.is_valid());
  24110. ASSERT_TRUE(callback_invoked);
  24111. svr.Get("/test", [&](const Request &req, Response &res) {
  24112. res.set_content("test", "text/plain");
  24113. auto cert = req.peer_cert();
  24114. ASSERT_TRUE(static_cast<bool>(cert));
  24115. auto common_name = cert.subject_cn();
  24116. EXPECT_EQ("Common Name", common_name);
  24117. });
  24118. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24119. auto se = detail::scope_exit([&] {
  24120. svr.stop();
  24121. t.join();
  24122. ASSERT_FALSE(svr.is_running());
  24123. });
  24124. svr.wait_until_ready();
  24125. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24126. cli.enable_server_certificate_verification(false);
  24127. cli.set_connection_timeout(30);
  24128. auto res = cli.Get("/test");
  24129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24130. ASSERT_EQ(StatusCode::OK_200, res->status);
  24131. }
  24132. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24133. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24134. // keep-alive SSL session, which reads through that config in
  24135. // mbedtls_ssl_close_notify.
  24136. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24137. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24138. ASSERT_TRUE(svr.is_valid());
  24139. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24140. res.set_content("test", "text/plain");
  24141. });
  24142. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24143. auto se = detail::scope_exit([&] {
  24144. svr.stop();
  24145. t.join();
  24146. ASSERT_FALSE(svr.is_running());
  24147. });
  24148. svr.wait_until_ready();
  24149. {
  24150. SSLClient cli(HOST, PORT);
  24151. cli.enable_server_certificate_verification(false);
  24152. cli.set_keep_alive(true);
  24153. auto res = cli.Get("/test");
  24154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24155. ASSERT_EQ(StatusCode::OK_200, res->status);
  24156. // cli is destructed here with the keep-alive SSL session still open.
  24157. }
  24158. }
  24159. #endif
  24160. // WebSocket Tests
  24161. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24162. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24163. // defining the meaning of these bits has been negotiated.
  24164. auto make_frame = [](uint8_t first_byte) {
  24165. std::string frame;
  24166. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24167. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24168. frame += "Hello";
  24169. return frame;
  24170. };
  24171. // RSV1 set (0x40)
  24172. {
  24173. detail::BufferStream strm;
  24174. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24175. ws::Opcode opcode;
  24176. std::string payload;
  24177. bool fin;
  24178. EXPECT_EQ(
  24179. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24180. ws::impl::FrameRead::Fail);
  24181. }
  24182. // RSV2 set (0x20)
  24183. {
  24184. detail::BufferStream strm;
  24185. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24186. ws::Opcode opcode;
  24187. std::string payload;
  24188. bool fin;
  24189. EXPECT_EQ(
  24190. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24191. ws::impl::FrameRead::Fail);
  24192. }
  24193. // RSV3 set (0x10)
  24194. {
  24195. detail::BufferStream strm;
  24196. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24197. ws::Opcode opcode;
  24198. std::string payload;
  24199. bool fin;
  24200. EXPECT_EQ(
  24201. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24202. ws::impl::FrameRead::Fail);
  24203. }
  24204. // No RSV bits set - should succeed
  24205. {
  24206. detail::BufferStream strm;
  24207. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24208. ws::Opcode opcode;
  24209. std::string payload;
  24210. bool fin;
  24211. EXPECT_EQ(
  24212. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24213. ws::impl::FrameRead::Ok);
  24214. EXPECT_EQ(ws::Opcode::Text, opcode);
  24215. EXPECT_EQ("Hello", payload);
  24216. EXPECT_TRUE(fin);
  24217. }
  24218. }
  24219. TEST(WebSocketTest, ControlFrameValidation) {
  24220. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24221. // payload length <= 125.
  24222. // Ping with FIN=0 - must be rejected
  24223. {
  24224. detail::BufferStream strm;
  24225. std::string frame;
  24226. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24227. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24228. strm.write(frame.data(), frame.size());
  24229. ws::Opcode opcode;
  24230. std::string payload;
  24231. bool fin;
  24232. EXPECT_EQ(
  24233. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24234. ws::impl::FrameRead::Fail);
  24235. }
  24236. // Close with FIN=0 - must be rejected
  24237. {
  24238. detail::BufferStream strm;
  24239. std::string frame;
  24240. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24241. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24242. strm.write(frame.data(), frame.size());
  24243. ws::Opcode opcode;
  24244. std::string payload;
  24245. bool fin;
  24246. EXPECT_EQ(
  24247. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24248. ws::impl::FrameRead::Fail);
  24249. }
  24250. // Ping with payload_len=126 (extended length) - must be rejected
  24251. {
  24252. detail::BufferStream strm;
  24253. std::string frame;
  24254. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24255. frame += static_cast<char>(126); // payload_len=126 (>125)
  24256. frame += static_cast<char>(0x00); // extended length high byte
  24257. frame += static_cast<char>(126); // extended length low byte
  24258. frame += std::string(126, 'x');
  24259. strm.write(frame.data(), frame.size());
  24260. ws::Opcode opcode;
  24261. std::string payload;
  24262. bool fin;
  24263. EXPECT_EQ(
  24264. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24265. ws::impl::FrameRead::Fail);
  24266. }
  24267. // Ping with FIN=1 and payload_len=125 - should succeed
  24268. {
  24269. detail::BufferStream strm;
  24270. std::string frame;
  24271. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24272. frame += static_cast<char>(125); // payload_len=125
  24273. frame += std::string(125, 'x');
  24274. strm.write(frame.data(), frame.size());
  24275. ws::Opcode opcode;
  24276. std::string payload;
  24277. bool fin;
  24278. EXPECT_EQ(
  24279. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24280. ws::impl::FrameRead::Ok);
  24281. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24282. EXPECT_EQ(125u, payload.size());
  24283. EXPECT_TRUE(fin);
  24284. }
  24285. }
  24286. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24287. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24288. // length MUST be 0.
  24289. // MSB set - must be rejected
  24290. {
  24291. detail::BufferStream strm;
  24292. std::string frame;
  24293. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24294. frame += static_cast<char>(127); // 64-bit extended length
  24295. frame += static_cast<char>(0x80); // MSB set (invalid)
  24296. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24297. strm.write(frame.data(), frame.size());
  24298. ws::Opcode opcode;
  24299. std::string payload;
  24300. bool fin;
  24301. EXPECT_EQ(
  24302. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24303. ws::impl::FrameRead::Fail);
  24304. }
  24305. // MSB clear - should pass length parsing (will be rejected by max_len,
  24306. // but that's a different check; use a small length to verify)
  24307. {
  24308. detail::BufferStream strm;
  24309. std::string frame;
  24310. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24311. frame += static_cast<char>(127); // 64-bit extended length
  24312. frame += std::string(7, '\0'); // high bytes = 0
  24313. frame += static_cast<char>(0x03); // length = 3
  24314. frame += "abc";
  24315. strm.write(frame.data(), frame.size());
  24316. ws::Opcode opcode;
  24317. std::string payload;
  24318. bool fin;
  24319. EXPECT_EQ(
  24320. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24321. ws::impl::FrameRead::Ok);
  24322. EXPECT_EQ(ws::Opcode::Text, opcode);
  24323. EXPECT_EQ("abc", payload);
  24324. }
  24325. }
  24326. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24327. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24328. // Valid UTF-8
  24329. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24330. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24331. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24332. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24333. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24334. // Invalid UTF-8
  24335. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24336. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24337. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24338. EXPECT_FALSE(
  24339. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24340. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24341. }
  24342. TEST(WebSocketTest, ConnectAndDisconnect) {
  24343. Server svr;
  24344. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24345. std::string msg;
  24346. while (ws.read(msg)) {}
  24347. });
  24348. auto port = svr.bind_to_any_port(HOST);
  24349. std::thread t([&]() { svr.listen_after_bind(); });
  24350. svr.wait_until_ready();
  24351. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24352. auto res = client.connect();
  24353. ASSERT_TRUE(res);
  24354. EXPECT_EQ(Error::Success, res.error());
  24355. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24356. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24357. EXPECT_TRUE(client.is_open());
  24358. client.close();
  24359. EXPECT_FALSE(client.is_open());
  24360. svr.stop();
  24361. t.join();
  24362. }
  24363. TEST(WebSocketTest, ValidURL) {
  24364. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24365. EXPECT_TRUE(ws1.is_valid());
  24366. ws::WebSocketClient ws2("ws://example.com/path");
  24367. EXPECT_TRUE(ws2.is_valid());
  24368. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24369. EXPECT_TRUE(ws3.is_valid());
  24370. #ifdef CPPHTTPLIB_SSL_ENABLED
  24371. ws::WebSocketClient wss1("wss://example.com/path");
  24372. EXPECT_TRUE(wss1.is_valid());
  24373. ws::WebSocketClient wss2("wss://example.com:443/path");
  24374. EXPECT_TRUE(wss2.is_valid());
  24375. #endif
  24376. }
  24377. TEST(WebSocketTest, InvalidURL) {
  24378. // No scheme
  24379. ws::WebSocketClient ws1("localhost:8080/path");
  24380. EXPECT_FALSE(ws1.is_valid());
  24381. // No path
  24382. ws::WebSocketClient ws2("ws://localhost:8080");
  24383. EXPECT_FALSE(ws2.is_valid());
  24384. // Empty string
  24385. ws::WebSocketClient ws3("");
  24386. EXPECT_FALSE(ws3.is_valid());
  24387. // Missing host
  24388. ws::WebSocketClient ws4("ws://:8080/path");
  24389. EXPECT_FALSE(ws4.is_valid());
  24390. // Port number overflow — should not crash
  24391. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24392. EXPECT_FALSE(ws5.is_valid());
  24393. // Port out of range
  24394. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24395. EXPECT_FALSE(ws6.is_valid());
  24396. }
  24397. TEST(WebSocketTest, UnsupportedScheme) {
  24398. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24399. ws::WebSocketClient ws1("http://localhost:8080/path");
  24400. EXPECT_FALSE(ws1.is_valid());
  24401. ws::WebSocketClient ws2("https://localhost:8080/path");
  24402. EXPECT_FALSE(ws2.is_valid());
  24403. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24404. EXPECT_FALSE(ws3.is_valid());
  24405. #else
  24406. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24407. std::invalid_argument);
  24408. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24409. std::invalid_argument);
  24410. #endif
  24411. }
  24412. TEST(WebSocketTest, ConnectWhenInvalid) {
  24413. ws::WebSocketClient ws("not a valid url");
  24414. EXPECT_FALSE(ws.is_valid());
  24415. auto res = ws.connect();
  24416. EXPECT_FALSE(res);
  24417. EXPECT_EQ(Error::Connection, res.error());
  24418. EXPECT_EQ(-1, res.status());
  24419. }
  24420. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24421. // Grab a port that is free, then close it again so nothing listens there
  24422. Server svr;
  24423. auto port = svr.bind_to_any_port(HOST);
  24424. svr.stop();
  24425. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24426. auto res = client.connect();
  24427. ASSERT_FALSE(res);
  24428. EXPECT_EQ(Error::Connection, res.error());
  24429. EXPECT_EQ(-1, res.status());
  24430. }
  24431. TEST(WebSocketTest, DefaultPort) {
  24432. ws::WebSocketClient ws1("ws://example.com/path");
  24433. EXPECT_TRUE(ws1.is_valid());
  24434. // ws:// defaults to port 80 (verified by successful parse)
  24435. #ifdef CPPHTTPLIB_SSL_ENABLED
  24436. ws::WebSocketClient ws2("wss://example.com/path");
  24437. EXPECT_TRUE(ws2.is_valid());
  24438. // wss:// defaults to port 443 (verified by successful parse)
  24439. #endif
  24440. }
  24441. TEST(WebSocketTest, IPv6LiteralAddress) {
  24442. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24443. EXPECT_TRUE(ws1.is_valid());
  24444. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24445. EXPECT_TRUE(ws2.is_valid());
  24446. }
  24447. TEST(WebSocketTest, ComplexPath) {
  24448. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24449. EXPECT_TRUE(ws1.is_valid());
  24450. ws::WebSocketClient ws2("ws://localhost:8080/");
  24451. EXPECT_TRUE(ws2.is_valid());
  24452. }
  24453. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24454. Server svr;
  24455. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24456. std::string msg;
  24457. while (ws.read(msg)) {}
  24458. });
  24459. auto port = svr.bind_to_any_port(HOST);
  24460. std::thread t([&]() { svr.listen_after_bind(); });
  24461. svr.wait_until_ready();
  24462. auto another_host = "example.com";
  24463. auto wrong_ip = "192.0.2.1";
  24464. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24465. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24466. ASSERT_TRUE(client.connect());
  24467. EXPECT_TRUE(client.is_open());
  24468. client.close();
  24469. svr.stop();
  24470. t.join();
  24471. }
  24472. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24473. Server svr;
  24474. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24475. std::string msg;
  24476. while (ws.read(msg)) {}
  24477. });
  24478. auto port = svr.bind_to_any_port(HOST);
  24479. std::thread t([&]() { svr.listen_after_bind(); });
  24480. svr.wait_until_ready();
  24481. auto wrong_ip = "192.0.2.1";
  24482. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24483. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24484. client.set_connection_timeout(1);
  24485. client.set_read_timeout(1);
  24486. client.set_write_timeout(1);
  24487. EXPECT_FALSE(client.connect());
  24488. EXPECT_FALSE(client.is_open());
  24489. svr.stop();
  24490. t.join();
  24491. }
  24492. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24493. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24494. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24495. // (RFC 6761) is only a map key and the Host header value.
  24496. auto host = "target.invalid";
  24497. Server svr;
  24498. std::string received_host;
  24499. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24500. received_host = req.get_header_value("Host");
  24501. std::string msg;
  24502. while (ws.read(msg)) {}
  24503. });
  24504. auto port = svr.bind_to_any_port(HOST);
  24505. std::thread t([&]() { svr.listen_after_bind(); });
  24506. // ASSERT_* below returns from the test body, which would leave t joinable
  24507. // and make ~thread call std::terminate.
  24508. auto se = detail::scope_exit([&] {
  24509. svr.stop();
  24510. if (t.joinable()) { t.join(); }
  24511. });
  24512. svr.wait_until_ready();
  24513. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24514. std::to_string(port) + "/ws");
  24515. client.set_direct_hostname_addr_map({{host, HOST}});
  24516. ASSERT_TRUE(client.connect());
  24517. EXPECT_TRUE(client.is_open());
  24518. client.close();
  24519. svr.stop();
  24520. t.join();
  24521. // The mapping only redirects the connection; the identity stays host_.
  24522. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24523. }
  24524. class WebSocketIntegrationTest : public ::testing::Test {
  24525. protected:
  24526. void SetUp() override {
  24527. server_ = httplib::detail::make_unique<Server>();
  24528. setup_server();
  24529. start_server();
  24530. }
  24531. void TearDown() override {
  24532. server_->stop();
  24533. if (server_thread_.joinable()) { server_thread_.join(); }
  24534. }
  24535. void setup_server() {
  24536. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24537. std::string msg;
  24538. ws::ReadResult ret;
  24539. while ((ret = ws.read(msg))) {
  24540. if (ret == ws::Binary) {
  24541. ws.send(msg.data(), msg.size());
  24542. } else {
  24543. ws.send(msg);
  24544. }
  24545. }
  24546. });
  24547. server_->WebSocket("/ws-echo-string",
  24548. [](const Request &, ws::WebSocket &ws) {
  24549. std::string msg;
  24550. while (ws.read(msg)) {
  24551. ws.send("echo: " + msg);
  24552. }
  24553. });
  24554. server_->WebSocket(
  24555. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24556. // Echo back request metadata
  24557. ws.send("path:" + req.path);
  24558. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24559. std::string msg;
  24560. while (ws.read(msg)) {}
  24561. });
  24562. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24563. std::string msg;
  24564. ws.read(msg); // wait for a message
  24565. ws.close();
  24566. });
  24567. server_->WebSocket("/ws-close-status",
  24568. [](const Request &, ws::WebSocket &ws) {
  24569. std::string msg;
  24570. ws.read(msg); // wait for a message
  24571. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24572. });
  24573. server_->WebSocket(
  24574. "/ws-subprotocol",
  24575. [](const Request &, ws::WebSocket &ws) {
  24576. std::string msg;
  24577. while (ws.read(msg)) {
  24578. ws.send(msg);
  24579. }
  24580. },
  24581. [](const std::vector<std::string> &protocols) -> std::string {
  24582. for (const auto &p : protocols) {
  24583. if (p == "graphql-ws") { return p; }
  24584. }
  24585. return "";
  24586. });
  24587. server_->WebSocket(
  24588. "/ws-subprotocol-unoffered",
  24589. [](const Request &, ws::WebSocket &ws) {
  24590. std::string msg;
  24591. while (ws.read(msg)) {
  24592. ws.send(msg);
  24593. }
  24594. },
  24595. [](const std::vector<std::string> &) -> std::string {
  24596. return "admin";
  24597. });
  24598. }
  24599. void start_server() {
  24600. port_ = server_->bind_to_any_port(HOST);
  24601. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24602. server_->wait_until_ready();
  24603. }
  24604. std::unique_ptr<Server> server_;
  24605. std::thread server_thread_;
  24606. int port_ = 0;
  24607. };
  24608. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24609. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24610. "/ws-echo");
  24611. ASSERT_TRUE(client.connect());
  24612. ASSERT_TRUE(client.is_open());
  24613. ASSERT_TRUE(client.send("Hello WebSocket"));
  24614. std::string msg;
  24615. EXPECT_EQ(ws::Text, client.read(msg));
  24616. EXPECT_EQ("Hello WebSocket", msg);
  24617. client.close();
  24618. }
  24619. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24620. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24621. "/ws-echo");
  24622. ASSERT_TRUE(client.connect());
  24623. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24624. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24625. std::string msg;
  24626. EXPECT_EQ(ws::Binary, client.read(msg));
  24627. EXPECT_EQ(binary_data, msg);
  24628. client.close();
  24629. }
  24630. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24631. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24632. "/ws-echo");
  24633. ASSERT_TRUE(client.connect());
  24634. for (int i = 0; i < 10; i++) {
  24635. auto text = "message " + std::to_string(i);
  24636. ASSERT_TRUE(client.send(text));
  24637. std::string msg;
  24638. ASSERT_TRUE(client.read(msg));
  24639. EXPECT_EQ(text, msg);
  24640. }
  24641. client.close();
  24642. }
  24643. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24644. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24645. "/ws-close");
  24646. ASSERT_TRUE(client.connect());
  24647. // Send a message to trigger the server to close
  24648. ASSERT_TRUE(client.send("trigger close"));
  24649. // The server will close, so read should return false
  24650. std::string msg;
  24651. EXPECT_FALSE(client.read(msg));
  24652. EXPECT_FALSE(client.is_open());
  24653. }
  24654. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24655. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24656. "/ws-echo");
  24657. ASSERT_TRUE(client.connect());
  24658. // 128KB message
  24659. std::string large_data(128 * 1024, 'X');
  24660. ASSERT_TRUE(client.send(large_data));
  24661. std::string msg;
  24662. ASSERT_TRUE(client.read(msg));
  24663. EXPECT_EQ(large_data, msg);
  24664. client.close();
  24665. }
  24666. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24667. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24668. "/ws-echo");
  24669. ASSERT_TRUE(client.connect());
  24670. const int num_threads = 4;
  24671. std::vector<std::thread> threads;
  24672. std::atomic<int> send_count{0};
  24673. for (int t = 0; t < num_threads; t++) {
  24674. threads.emplace_back([&client, &send_count, t]() {
  24675. for (int i = 0; i < 5; i++) {
  24676. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24677. if (client.send(text)) { send_count++; }
  24678. }
  24679. });
  24680. }
  24681. for (auto &th : threads) {
  24682. th.join();
  24683. }
  24684. int received = 0;
  24685. std::string msg;
  24686. while (received < send_count.load()) {
  24687. if (!client.read(msg)) { break; }
  24688. received++;
  24689. }
  24690. EXPECT_EQ(send_count.load(), received);
  24691. client.close();
  24692. }
  24693. TEST_F(WebSocketIntegrationTest, ReadString) {
  24694. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24695. "/ws-echo-string");
  24696. ASSERT_TRUE(client.connect());
  24697. ASSERT_TRUE(client.send("hello"));
  24698. std::string msg;
  24699. ASSERT_TRUE(client.read(msg));
  24700. EXPECT_EQ("echo: hello", msg);
  24701. ASSERT_TRUE(client.send("world"));
  24702. ASSERT_TRUE(client.read(msg));
  24703. EXPECT_EQ("echo: world", msg);
  24704. client.close();
  24705. }
  24706. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24707. Headers headers = {{"X-Test-Header", "test-value"}};
  24708. ws::WebSocketClient client(
  24709. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24710. ASSERT_TRUE(client.connect());
  24711. std::string msg;
  24712. ASSERT_TRUE(client.read(msg));
  24713. EXPECT_EQ("path:/ws-request-info", msg);
  24714. ASSERT_TRUE(client.read(msg));
  24715. EXPECT_EQ("header:test-value", msg);
  24716. client.close();
  24717. }
  24718. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24719. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24720. "/ws-echo");
  24721. client.set_read_timeout(1, 0); // 1 second
  24722. ASSERT_TRUE(client.connect());
  24723. // Don't send anything — server echo handler waits for a message, so read()
  24724. // should time out. The connection survives it: nothing was consumed.
  24725. std::string msg;
  24726. EXPECT_EQ(client.read(msg), ws::Timeout);
  24727. EXPECT_TRUE(client.is_open());
  24728. // And it is still usable afterwards.
  24729. EXPECT_TRUE(client.send("after timeout"));
  24730. EXPECT_EQ(client.read(msg), ws::Text);
  24731. EXPECT_EQ(msg, "after timeout");
  24732. }
  24733. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24734. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24735. "/ws-echo");
  24736. client.set_read_timeout(1, 0);
  24737. ASSERT_TRUE(client.connect());
  24738. ASSERT_TRUE(client.send("first"));
  24739. std::string msg;
  24740. ASSERT_EQ(client.read(msg), ws::Text);
  24741. ASSERT_EQ(msg, "first");
  24742. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24743. // not be used with a read timeout: it would reprocess the previous message.
  24744. EXPECT_EQ(client.read(msg), ws::Timeout);
  24745. EXPECT_EQ(msg, "first");
  24746. }
  24747. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24748. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24749. "/ws-echo");
  24750. ASSERT_TRUE(client.connect());
  24751. // Setting it once the connection is open reaches the live stream, not just
  24752. // the seed for the next connect().
  24753. client.set_read_timeout(1, 0);
  24754. std::string msg;
  24755. EXPECT_EQ(client.read(msg), ws::Timeout);
  24756. EXPECT_TRUE(client.is_open());
  24757. }
  24758. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  24759. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24760. "/ws-echo");
  24761. client.set_read_timeout(5, 0);
  24762. ASSERT_TRUE(client.connect());
  24763. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24764. // The server should reject it and close the connection.
  24765. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  24766. client.send(oversized);
  24767. // The server's read() should have failed due to payload limit,
  24768. // so our read() should return false (connection closed).
  24769. std::string msg;
  24770. EXPECT_FALSE(client.read(msg));
  24771. }
  24772. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  24773. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24774. "/ws-echo");
  24775. client.set_read_timeout(10, 0);
  24776. ASSERT_TRUE(client.connect());
  24777. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  24778. // This should succeed.
  24779. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  24780. ASSERT_TRUE(client.send(at_limit));
  24781. std::string msg;
  24782. ASSERT_TRUE(client.read(msg));
  24783. EXPECT_EQ(at_limit.size(), msg.size());
  24784. client.close();
  24785. }
  24786. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24787. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24788. "/nonexistent");
  24789. auto res = client.connect();
  24790. EXPECT_FALSE(res);
  24791. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24792. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24793. EXPECT_FALSE(client.is_open());
  24794. }
  24795. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24796. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24797. "/ws-echo");
  24798. ASSERT_TRUE(client.connect());
  24799. ASSERT_TRUE(client.send(""));
  24800. std::string msg;
  24801. EXPECT_EQ(ws::Text, client.read(msg));
  24802. EXPECT_EQ("", msg);
  24803. client.close();
  24804. }
  24805. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24806. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24807. "/ws-echo");
  24808. // First connection
  24809. ASSERT_TRUE(client.connect());
  24810. ASSERT_TRUE(client.send("first"));
  24811. std::string msg;
  24812. ASSERT_TRUE(client.read(msg));
  24813. EXPECT_EQ("first", msg);
  24814. client.close();
  24815. EXPECT_FALSE(client.is_open());
  24816. // Reconnect using the same client object
  24817. ASSERT_TRUE(client.connect());
  24818. ASSERT_TRUE(client.is_open());
  24819. ASSERT_TRUE(client.send("second"));
  24820. ASSERT_TRUE(client.read(msg));
  24821. EXPECT_EQ("second", msg);
  24822. client.close();
  24823. }
  24824. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24825. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24826. "/ws-close-status");
  24827. ASSERT_TRUE(client.connect());
  24828. // Trigger the server to close with GoingAway status
  24829. ASSERT_TRUE(client.send("trigger"));
  24830. // read() should return false after receiving the close frame
  24831. std::string msg;
  24832. EXPECT_FALSE(client.read(msg));
  24833. EXPECT_FALSE(client.is_open());
  24834. }
  24835. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24836. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24837. "/ws-echo");
  24838. ASSERT_TRUE(client.connect());
  24839. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24840. EXPECT_FALSE(client.is_open());
  24841. }
  24842. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24843. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24844. ws::WebSocketClient client(
  24845. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24846. ASSERT_TRUE(client.connect());
  24847. // Server should have selected graphql-ws
  24848. EXPECT_EQ("graphql-ws", client.subprotocol());
  24849. client.close();
  24850. }
  24851. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24852. Headers headers;
  24853. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24854. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24855. ws::WebSocketClient client(
  24856. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24857. ASSERT_TRUE(client.connect());
  24858. // The offer on the second field line counts too, so graphql-ws is selected
  24859. EXPECT_EQ("graphql-ws", client.subprotocol());
  24860. client.close();
  24861. }
  24862. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24863. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24864. ws::WebSocketClient client(
  24865. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24866. ASSERT_TRUE(client.connect());
  24867. // Server should not have selected any subprotocol
  24868. EXPECT_TRUE(client.subprotocol().empty());
  24869. client.close();
  24870. }
  24871. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24872. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24873. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24874. "/ws-subprotocol-unoffered",
  24875. headers);
  24876. ASSERT_TRUE(client.connect());
  24877. EXPECT_TRUE(client.subprotocol().empty());
  24878. client.close();
  24879. }
  24880. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24881. // Connect without requesting any subprotocol
  24882. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24883. "/ws-subprotocol");
  24884. ASSERT_TRUE(client.connect());
  24885. EXPECT_TRUE(client.subprotocol().empty());
  24886. client.close();
  24887. }
  24888. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24889. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24890. "/ws-echo");
  24891. client.set_tcp_nodelay(true);
  24892. client.set_connection_timeout(3, 0);
  24893. bool socket_options_called = false;
  24894. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24895. ASSERT_TRUE(client.connect());
  24896. ASSERT_TRUE(client.is_open());
  24897. EXPECT_TRUE(socket_options_called);
  24898. ASSERT_TRUE(client.send("hello"));
  24899. std::string msg;
  24900. auto result = client.read(msg);
  24901. EXPECT_EQ(result, ws::ReadResult::Text);
  24902. EXPECT_EQ(msg, "hello");
  24903. client.close();
  24904. }
  24905. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24906. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24907. "/ws-echo");
  24908. client.set_connection_timeout(std::chrono::seconds(3));
  24909. client.set_write_timeout(std::chrono::seconds(3));
  24910. // A sub-second remainder exercises the seconds/microseconds split.
  24911. client.set_read_timeout(std::chrono::milliseconds(1500));
  24912. ASSERT_TRUE(client.connect());
  24913. auto start = std::chrono::steady_clock::now();
  24914. std::string msg;
  24915. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24916. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24917. std::chrono::steady_clock::now() - start)
  24918. .count();
  24919. // Above 1s so that dropping the microseconds half of the split fails here.
  24920. // Ignoring the setter altogether would not reach this line at all: a client
  24921. // waits forever by default.
  24922. EXPECT_GE(elapsed, 1400);
  24923. EXPECT_LT(elapsed, 30000);
  24924. }
  24925. #ifndef _WIN32
  24926. // A send() that times out after part of the data went out returns the count
  24927. // written so far. Every byte of the frame must still be sent, or the peer reads
  24928. // the next frame's header and payload as the rest of this one.
  24929. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24930. signal(SIGPIPE, SIG_IGN);
  24931. const std::string large(4 * 1024 * 1024, 'A');
  24932. std::atomic<bool> large_sent{false};
  24933. std::atomic<bool> small_sent{false};
  24934. Server svr;
  24935. svr.set_write_timeout(0, 500000);
  24936. svr.set_socket_options([](socket_t sock) {
  24937. int size = 8192;
  24938. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24939. reinterpret_cast<const char *>(&size), sizeof(size));
  24940. });
  24941. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24942. large_sent = ws.send(large.data(), large.size());
  24943. small_sent = ws.send("after");
  24944. std::string msg;
  24945. while (ws.read(msg)) {}
  24946. });
  24947. auto port = svr.bind_to_any_port(HOST);
  24948. std::thread t([&]() { svr.listen_after_bind(); });
  24949. auto se = detail::scope_exit([&] {
  24950. svr.stop();
  24951. t.join();
  24952. });
  24953. svr.wait_until_ready();
  24954. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24955. std::to_string(port) + "/ws");
  24956. client.set_read_timeout(5);
  24957. client.set_socket_options([](socket_t sock) {
  24958. int size = 8192;
  24959. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24960. reinterpret_cast<const char *>(&size), sizeof(size));
  24961. });
  24962. ASSERT_TRUE(client.connect());
  24963. // Outlast the server's write timeout, then drain.
  24964. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  24965. std::string msg;
  24966. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  24967. EXPECT_TRUE(msg == large);
  24968. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  24969. EXPECT_EQ("after", msg);
  24970. EXPECT_TRUE(large_sent);
  24971. EXPECT_TRUE(small_sent);
  24972. client.close();
  24973. }
  24974. // A send() that fails partway leaves a frame on the wire whose header announces
  24975. // more than was sent. Nothing may follow it, or the peer reads the next frames
  24976. // as the rest of it and a later payload's bytes as a frame of their own.
  24977. TEST(WebSocketPartialWriteTest, FailedWriteClosesConnection) {
  24978. signal(SIGPIPE, SIG_IGN);
  24979. const std::string large(4 * 1024 * 1024, 'A');
  24980. std::atomic<bool> large_sent{true};
  24981. std::atomic<bool> open_after_failure{true};
  24982. std::atomic<bool> handler_done{false};
  24983. Server svr;
  24984. svr.set_write_timeout(0, 200000);
  24985. svr.set_socket_options([](socket_t sock) {
  24986. int size = 8192;
  24987. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24988. reinterpret_cast<const char *>(&size), sizeof(size));
  24989. });
  24990. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24991. large_sent = ws.send(large.data(), large.size());
  24992. open_after_failure = ws.is_open();
  24993. handler_done = true;
  24994. });
  24995. auto port = svr.bind_to_any_port(HOST);
  24996. std::thread t([&]() { svr.listen_after_bind(); });
  24997. auto se = detail::scope_exit([&] {
  24998. svr.stop();
  24999. t.join();
  25000. });
  25001. svr.wait_until_ready();
  25002. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25003. std::to_string(port) + "/ws");
  25004. client.set_socket_options([](socket_t sock) {
  25005. int size = 8192;
  25006. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25007. reinterpret_cast<const char *>(&size), sizeof(size));
  25008. });
  25009. ASSERT_TRUE(client.connect());
  25010. // Read nothing, so the server's write times out partway through the frame.
  25011. for (int i = 0; i < 100 && !handler_done; i++) {
  25012. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  25013. }
  25014. ASSERT_TRUE(handler_done);
  25015. ASSERT_FALSE(large_sent);
  25016. EXPECT_FALSE(open_after_failure);
  25017. client.close();
  25018. }
  25019. #endif
  25020. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  25021. Server svr;
  25022. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25023. if (!req.has_header("Authorization")) {
  25024. res.status = StatusCode::Unauthorized_401;
  25025. res.set_content("Unauthorized", "text/plain");
  25026. return Server::HandlerResponse::Handled;
  25027. }
  25028. return Server::HandlerResponse::Unhandled;
  25029. });
  25030. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25031. std::string msg;
  25032. while (ws.read(msg)) {
  25033. ws.send(msg);
  25034. }
  25035. });
  25036. auto port = svr.bind_to_any_port("localhost");
  25037. std::thread t([&]() { svr.listen_after_bind(); });
  25038. svr.wait_until_ready();
  25039. // Without Authorization header - should be rejected before upgrade
  25040. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  25041. EXPECT_FALSE(client1.connect());
  25042. // The rejection is framed like any other HTTP response
  25043. {
  25044. Client cli("localhost", port);
  25045. Headers headers = {{"Upgrade", "websocket"},
  25046. {"Connection", "Upgrade"},
  25047. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25048. {"Sec-WebSocket-Version", "13"}};
  25049. auto res = cli.Get("/ws", headers);
  25050. ASSERT_TRUE(res);
  25051. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25052. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25053. EXPECT_EQ("Unauthorized", res->body);
  25054. }
  25055. // With Authorization header - should succeed
  25056. Headers headers = {{"Authorization", "Bearer token123"}};
  25057. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  25058. headers);
  25059. ASSERT_TRUE(client2.connect());
  25060. ASSERT_TRUE(client2.send("hello"));
  25061. std::string msg;
  25062. ASSERT_TRUE(client2.read(msg));
  25063. EXPECT_EQ("hello", msg);
  25064. client2.close();
  25065. svr.stop();
  25066. t.join();
  25067. }
  25068. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  25069. Server svr;
  25070. std::atomic<int> pre_routing_calls{0};
  25071. std::atomic<int> pre_request_calls{0};
  25072. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  25073. pre_routing_calls++;
  25074. if (req.path == "/handled") {
  25075. res.set_content("handled", "text/plain");
  25076. return Server::HandlerResponse::Handled;
  25077. }
  25078. return Server::HandlerResponse::Unhandled;
  25079. });
  25080. svr.set_pre_request_handler([&](const Request &, Response &) {
  25081. pre_request_calls++;
  25082. return Server::HandlerResponse::Unhandled;
  25083. });
  25084. svr.Get("/http", [](const Request &, Response &res) {
  25085. res.set_content("http", "text/plain");
  25086. });
  25087. svr.WebSocket("/ws",
  25088. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25089. auto port = svr.bind_to_any_port("localhost");
  25090. std::thread t([&]() { svr.listen_after_bind(); });
  25091. auto se = detail::scope_exit([&] {
  25092. svr.stop();
  25093. t.join();
  25094. });
  25095. svr.wait_until_ready();
  25096. Headers upgrade = {{"Upgrade", "websocket"},
  25097. {"Connection", "Upgrade"},
  25098. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25099. {"Sec-WebSocket-Version", "13"}};
  25100. auto get = [&](const char *path) {
  25101. pre_routing_calls = 0;
  25102. return Client("localhost", port).Get(path, upgrade);
  25103. };
  25104. // No WebSocket route, but an HTTP one
  25105. auto res = get("/http");
  25106. ASSERT_TRUE(res);
  25107. EXPECT_EQ(StatusCode::OK_200, res->status);
  25108. EXPECT_EQ("http", res->body);
  25109. EXPECT_EQ(1, pre_routing_calls);
  25110. EXPECT_EQ(1, pre_request_calls);
  25111. // No route at all
  25112. res = get("/none");
  25113. ASSERT_TRUE(res);
  25114. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25115. EXPECT_EQ(1, pre_routing_calls);
  25116. // Answered by the pre-routing handler
  25117. res = get("/handled");
  25118. ASSERT_TRUE(res);
  25119. EXPECT_EQ(StatusCode::OK_200, res->status);
  25120. EXPECT_EQ("handled", res->body);
  25121. EXPECT_EQ(1, pre_routing_calls);
  25122. // A WebSocket route
  25123. pre_routing_calls = 0;
  25124. pre_request_calls = 0;
  25125. {
  25126. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25127. "/ws");
  25128. ASSERT_TRUE(client.connect());
  25129. std::string msg;
  25130. ASSERT_TRUE(client.read(msg));
  25131. EXPECT_EQ("ws", msg);
  25132. client.close();
  25133. }
  25134. EXPECT_EQ(1, pre_routing_calls);
  25135. EXPECT_EQ(1, pre_request_calls);
  25136. }
  25137. // An upgrade request answered by a hook leaves its body unread, so that body
  25138. // must not be served as the next request on the connection.
  25139. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25140. Server svr;
  25141. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25142. if (req.path == "/pre-routing") {
  25143. res.set_content("pre-routing", "text/plain");
  25144. return Server::HandlerResponse::Handled;
  25145. }
  25146. return Server::HandlerResponse::Unhandled;
  25147. });
  25148. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25149. if (req.matched_route == "/pre-request") {
  25150. res.set_content("pre-request", "text/plain");
  25151. return Server::HandlerResponse::Handled;
  25152. }
  25153. return Server::HandlerResponse::Unhandled;
  25154. });
  25155. svr.Get("/smuggled", [](const Request &, Response &res) {
  25156. res.set_content("smuggled", "text/plain");
  25157. });
  25158. svr.WebSocket("/pre-request",
  25159. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25160. auto port = svr.bind_to_any_port(HOST);
  25161. std::thread t([&]() { svr.listen_after_bind(); });
  25162. auto se = detail::scope_exit([&] {
  25163. svr.stop();
  25164. t.join();
  25165. });
  25166. svr.wait_until_ready();
  25167. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25168. for (auto path : {"/pre-routing", "/pre-request"}) {
  25169. std::string req = std::string("GET ") + path +
  25170. " HTTP/1.1\r\n"
  25171. "Host: localhost\r\n"
  25172. "Upgrade: websocket\r\n"
  25173. "Connection: Upgrade\r\n"
  25174. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25175. "Sec-WebSocket-Version: 13\r\n"
  25176. "Content-Length: " +
  25177. std::to_string(body.size()) + "\r\n\r\n" + body;
  25178. std::string res;
  25179. ASSERT_TRUE(send_request(5, req, &res, port));
  25180. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25181. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25182. // Only one response, and the body was not served as a request
  25183. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25184. }
  25185. }
  25186. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25187. Server svr;
  25188. std::atomic<int> pre_request_calls{0};
  25189. std::atomic<bool> route_matched{false};
  25190. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25191. pre_request_calls++;
  25192. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25193. if (req.get_header_value("Authorization") != "Bearer token123") {
  25194. res.status = StatusCode::Unauthorized_401;
  25195. res.set_content("Unauthorized", "text/plain");
  25196. return Server::HandlerResponse::Handled;
  25197. }
  25198. return Server::HandlerResponse::Unhandled;
  25199. });
  25200. std::atomic<bool> handler_called{false};
  25201. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25202. handler_called = true;
  25203. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25204. });
  25205. auto port = svr.bind_to_any_port("localhost");
  25206. std::thread t([&]() { svr.listen_after_bind(); });
  25207. svr.wait_until_ready();
  25208. // Without Authorization header - should be rejected before upgrade
  25209. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25210. "/ws/1");
  25211. EXPECT_FALSE(client1.connect());
  25212. EXPECT_FALSE(handler_called);
  25213. EXPECT_EQ(1, pre_request_calls);
  25214. EXPECT_TRUE(route_matched);
  25215. // The rejection is an ordinary HTTP response, not a protocol switch
  25216. {
  25217. Client cli("localhost", port);
  25218. Headers headers = {{"Upgrade", "websocket"},
  25219. {"Connection", "Upgrade"},
  25220. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25221. {"Sec-WebSocket-Version", "13"}};
  25222. auto res = cli.Get("/ws/1", headers);
  25223. ASSERT_TRUE(res);
  25224. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25225. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25226. EXPECT_EQ("Unauthorized", res->body);
  25227. }
  25228. EXPECT_FALSE(handler_called);
  25229. // With Authorization header - should succeed
  25230. Headers headers = {{"Authorization", "Bearer token123"}};
  25231. ws::WebSocketClient client2(
  25232. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25233. ASSERT_TRUE(client2.connect());
  25234. std::string msg;
  25235. ASSERT_TRUE(client2.read(msg));
  25236. EXPECT_EQ("/ws/:id 2", msg);
  25237. EXPECT_TRUE(handler_called);
  25238. client2.close();
  25239. svr.stop();
  25240. t.join();
  25241. }
  25242. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25243. static Headers websocket_upgrade_headers() {
  25244. return {{"Upgrade", "websocket"},
  25245. {"Connection", "Upgrade"},
  25246. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25247. {"Sec-WebSocket-Version", "13"},
  25248. {"Sec-WebSocket-Protocol", "chat"}};
  25249. }
  25250. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25251. Server svr;
  25252. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25253. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25254. return Server::HandlerResponse::Unhandled;
  25255. });
  25256. svr.set_pre_request_handler([](const Request &req, Response &) {
  25257. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25258. return Server::HandlerResponse::Unhandled;
  25259. });
  25260. svr.set_exception_handler(
  25261. [](const Request &, Response &res, std::exception_ptr ep) {
  25262. try {
  25263. std::rethrow_exception(ep);
  25264. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25265. });
  25266. auto handler = [](const Request &, ws::WebSocket &) {};
  25267. svr.WebSocket("/pre-routing", handler);
  25268. svr.WebSocket("/pre-request", handler);
  25269. svr.WebSocket("/sub-protocol", handler,
  25270. [](const std::vector<std::string> &) -> std::string {
  25271. throw std::runtime_error("/sub-protocol");
  25272. });
  25273. auto port = svr.bind_to_any_port(HOST);
  25274. ASSERT_GT(port, 0);
  25275. thread t = thread([&] { svr.listen_after_bind(); });
  25276. auto se = detail::scope_exit([&] {
  25277. svr.stop();
  25278. t.join();
  25279. ASSERT_FALSE(svr.is_running());
  25280. });
  25281. svr.wait_until_ready();
  25282. Client cli(HOST, port);
  25283. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25284. auto res = cli.Get(path, websocket_upgrade_headers());
  25285. if (!res) {
  25286. ADD_FAILURE() << path << ": " << to_string(res.error());
  25287. continue;
  25288. }
  25289. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25290. EXPECT_EQ(path, res->body);
  25291. }
  25292. }
  25293. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25294. Server svr;
  25295. svr.set_pre_routing_handler(
  25296. [](const Request &, Response &) -> Server::HandlerResponse {
  25297. throw std::runtime_error("pre-routing");
  25298. });
  25299. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25300. auto port = svr.bind_to_any_port(HOST);
  25301. ASSERT_GT(port, 0);
  25302. thread t = thread([&] { svr.listen_after_bind(); });
  25303. auto se = detail::scope_exit([&] {
  25304. svr.stop();
  25305. t.join();
  25306. ASSERT_FALSE(svr.is_running());
  25307. });
  25308. svr.wait_until_ready();
  25309. Client cli(HOST, port);
  25310. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25311. ASSERT_TRUE(res) << to_string(res.error());
  25312. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25313. }
  25314. #endif
  25315. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25316. Server svr;
  25317. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25318. // A read timeout is how a handler gets control back. Without it, a handler
  25319. // parked in read() can never write on the connection it is reading.
  25320. ws.set_read_timeout(std::chrono::milliseconds(100));
  25321. std::string msg;
  25322. while (ws.is_open()) {
  25323. auto r = ws.read(msg);
  25324. if (r == httplib::ws::Timeout) {
  25325. ws.send("tick");
  25326. continue;
  25327. }
  25328. if (r == httplib::ws::Fail) { break; }
  25329. ws.send(msg);
  25330. }
  25331. });
  25332. auto port = svr.bind_to_any_port("localhost");
  25333. std::thread t([&]() { svr.listen_after_bind(); });
  25334. svr.wait_until_ready();
  25335. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25336. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25337. ASSERT_TRUE(client.connect());
  25338. // The client sends nothing, so anything it receives came out of the
  25339. // handler's timeout path.
  25340. std::string msg;
  25341. ASSERT_EQ(client.read(msg), ws::Text);
  25342. EXPECT_EQ("tick", msg);
  25343. client.close();
  25344. svr.stop();
  25345. t.join();
  25346. }
  25347. // Stream::read may return fewer bytes than asked for. This is that contract at
  25348. // its worst -- one byte per call -- which is what a frame header straddling a
  25349. // read buffer's boundary looks like to the frame parser.
  25350. class WsByteAtATimeStream : public Stream {
  25351. public:
  25352. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25353. bool is_readable() const override { return true; }
  25354. bool wait_readable() const override { return true; }
  25355. bool wait_writable() const override { return true; }
  25356. ssize_t read(char *ptr, size_t size) override {
  25357. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25358. *ptr = data_[pos_++];
  25359. return 1;
  25360. }
  25361. ssize_t write(const char *, size_t size) override {
  25362. return static_cast<ssize_t>(size);
  25363. }
  25364. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25365. ip = "127.0.0.1";
  25366. port = 0;
  25367. }
  25368. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25369. ip = "127.0.0.1";
  25370. port = 0;
  25371. }
  25372. socket_t socket() const override { return INVALID_SOCKET; }
  25373. time_t duration() const override { return 0; }
  25374. private:
  25375. std::string data_;
  25376. size_t pos_ = 0;
  25377. };
  25378. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25379. // The payload uses the 16-bit extended length, so the header, the length
  25380. // and the mask key are all multi-byte fields here. Each used to be read
  25381. // with a single read() call, which fails as soon as one is split. The
  25382. // payload is also a little over one read chunk, so it is read in two.
  25383. std::string body;
  25384. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25385. body += static_cast<char>(i % 251);
  25386. }
  25387. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25388. std::string frame;
  25389. frame += static_cast<char>(0x81); // FIN + Text
  25390. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25391. frame += static_cast<char>(body.size() >> 8);
  25392. frame += static_cast<char>(body.size() & 0xff);
  25393. for (size_t i = 0; i < 4; i++) {
  25394. frame += static_cast<char>(mask[i]);
  25395. }
  25396. for (size_t i = 0; i < body.size(); i++) {
  25397. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25398. }
  25399. WsByteAtATimeStream strm(frame);
  25400. ws::Opcode opcode;
  25401. std::string payload;
  25402. bool fin = false;
  25403. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25404. /*expect_masked=*/true, body.size()),
  25405. ws::impl::FrameRead::Ok);
  25406. EXPECT_TRUE(fin);
  25407. EXPECT_EQ(opcode, ws::Opcode::Text);
  25408. EXPECT_EQ(payload, body);
  25409. }
  25410. // Keeps what is written, counting the writes, and reads it back.
  25411. class WsWriteCountingStream : public Stream {
  25412. public:
  25413. bool is_readable() const override { return true; }
  25414. bool wait_readable() const override { return true; }
  25415. bool wait_writable() const override { return true; }
  25416. ssize_t read(char *ptr, size_t size) override {
  25417. auto n = (std::min)(size, data_.size() - pos_);
  25418. if (n == 0) { return 0; }
  25419. memcpy(ptr, data_.data() + pos_, n);
  25420. pos_ += n;
  25421. return static_cast<ssize_t>(n);
  25422. }
  25423. ssize_t write(const char *ptr, size_t size) override {
  25424. writes++;
  25425. data_.append(ptr, size);
  25426. return static_cast<ssize_t>(size);
  25427. }
  25428. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25429. ip = "127.0.0.1";
  25430. port = 0;
  25431. }
  25432. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25433. ip = "127.0.0.1";
  25434. port = 0;
  25435. }
  25436. socket_t socket() const override { return INVALID_SOCKET; }
  25437. time_t duration() const override { return 0; }
  25438. int writes = 0;
  25439. private:
  25440. std::string data_;
  25441. size_t pos_ = 0;
  25442. };
  25443. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25444. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25445. // masked and not, reads back as written; a payload over one chunk follows
  25446. // its first in more writes.
  25447. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25448. for (auto mask : {false, true}) {
  25449. std::string body(len, '\0');
  25450. for (size_t i = 0; i < len; i++) {
  25451. body[i] = static_cast<char>(i % 251);
  25452. }
  25453. WsWriteCountingStream strm;
  25454. ASSERT_TRUE(detail::write_websocket_frame(
  25455. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25456. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25457. ws::Opcode opcode;
  25458. std::string payload;
  25459. bool fin = false;
  25460. ASSERT_EQ(
  25461. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25462. ws::impl::FrameRead::Ok)
  25463. << len << " " << mask;
  25464. EXPECT_TRUE(fin);
  25465. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25466. EXPECT_EQ(body, payload) << len << " " << mask;
  25467. }
  25468. }
  25469. }
  25470. // Hands out its pieces one read at a time, timing out between each two.
  25471. class WsTimeoutBetweenPiecesStream : public Stream {
  25472. public:
  25473. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25474. : pieces_(std::move(pieces)) {}
  25475. bool is_readable() const override { return true; }
  25476. bool wait_readable() const override { return true; }
  25477. bool wait_writable() const override { return true; }
  25478. ssize_t read(char *ptr, size_t size) override {
  25479. if (time_out_) {
  25480. time_out_ = false;
  25481. error_ = Error::Timeout;
  25482. return -1;
  25483. }
  25484. if (i_ >= pieces_.size()) {
  25485. error_ = Error::ConnectionClosed;
  25486. return 0;
  25487. }
  25488. auto &piece = pieces_[i_];
  25489. auto n = (std::min)(size, piece.size() - at_);
  25490. memcpy(ptr, piece.data() + at_, n);
  25491. at_ += n;
  25492. if (at_ == piece.size()) {
  25493. i_++;
  25494. at_ = 0;
  25495. time_out_ = true;
  25496. }
  25497. return static_cast<ssize_t>(n);
  25498. }
  25499. ssize_t write(const char *, size_t size) override {
  25500. return static_cast<ssize_t>(size);
  25501. }
  25502. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25503. ip = "127.0.0.1";
  25504. port = 0;
  25505. }
  25506. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25507. ip = "127.0.0.1";
  25508. port = 0;
  25509. }
  25510. socket_t socket() const override { return INVALID_SOCKET; }
  25511. time_t duration() const override { return 0; }
  25512. private:
  25513. std::vector<std::string> pieces_;
  25514. size_t i_ = 0;
  25515. size_t at_ = 0;
  25516. bool time_out_ = false;
  25517. };
  25518. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25519. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25520. std::string frame = "\x81\x85";
  25521. frame.append(4, '\0');
  25522. frame += "Hello";
  25523. // The header's first byte, then its second with half the mask key, then
  25524. // the rest
  25525. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25526. frame.substr(4)};
  25527. WsTimeoutBetweenPiecesStream strm(pieces);
  25528. ws::impl::FrameReader reader;
  25529. ws::Opcode opcode;
  25530. std::string payload;
  25531. bool fin = false;
  25532. for (int i = 0; i < 2; i++) {
  25533. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25534. reader.read(strm, opcode, payload, fin, true, 0));
  25535. EXPECT_TRUE(reader.begun());
  25536. }
  25537. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25538. reader.read(strm, opcode, payload, fin, true, 0));
  25539. EXPECT_FALSE(reader.begun());
  25540. EXPECT_TRUE(fin);
  25541. EXPECT_EQ(ws::Opcode::Text, opcode);
  25542. EXPECT_EQ("Hello", payload);
  25543. // Read in one go, the frame cannot be gone on with after a timeout
  25544. WsTimeoutBetweenPiecesStream again(pieces);
  25545. EXPECT_EQ(
  25546. ws::impl::FrameRead::Fail,
  25547. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25548. }
  25549. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25550. std::string body(2000, 'x');
  25551. std::string frame;
  25552. frame += static_cast<char>(0x82); // FIN + Binary
  25553. frame += static_cast<char>(126); // 16-bit length follows
  25554. frame += static_cast<char>(body.size() >> 8);
  25555. frame += static_cast<char>(body.size() & 0xff);
  25556. frame += body;
  25557. detail::BufferStream strm;
  25558. strm.write(frame.data(), frame.size());
  25559. ws::Opcode opcode;
  25560. std::string payload;
  25561. bool fin;
  25562. EXPECT_EQ(
  25563. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25564. ws::impl::FrameRead::Ok);
  25565. EXPECT_EQ(body, payload);
  25566. }
  25567. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25568. // The header announces the largest payload allowed, and only 3 bytes of it
  25569. // ever arrive.
  25570. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25571. std::string frame;
  25572. frame += static_cast<char>(0x82); // FIN + Binary
  25573. frame += static_cast<char>(127); // 64-bit length follows
  25574. for (int shift = 56; shift >= 0; shift -= 8) {
  25575. frame += static_cast<char>((len >> shift) & 0xff);
  25576. }
  25577. frame += "abc";
  25578. detail::BufferStream strm;
  25579. strm.write(frame.data(), frame.size());
  25580. ws::Opcode opcode;
  25581. std::string payload;
  25582. bool fin;
  25583. EXPECT_EQ(
  25584. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25585. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25586. ws::impl::FrameRead::Fail);
  25587. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25588. }
  25589. TEST(WebSocketTest, QueryStringInHandshake) {
  25590. Server svr;
  25591. std::mutex mtx;
  25592. std::string received_target;
  25593. std::string received_token;
  25594. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25595. {
  25596. std::lock_guard<std::mutex> lock(mtx);
  25597. received_target = req.target;
  25598. if (req.has_param("token")) {
  25599. received_token = req.get_param_value("token");
  25600. }
  25601. }
  25602. std::string msg;
  25603. while (ws.read(msg)) {
  25604. ws.send(msg);
  25605. }
  25606. });
  25607. auto port = svr.bind_to_any_port("localhost");
  25608. std::thread t([&]() { svr.listen_after_bind(); });
  25609. svr.wait_until_ready();
  25610. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25611. "/ws?token=ABC&session=123");
  25612. ASSERT_TRUE(client.connect());
  25613. // Round-trip ensures the handler has run and captured the request.
  25614. ASSERT_TRUE(client.send("hello"));
  25615. std::string msg;
  25616. ASSERT_TRUE(client.read(msg));
  25617. EXPECT_EQ("hello", msg);
  25618. client.close();
  25619. {
  25620. std::lock_guard<std::mutex> lock(mtx);
  25621. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25622. EXPECT_EQ("ABC", received_token);
  25623. }
  25624. svr.stop();
  25625. t.join();
  25626. }
  25627. // Run a handshake against a throwaway server and hand the request the server
  25628. // received back to the caller, so tests can assert on the headers the client
  25629. // actually put on the wire.
  25630. static void capture_websocket_handshake_request(
  25631. const Headers &client_headers,
  25632. std::function<void(const Request &, int port)> verify) {
  25633. Server svr;
  25634. std::mutex mtx;
  25635. Request received;
  25636. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25637. {
  25638. std::lock_guard<std::mutex> lock(mtx);
  25639. received = req;
  25640. }
  25641. std::string msg;
  25642. while (ws.read(msg)) {
  25643. ws.send(msg);
  25644. }
  25645. });
  25646. auto port = svr.bind_to_any_port("localhost");
  25647. std::thread t([&]() { svr.listen_after_bind(); });
  25648. auto se = detail::scope_exit([&] {
  25649. svr.stop();
  25650. t.join();
  25651. });
  25652. svr.wait_until_ready();
  25653. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25654. client_headers);
  25655. ASSERT_TRUE(client.connect());
  25656. ASSERT_TRUE(client.send("hello"));
  25657. std::string msg;
  25658. ASSERT_TRUE(client.read(msg));
  25659. client.close();
  25660. {
  25661. std::lock_guard<std::mutex> lock(mtx);
  25662. verify(received, port);
  25663. }
  25664. }
  25665. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25666. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25667. // Non-default port must be present in the Host header. Default ports
  25668. // (80/443) are omitted; that logic is covered by
  25669. // MakeHostAndPortStringTest.
  25670. EXPECT_EQ("localhost:" + std::to_string(port),
  25671. req.get_header_value("Host"));
  25672. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25673. req.get_header_value("User-Agent"));
  25674. EXPECT_FALSE(req.has_header("Accept"));
  25675. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25676. EXPECT_FALSE(req.has_header("Content-Length"));
  25677. });
  25678. }
  25679. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25680. capture_websocket_handshake_request(
  25681. {{"Host", "example.com"},
  25682. {"User-Agent", "custom-agent"},
  25683. {"X-Custom", "value"}},
  25684. [](const Request &req, int) {
  25685. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25686. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25687. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25688. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25689. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25690. });
  25691. }
  25692. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25693. capture_websocket_handshake_request(
  25694. {{"Upgrade", "bogus"},
  25695. {"Connection", "close"},
  25696. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25697. {"Sec-WebSocket-Version", "8"}},
  25698. [](const Request &req, int) {
  25699. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25700. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25701. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25702. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25703. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25704. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25705. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25706. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25707. req.get_header_value("Sec-WebSocket-Key"));
  25708. });
  25709. }
  25710. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25711. // A header the client refuses to send must abort the handshake before any
  25712. // part of it reaches the wire; a lone request line would otherwise sit in
  25713. // the peer's buffer as a truncated request.
  25714. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25715. ASSERT_NE(INVALID_SOCKET, srv);
  25716. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25717. sockaddr_in addr{};
  25718. addr.sin_family = AF_INET;
  25719. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25720. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25721. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25722. ASSERT_EQ(0, ::listen(srv, 1));
  25723. sockaddr_in bound{};
  25724. socklen_t bound_len = sizeof(bound);
  25725. ASSERT_EQ(
  25726. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25727. auto port = ntohs(bound.sin_port);
  25728. ssize_t received = -1;
  25729. std::thread t([&] {
  25730. // Bound every blocking call so a regression fails the test with a bad
  25731. // value instead of hanging the suite.
  25732. fd_set rfds;
  25733. FD_ZERO(&rfds);
  25734. FD_SET(srv, &rfds);
  25735. timeval tv{5, 0};
  25736. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25737. 0) {
  25738. return;
  25739. }
  25740. sockaddr_in cli_addr{};
  25741. socklen_t cli_len = sizeof(cli_addr);
  25742. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25743. if (cli == INVALID_SOCKET) { return; }
  25744. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25745. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25746. char buf[4096];
  25747. received = ::recv(cli, buf, sizeof(buf), 0);
  25748. });
  25749. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25750. // connect() has already shut the socket down by the time it returns false,
  25751. // so the peer sees EOF without waiting for the client to be destroyed.
  25752. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25753. {{"X-Bad", "a\r\nInjected: 1"}});
  25754. EXPECT_FALSE(client.connect());
  25755. t.join();
  25756. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25757. EXPECT_EQ(0, received);
  25758. }
  25759. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25760. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25761. // contains "upgrade" as a substring is a different token and must not
  25762. // start a WebSocket handshake.
  25763. auto make_request = [](const std::vector<std::string> &connection_values) {
  25764. Request req;
  25765. req.method = "GET";
  25766. req.headers.emplace("Upgrade", "websocket");
  25767. for (const auto &value : connection_values) {
  25768. req.headers.emplace("Connection", value);
  25769. }
  25770. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25771. req.headers.emplace("Sec-WebSocket-Version", "13");
  25772. return req;
  25773. };
  25774. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25775. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25776. EXPECT_TRUE(
  25777. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25778. EXPECT_TRUE(
  25779. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25780. EXPECT_TRUE(
  25781. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25782. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25783. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25784. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25785. EXPECT_FALSE(
  25786. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25787. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25788. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25789. }
  25790. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25791. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25792. // asks recipients to match each protocol-name case-insensitively, and RFC
  25793. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25794. // client naming websocket alongside another protocol, or on a second field
  25795. // line, is offering websocket; a value that merely contains "websocket" as a
  25796. // substring is a different protocol name and is not.
  25797. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25798. Request req;
  25799. req.method = "GET";
  25800. for (const auto &value : upgrade_values) {
  25801. req.headers.emplace("Upgrade", value);
  25802. }
  25803. req.headers.emplace("Connection", "Upgrade");
  25804. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25805. req.headers.emplace("Sec-WebSocket-Version", "13");
  25806. return req;
  25807. };
  25808. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25809. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25810. EXPECT_TRUE(
  25811. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25812. EXPECT_TRUE(
  25813. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25814. EXPECT_TRUE(
  25815. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25816. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25817. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25818. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25819. EXPECT_FALSE(
  25820. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25821. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25822. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25823. }
  25824. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25825. Server svr;
  25826. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25827. auto port = svr.bind_to_any_port("localhost");
  25828. std::thread t([&]() { svr.listen_after_bind(); });
  25829. auto se = detail::scope_exit([&] {
  25830. svr.stop();
  25831. t.join();
  25832. });
  25833. svr.wait_until_ready();
  25834. Headers headers = {{"Upgrade", "websocket"},
  25835. {"Connection", "notupgrade"},
  25836. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25837. {"Sec-WebSocket-Version", "13"}};
  25838. Client cli("localhost", port);
  25839. auto res = cli.Get("/ws", headers);
  25840. // The route exists only as a WebSocket route, so a request that fails the
  25841. // handshake check falls through to ordinary routing.
  25842. ASSERT_TRUE(res);
  25843. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25844. }
  25845. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25846. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25847. // Connection value is the only thing left for the client to reject.
  25848. Server svr;
  25849. svr.Get("/ws", [](const Request &req, Response &res) {
  25850. res.status = StatusCode::SwitchingProtocol_101;
  25851. res.set_header("Upgrade", "websocket");
  25852. res.set_header("Connection", "notupgrade");
  25853. res.set_header("Sec-WebSocket-Accept",
  25854. detail::websocket_accept_key(
  25855. req.get_header_value("Sec-WebSocket-Key")));
  25856. });
  25857. auto port = svr.bind_to_any_port("localhost");
  25858. std::thread t([&]() { svr.listen_after_bind(); });
  25859. auto se = detail::scope_exit([&] {
  25860. svr.stop();
  25861. t.join();
  25862. });
  25863. svr.wait_until_ready();
  25864. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25865. auto res = client.connect();
  25866. EXPECT_FALSE(res);
  25867. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25868. EXPECT_FALSE(client.is_open());
  25869. }
  25870. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25871. Server svr;
  25872. svr.Get("/ws", [](const Request &req, Response &res) {
  25873. res.status = StatusCode::SwitchingProtocol_101;
  25874. res.set_header("Upgrade", "websocket");
  25875. res.set_header("Connection", "Upgrade");
  25876. res.set_header("Sec-WebSocket-Accept",
  25877. detail::websocket_accept_key(
  25878. req.get_header_value("Sec-WebSocket-Key")));
  25879. res.set_header("Sec-WebSocket-Protocol", "admin");
  25880. });
  25881. auto port = svr.bind_to_any_port("localhost");
  25882. std::thread t([&]() { svr.listen_after_bind(); });
  25883. auto se = detail::scope_exit([&] {
  25884. svr.stop();
  25885. t.join();
  25886. });
  25887. svr.wait_until_ready();
  25888. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25889. // Server selects a subprotocol the client never offered
  25890. {
  25891. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25892. ws::WebSocketClient client(url, headers);
  25893. auto res = client.connect();
  25894. EXPECT_FALSE(res);
  25895. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25896. EXPECT_FALSE(client.is_open());
  25897. EXPECT_TRUE(client.subprotocol().empty());
  25898. }
  25899. // Client offered none but the server named one anyway
  25900. {
  25901. ws::WebSocketClient client(url);
  25902. auto res = client.connect();
  25903. EXPECT_FALSE(res);
  25904. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25905. EXPECT_FALSE(client.is_open());
  25906. EXPECT_TRUE(client.subprotocol().empty());
  25907. }
  25908. }
  25909. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25910. // The socket path doubles as the URL host, so it must not contain '/'.
  25911. const char *shard = getenv("GTEST_SHARD_INDEX");
  25912. const std::string sock_path =
  25913. shard ? std::string("httplib-ws-") + shard + ".sock"
  25914. : std::string("httplib-ws.sock");
  25915. std::remove(sock_path.c_str());
  25916. Server svr;
  25917. std::mutex mtx;
  25918. std::string received_host;
  25919. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25920. {
  25921. std::lock_guard<std::mutex> lock(mtx);
  25922. received_host = req.get_header_value("Host");
  25923. }
  25924. std::string msg;
  25925. while (ws.read(msg)) {
  25926. ws.send(msg);
  25927. }
  25928. });
  25929. svr.set_address_family(AF_UNIX);
  25930. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25931. auto se = detail::scope_exit([&] {
  25932. svr.stop();
  25933. t.join();
  25934. std::remove(sock_path.c_str());
  25935. });
  25936. svr.wait_until_ready();
  25937. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25938. client.set_address_family(AF_UNIX);
  25939. ASSERT_TRUE(client.connect());
  25940. ASSERT_TRUE(client.send("hello"));
  25941. std::string msg;
  25942. ASSERT_TRUE(client.read(msg));
  25943. client.close();
  25944. {
  25945. std::lock_guard<std::mutex> lock(mtx);
  25946. // There is no host:port for a Unix socket, so the same "localhost"
  25947. // placeholder the HTTP client uses is expected.
  25948. EXPECT_EQ("localhost", received_host);
  25949. }
  25950. }
  25951. // Two threads must never parse WebSocket frames from the same stream.
  25952. // close() used to read the peer's Close reply with its own frame read, so it
  25953. // raced a reader thread that was in the middle of a payload: the payload loop
  25954. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25955. // so bytes taken by close() were replaced with bytes from further along the
  25956. // stream. The message kept its length and silently changed content.
  25957. //
  25958. // The raw peer below sends a frame header plus part of the payload, waits for
  25959. // the handler to call close(), and only then sends the rest. Whichever thread
  25960. // would win the race for those bytes, the message must arrive intact, because
  25961. // close() must not touch the stream while read() owns it.
  25962. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25963. #ifndef _WIN32
  25964. signal(SIGPIPE, SIG_IGN);
  25965. #endif
  25966. const size_t payload_len = 120; // fits the 7-bit length field
  25967. const size_t prefix_len = 8;
  25968. const int attempts = 8;
  25969. std::string expected(payload_len, '\0');
  25970. for (size_t i = 0; i < payload_len; i++) {
  25971. expected[i] = static_cast<char>('a' + i % 26);
  25972. }
  25973. std::atomic<bool> peer_stalled{false};
  25974. std::atomic<bool> handler_done{false};
  25975. std::mutex received_mutex;
  25976. std::vector<std::string> received;
  25977. // Bound every wait, so a regression fails the test instead of hanging the
  25978. // suite.
  25979. auto wait_for = [](const std::atomic<bool> &flag) {
  25980. for (int i = 0; i < 500 && !flag; i++) {
  25981. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  25982. }
  25983. };
  25984. Server svr;
  25985. svr.set_websocket_ping_interval(0);
  25986. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25987. std::thread reader([&]() {
  25988. std::string msg;
  25989. while (ws.read(msg)) {
  25990. std::lock_guard<std::mutex> guard(received_mutex);
  25991. received.push_back(msg);
  25992. }
  25993. });
  25994. // Wait until the peer stalls mid-payload, so the reader thread is parked
  25995. // inside a frame when close() runs.
  25996. wait_for(peer_stalled);
  25997. ws.close();
  25998. reader.join();
  25999. handler_done = true;
  26000. });
  26001. auto port = svr.bind_to_any_port("127.0.0.1");
  26002. std::thread t([&]() { svr.listen_after_bind(); });
  26003. auto se = detail::scope_exit([&] {
  26004. svr.stop();
  26005. t.join();
  26006. });
  26007. svr.wait_until_ready();
  26008. auto send_bytes = [](socket_t s, const std::string &data) {
  26009. #ifdef _WIN32
  26010. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  26011. #else
  26012. auto n = ::send(s, data.data(), data.size(), 0);
  26013. #endif
  26014. return n == static_cast<decltype(n)>(data.size());
  26015. };
  26016. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  26017. // Every length used here fits the 7-bit length field.
  26018. auto masked_header = [](uint8_t first_byte, size_t len) {
  26019. std::string h;
  26020. h += static_cast<char>(first_byte);
  26021. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  26022. h.append(4, '\0'); // mask key
  26023. return h;
  26024. };
  26025. for (int attempt = 0; attempt < attempts; attempt++) {
  26026. peer_stalled = false;
  26027. handler_done = false;
  26028. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26029. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  26030. auto se_sock = detail::scope_exit([&] {
  26031. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  26032. });
  26033. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26034. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  26035. sockaddr_in addr{};
  26036. addr.sin_family = AF_INET;
  26037. addr.sin_port = htons(static_cast<uint16_t>(port));
  26038. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26039. ASSERT_EQ(
  26040. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  26041. << "attempt " << attempt;
  26042. ASSERT_TRUE(send_bytes(sock,
  26043. "GET /ws HTTP/1.1\r\n"
  26044. "Host: 127.0.0.1\r\n"
  26045. "Upgrade: websocket\r\n"
  26046. "Connection: Upgrade\r\n"
  26047. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26048. "Sec-WebSocket-Version: 13\r\n"
  26049. "\r\n"))
  26050. << "attempt " << attempt;
  26051. std::string response;
  26052. while (response.find("\r\n\r\n") == std::string::npos) {
  26053. char buf[512];
  26054. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  26055. if (n <= 0) { break; }
  26056. response.append(buf, static_cast<size_t>(n));
  26057. }
  26058. ASSERT_NE(std::string::npos, response.find(" 101 "))
  26059. << "attempt " << attempt;
  26060. // Send the header of a Binary message but only the first prefix_len bytes
  26061. // of its payload, leaving the reader thread stalled inside the payload.
  26062. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  26063. expected.substr(0, prefix_len)))
  26064. << "attempt " << attempt;
  26065. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26066. peer_stalled = true;
  26067. // Let close() send its Close frame and park in its own read before the
  26068. // rest of the payload arrives, so both threads are waiting for it.
  26069. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26070. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  26071. close_frame += static_cast<char>(0x03); // status 1000
  26072. close_frame += static_cast<char>(0xE8);
  26073. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  26074. << "attempt " << attempt;
  26075. // Closing the peer releases the reader thread even on the buggy path,
  26076. // where it waits for bytes another thread already consumed.
  26077. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26078. detail::close_socket(sock);
  26079. sock = INVALID_SOCKET;
  26080. wait_for(handler_done);
  26081. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  26082. }
  26083. std::lock_guard<std::mutex> guard(received_mutex);
  26084. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  26085. << "a message in flight when close() ran was dropped";
  26086. for (size_t i = 0; i < received.size(); i++) {
  26087. EXPECT_EQ(expected, received[i]) << "message " << i;
  26088. }
  26089. }
  26090. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  26091. // returning the socket, or INVALID_SOCKET.
  26092. static socket_t connect_raw_websocket(int port, const std::string &path) {
  26093. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26094. if (sock == INVALID_SOCKET) { return sock; }
  26095. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26096. sockaddr_in addr{};
  26097. addr.sin_family = AF_INET;
  26098. addr.sin_port = htons(static_cast<uint16_t>(port));
  26099. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26100. std::string req = "GET " + path +
  26101. " HTTP/1.1\r\n"
  26102. "Host: 127.0.0.1\r\n"
  26103. "Upgrade: websocket\r\n"
  26104. "Connection: Upgrade\r\n"
  26105. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26106. "Sec-WebSocket-Version: 13\r\n"
  26107. "\r\n";
  26108. std::string res;
  26109. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  26110. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26111. static_cast<ssize_t>(req.size())) {
  26112. char c;
  26113. while (res.find("\r\n\r\n") == std::string::npos &&
  26114. ::recv(sock, &c, 1, 0) == 1) {
  26115. res += c;
  26116. }
  26117. }
  26118. if (res.find(" 101 ") == std::string::npos) {
  26119. detail::close_socket(sock);
  26120. return INVALID_SOCKET;
  26121. }
  26122. return sock;
  26123. }
  26124. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26125. // The payload must fit the 7-bit length field.
  26126. static std::string masked_frame(uint8_t first_byte,
  26127. const std::string &payload) {
  26128. std::string f;
  26129. f += static_cast<char>(first_byte);
  26130. f += static_cast<char>(0x80 | payload.size());
  26131. f.append(4, '\0');
  26132. return f + payload;
  26133. }
  26134. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26135. std::atomic<bool> done{false};
  26136. std::string received;
  26137. Server svr;
  26138. svr.set_websocket_ping_interval(0);
  26139. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26140. std::string msg;
  26141. if (ws.read(msg) == ws::Binary) { received = msg; }
  26142. done = true;
  26143. });
  26144. auto port = svr.bind_to_any_port("127.0.0.1");
  26145. std::thread t([&]() { svr.listen_after_bind(); });
  26146. auto se = detail::scope_exit([&] {
  26147. svr.stop();
  26148. t.join();
  26149. });
  26150. svr.wait_until_ready();
  26151. auto sock = connect_raw_websocket(port, "/ws");
  26152. ASSERT_NE(INVALID_SOCKET, sock);
  26153. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26154. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26155. masked_frame(0x89, "p") + // FIN + Ping
  26156. masked_frame(0x80, "lo"); // FIN + Continuation
  26157. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26158. for (int i = 0; i < 500 && !done; i++) {
  26159. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26160. }
  26161. ASSERT_TRUE(done);
  26162. EXPECT_EQ("Hello", received);
  26163. // The Ping between the fragments is answered with a Pong.
  26164. char pong[3];
  26165. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26166. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26167. }
  26168. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26169. #ifndef _WIN32
  26170. signal(SIGPIPE, SIG_IGN);
  26171. #endif
  26172. std::atomic<bool> read_ended{false};
  26173. std::atomic<bool> sending{true};
  26174. Server svr;
  26175. svr.set_websocket_ping_interval(0);
  26176. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26177. std::thread reader([&]() {
  26178. std::string msg;
  26179. while (ws.read(msg)) {}
  26180. read_ended = true;
  26181. });
  26182. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26183. ws.close();
  26184. reader.join();
  26185. });
  26186. auto port = svr.bind_to_any_port("127.0.0.1");
  26187. std::thread t([&]() { svr.listen_after_bind(); });
  26188. auto se = detail::scope_exit([&] {
  26189. svr.stop();
  26190. t.join();
  26191. });
  26192. svr.wait_until_ready();
  26193. auto sock = connect_raw_websocket(port, "/ws");
  26194. ASSERT_NE(INVALID_SOCKET, sock);
  26195. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26196. // A Text message whose empty continuation frames never end
  26197. std::thread sender([&]() {
  26198. auto data = masked_frame(0x01, "");
  26199. while (sending) {
  26200. data += masked_frame(0x00, "");
  26201. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26202. return;
  26203. }
  26204. data.clear();
  26205. }
  26206. });
  26207. for (int i = 0; i < 300 && !read_ended; i++) {
  26208. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26209. }
  26210. sending = false;
  26211. sender.join();
  26212. EXPECT_TRUE(read_ended);
  26213. }
  26214. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26215. Server svr;
  26216. svr.set_websocket_ping_interval(-1);
  26217. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26218. std::string msg;
  26219. while (ws.read(msg)) {}
  26220. });
  26221. auto port = svr.bind_to_any_port("127.0.0.1");
  26222. std::thread t([&]() { svr.listen_after_bind(); });
  26223. auto se = detail::scope_exit([&] {
  26224. svr.stop();
  26225. t.join();
  26226. });
  26227. svr.wait_until_ready();
  26228. auto sock = connect_raw_websocket(port, "/ws");
  26229. ASSERT_NE(INVALID_SOCKET, sock);
  26230. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26231. // Nothing comes while the client stays quiet.
  26232. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26233. char c;
  26234. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26235. }
  26236. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26237. // and that has to end a read() already waiting on the peer, on every platform.
  26238. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26239. // The peer sends no pings, and its handler never calls read(), which is
  26240. // where pongs are written.
  26241. std::mutex mutex;
  26242. std::condition_variable cv;
  26243. auto release = false;
  26244. svr.set_websocket_ping_interval(0);
  26245. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26246. std::unique_lock<std::mutex> lock(mutex);
  26247. cv.wait(lock, [&] { return release; });
  26248. });
  26249. auto port = svr.bind_to_any_port(HOST);
  26250. std::thread t([&]() { svr.listen_after_bind(); });
  26251. auto se = detail::scope_exit([&] {
  26252. {
  26253. std::lock_guard<std::mutex> lock(mutex);
  26254. release = true;
  26255. }
  26256. cv.notify_all();
  26257. svr.stop();
  26258. t.join();
  26259. });
  26260. svr.wait_until_ready();
  26261. ws::WebSocketClient client(std::string(scheme) +
  26262. "://localhost:" + std::to_string(port) + "/ws");
  26263. #ifdef CPPHTTPLIB_SSL_ENABLED
  26264. client.enable_server_certificate_verification(false);
  26265. #endif
  26266. // A ping a second, given up on after two go unanswered: about 3s
  26267. client.set_websocket_ping_interval(1);
  26268. client.set_websocket_max_missed_pongs(2);
  26269. // Well past that, so that a read the timeout ends instead stands out
  26270. client.set_read_timeout(10);
  26271. ASSERT_TRUE(client.connect());
  26272. auto start = std::chrono::steady_clock::now();
  26273. std::string msg;
  26274. EXPECT_EQ(ws::Fail, client.read(msg));
  26275. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26276. std::chrono::steady_clock::now() - start)
  26277. .count(),
  26278. 6000);
  26279. EXPECT_FALSE(client.is_open());
  26280. }
  26281. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26282. Server svr;
  26283. check_pong_timeout_ends_read(svr, "ws");
  26284. }
  26285. #ifdef CPPHTTPLIB_SSL_ENABLED
  26286. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26287. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26288. ASSERT_TRUE(svr.is_valid());
  26289. check_pong_timeout_ends_read(svr, "wss");
  26290. }
  26291. #endif
  26292. // listen() returns only after every handler has, so Server::stop() has to end
  26293. // a WebSocket handler's read() waiting on a client that stays connected and
  26294. // quiet, whether or not the handler bounded its reads, and the client's
  26295. // connection ends with it.
  26296. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26297. bool bounded) {
  26298. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26299. if (bounded) { ws.set_read_timeout(0, 50000); }
  26300. std::string msg;
  26301. while (ws.read(msg) != ws::Fail) {}
  26302. });
  26303. auto port = svr.bind_to_any_port(HOST);
  26304. std::thread t([&]() { svr.listen_after_bind(); });
  26305. auto se = detail::scope_exit([&] {
  26306. if (t.joinable()) {
  26307. svr.stop();
  26308. t.join();
  26309. }
  26310. });
  26311. svr.wait_until_ready();
  26312. ws::WebSocketClient client(std::string(scheme) +
  26313. "://localhost:" + std::to_string(port) + "/ws");
  26314. #ifdef CPPHTTPLIB_SSL_ENABLED
  26315. client.enable_server_certificate_verification(false);
  26316. #endif
  26317. client.set_read_timeout(2);
  26318. ASSERT_TRUE(client.connect());
  26319. auto stopped = std::async(std::launch::async, [&] {
  26320. svr.stop();
  26321. t.join();
  26322. });
  26323. std::string msg;
  26324. EXPECT_EQ(ws::Fail, client.read(msg));
  26325. EXPECT_FALSE(client.is_open());
  26326. auto in_time =
  26327. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26328. // A handler the stop did not reach ends when the client leaves
  26329. if (!in_time) { client.close(); }
  26330. stopped.wait();
  26331. EXPECT_TRUE(in_time);
  26332. }
  26333. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26334. Server svr;
  26335. check_stop_ends_websocket_read(svr, "ws", false);
  26336. }
  26337. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26338. Server svr;
  26339. check_stop_ends_websocket_read(svr, "ws", true);
  26340. }
  26341. #ifdef CPPHTTPLIB_SSL_ENABLED
  26342. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26343. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26344. ASSERT_TRUE(svr.is_valid());
  26345. check_stop_ends_websocket_read(svr, "wss", false);
  26346. }
  26347. #endif
  26348. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26349. // dropped connection, whether the handler waits for a message or for the rest
  26350. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26351. // time out inside the message as well, and the stop ends them too.
  26352. static void check_stop_closes_with_going_away(const std::string &sent,
  26353. bool bounded = false) {
  26354. Server svr;
  26355. svr.set_websocket_ping_interval(0);
  26356. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26357. if (bounded) { ws.set_read_timeout(0, 10000); }
  26358. std::string msg;
  26359. while (ws.read(msg) != ws::Fail) {}
  26360. });
  26361. auto port = svr.bind_to_any_port("127.0.0.1");
  26362. std::thread t([&]() { svr.listen_after_bind(); });
  26363. auto se = detail::scope_exit([&] {
  26364. svr.stop();
  26365. t.join();
  26366. });
  26367. svr.wait_until_ready();
  26368. // Closed before the join above, which a handler the stop did not reach
  26369. // would otherwise hold up.
  26370. auto sock = connect_raw_websocket(port, "/ws");
  26371. ASSERT_NE(INVALID_SOCKET, sock);
  26372. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26373. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26374. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26375. // Let the handler take what was sent and wait for more
  26376. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26377. svr.stop();
  26378. // FIN + Close, its length, then the code: unmasked, from a server
  26379. std::string head;
  26380. char c;
  26381. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26382. head += c;
  26383. }
  26384. const std::string reason = "server stopping";
  26385. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26386. "\x03\xe9",
  26387. head);
  26388. }
  26389. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26390. check_stop_closes_with_going_away("");
  26391. }
  26392. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26393. // A Text frame without FIN: the first fragment of a message
  26394. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26395. }
  26396. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26397. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26398. /*bounded=*/true);
  26399. }
  26400. // A handler that bounds its reads gets control back within its timeout even
  26401. // while a message arrives in pieces, and the message whole once the last has
  26402. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26403. // sent a while after the one before, much longer than the handler's timeout.
  26404. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26405. const std::string &expected) {
  26406. std::atomic<bool> done{false};
  26407. std::string received;
  26408. std::chrono::steady_clock::duration longest{};
  26409. Server svr;
  26410. svr.set_websocket_ping_interval(0);
  26411. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26412. ws.set_read_timeout(0, 10000);
  26413. std::string msg;
  26414. ws::ReadResult r;
  26415. do {
  26416. auto began = std::chrono::steady_clock::now();
  26417. r = ws.read(msg);
  26418. longest = (std::max)(longest, std::chrono::steady_clock::now() - began);
  26419. } while (r == ws::Timeout);
  26420. if (r == ws::Text) { received = msg; }
  26421. done = true;
  26422. });
  26423. auto port = svr.bind_to_any_port("127.0.0.1");
  26424. std::thread t([&]() { svr.listen_after_bind(); });
  26425. auto se = detail::scope_exit([&] {
  26426. svr.stop();
  26427. t.join();
  26428. });
  26429. svr.wait_until_ready();
  26430. auto sock = connect_raw_websocket(port, "/ws");
  26431. ASSERT_NE(INVALID_SOCKET, sock);
  26432. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26433. for (const auto &piece : pieces) {
  26434. ASSERT_EQ(static_cast<ssize_t>(piece.size()),
  26435. detail::send_socket(sock, piece.data(), piece.size(), 0));
  26436. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26437. }
  26438. for (int i = 0; i < 500 && !done; i++) {
  26439. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26440. }
  26441. ASSERT_TRUE(done);
  26442. EXPECT_EQ(expected, received);
  26443. // Far under the 200 ms between the pieces, however loaded the machine
  26444. EXPECT_LT(longest, std::chrono::milliseconds(150));
  26445. }
  26446. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26447. // The header's first byte, then its second with half the mask key, then
  26448. // the rest: what a frame written in several writes may look like when
  26449. // Nagle's algorithm holds the later ones back for an ACK.
  26450. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26451. check_bounded_read_resumes(
  26452. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26453. }
  26454. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26455. check_bounded_read_resumes(
  26456. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26457. }
  26458. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26459. Server svr;
  26460. svr.set_websocket_ping_interval(0);
  26461. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26462. std::string msg;
  26463. while (ws.read(msg)) {}
  26464. });
  26465. auto port = svr.bind_to_any_port("127.0.0.1");
  26466. std::thread t([&]() { svr.listen_after_bind(); });
  26467. auto se = detail::scope_exit([&] {
  26468. svr.stop();
  26469. t.join();
  26470. });
  26471. svr.wait_until_ready();
  26472. // Each Close payload and the reply it should get: an echo when valid, 1002
  26473. // otherwise.
  26474. std::vector<std::pair<std::string, std::string>> cases = {
  26475. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26476. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26477. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26478. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26479. };
  26480. // Also between the fragments of a message.
  26481. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26482. for (const auto &c : cases) {
  26483. auto sock = connect_raw_websocket(port, "/ws");
  26484. ASSERT_NE(INVALID_SOCKET, sock);
  26485. auto frames = prefix + masked_frame(0x88, c.first);
  26486. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26487. std::string reply;
  26488. char buf[256];
  26489. while (reply.size() < 2 + c.second.size()) {
  26490. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26491. if (n <= 0) { break; }
  26492. reply.append(buf, static_cast<size_t>(n));
  26493. }
  26494. detail::close_socket(sock);
  26495. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26496. c.second,
  26497. reply);
  26498. }
  26499. }
  26500. }
  26501. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26502. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26503. protected:
  26504. void SetUp() override {
  26505. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26506. SERVER_PRIVATE_KEY_FILE);
  26507. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26508. std::string msg;
  26509. ws::ReadResult ret;
  26510. while ((ret = ws.read(msg))) {
  26511. if (ret == ws::Binary) {
  26512. ws.send(msg.data(), msg.size());
  26513. } else {
  26514. ws.send(msg);
  26515. }
  26516. }
  26517. });
  26518. port_ = server_->bind_to_any_port(HOST);
  26519. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26520. server_->wait_until_ready();
  26521. }
  26522. void TearDown() override {
  26523. server_->stop();
  26524. if (server_thread_.joinable()) { server_thread_.join(); }
  26525. }
  26526. std::unique_ptr<SSLServer> server_;
  26527. std::thread server_thread_;
  26528. int port_ = 0;
  26529. };
  26530. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26531. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26532. {
  26533. ws::WebSocketClient client(url);
  26534. client.enable_server_certificate_verification(false);
  26535. auto calls = 0;
  26536. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26537. calls++;
  26538. return false;
  26539. });
  26540. EXPECT_FALSE(client.connect());
  26541. EXPECT_GT(calls, 0);
  26542. }
  26543. {
  26544. ws::WebSocketClient client(url);
  26545. client.enable_server_certificate_verification(false);
  26546. client.set_session_verifier([](tls::session_t) {
  26547. return SSLVerifierResponse::CertificateRejected;
  26548. });
  26549. EXPECT_FALSE(client.connect());
  26550. }
  26551. {
  26552. ws::WebSocketClient client(url);
  26553. client.enable_server_certificate_verification(false);
  26554. client.set_session_verifier([](tls::session_t) {
  26555. return SSLVerifierResponse::CertificateAccepted;
  26556. });
  26557. EXPECT_TRUE(client.connect());
  26558. }
  26559. }
  26560. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26561. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26562. "/ws-echo");
  26563. client.enable_server_certificate_verification(false);
  26564. ASSERT_TRUE(client.connect());
  26565. ASSERT_TRUE(client.is_open());
  26566. ASSERT_TRUE(client.send("Hello WSS"));
  26567. std::string msg;
  26568. EXPECT_EQ(ws::Text, client.read(msg));
  26569. EXPECT_EQ("Hello WSS", msg);
  26570. client.close();
  26571. }
  26572. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  26573. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  26574. "/ws-echo");
  26575. client.enable_server_certificate_verification(false);
  26576. EXPECT_TRUE(client.connect());
  26577. }
  26578. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26579. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26580. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26581. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26582. // client (without calling close() first) is the only path that runs
  26583. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26584. // bug exactly.
  26585. //
  26586. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26587. // when linked against an instrumented libssl; run under Valgrind to catch it
  26588. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26589. // suite (the freed session otherwise stalls on the close handshake) — this test
  26590. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26591. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26592. {
  26593. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26594. "/ws-echo");
  26595. client.enable_server_certificate_verification(false);
  26596. client.set_read_timeout(2, 0);
  26597. client.set_write_timeout(2, 0);
  26598. ASSERT_TRUE(client.connect());
  26599. ASSERT_TRUE(client.is_open());
  26600. ASSERT_TRUE(client.send("still open"));
  26601. // Intentionally do NOT call client.close(): leaving scope runs
  26602. // shutdown_and_close() with the WebSocket still open, which must send the
  26603. // close frame while the TLS session is still alive.
  26604. }
  26605. }
  26606. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26607. // shutdown_and_close() at the start of connect(), reproducing the same
  26608. // use-after-free within the test body rather than at scope exit. The second
  26609. // connect must succeed and echo, proving the close handshake ran over a live
  26610. // session. See the note above about memory-tool requirements.
  26611. TEST_F(WebSocketSSLIntegrationTest,
  26612. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26613. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26614. "/ws-echo");
  26615. client.enable_server_certificate_verification(false);
  26616. client.set_read_timeout(2, 0);
  26617. client.set_write_timeout(2, 0);
  26618. ASSERT_TRUE(client.connect());
  26619. ASSERT_TRUE(client.is_open());
  26620. ASSERT_TRUE(client.send("still open"));
  26621. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26622. // the still-open connection, which must not touch a freed TLS session.
  26623. ASSERT_TRUE(client.connect());
  26624. ASSERT_TRUE(client.is_open());
  26625. ASSERT_TRUE(client.send("after reconnect"));
  26626. std::string msg;
  26627. EXPECT_EQ(ws::Text, client.read(msg));
  26628. EXPECT_EQ("after reconnect", msg);
  26629. client.close();
  26630. }
  26631. #endif
  26632. #ifdef CPPHTTPLIB_SSL_ENABLED
  26633. class WebSocketSSLCATest : public ::testing::Test {
  26634. protected:
  26635. void SetUp() override {
  26636. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26637. SERVER_PRIVATE_KEY_FILE);
  26638. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26639. std::string msg;
  26640. while (ws.read(msg)) {
  26641. ws.send(msg);
  26642. }
  26643. });
  26644. port_ = server_->bind_to_any_port("127.0.0.1");
  26645. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26646. server_->wait_until_ready();
  26647. }
  26648. void TearDown() override {
  26649. server_->stop();
  26650. if (server_thread_.joinable()) { server_thread_.join(); }
  26651. }
  26652. std::string url() const {
  26653. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26654. }
  26655. std::unique_ptr<SSLServer> server_;
  26656. std::thread server_thread_;
  26657. int port_ = 0;
  26658. };
  26659. // A custom CA loaded as PEM verifies the server with full certificate
  26660. // verification enabled
  26661. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26662. ws::WebSocketClient client(url());
  26663. std::string cert;
  26664. read_file(SERVER_CERT2_FILE, cert);
  26665. client.load_ca_cert_store(cert.c_str(), cert.size());
  26666. ASSERT_TRUE(client.connect());
  26667. ASSERT_TRUE(client.send("hello"));
  26668. std::string msg;
  26669. EXPECT_EQ(ws::Text, client.read(msg));
  26670. EXPECT_EQ("hello", msg);
  26671. client.close();
  26672. }
  26673. // A custom CA that does not cover the server must fail verification (the
  26674. // custom CA is exclusive; system certs are not loaded alongside it)
  26675. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26676. ws::WebSocketClient client(url());
  26677. std::string cert;
  26678. read_file(CLIENT_CA_CERT_FILE, cert);
  26679. client.load_ca_cert_store(cert.c_str(), cert.size());
  26680. auto res = client.connect();
  26681. ASSERT_FALSE(res);
  26682. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26683. EXPECT_EQ(-1, res.status());
  26684. EXPECT_NE(0u, res.ssl_backend_error());
  26685. }
  26686. // The same CA as a file path rather than PEM in memory
  26687. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26688. ws::WebSocketClient client(url());
  26689. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26690. ASSERT_TRUE(client.connect());
  26691. ASSERT_TRUE(client.send("hello"));
  26692. std::string msg;
  26693. EXPECT_EQ(ws::Text, client.read(msg));
  26694. EXPECT_EQ("hello", msg);
  26695. client.close();
  26696. }
  26697. // ...and a CA file that does not cover the server still fails, so it is the
  26698. // path above that decides the outcome
  26699. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  26700. ws::WebSocketClient client(url());
  26701. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26702. ASSERT_FALSE(client.connect());
  26703. }
  26704. // Regression test: reconnecting with a native custom CA store used to reuse
  26705. // a store handle the previous TLS context had already freed (use-after-free
  26706. // under the OpenSSL backend). The context now lives as long as the client.
  26707. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  26708. ws::WebSocketClient client(url());
  26709. std::string cert;
  26710. read_file(SERVER_CERT2_FILE, cert);
  26711. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  26712. ASSERT_TRUE(client.connect());
  26713. client.close();
  26714. ASSERT_TRUE(client.connect());
  26715. ASSERT_TRUE(client.send("again"));
  26716. std::string msg;
  26717. EXPECT_EQ(ws::Text, client.read(msg));
  26718. EXPECT_EQ("again", msg);
  26719. client.close();
  26720. }
  26721. // Regression test: a certificate with a trusted chain but no identity match
  26722. // for the server IP must be rejected. The Mbed TLS backend used to skip
  26723. // verification entirely for IP hosts, so this connection succeeded there.
  26724. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  26725. // chain verification while the identity check must still fail.
  26726. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  26727. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26728. ASSERT_TRUE(svr.is_valid());
  26729. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26730. std::string msg;
  26731. while (ws.read(msg)) {
  26732. ws.send(msg);
  26733. }
  26734. });
  26735. auto port = svr.bind_to_any_port("127.0.0.1");
  26736. auto t = std::thread([&]() { svr.listen_after_bind(); });
  26737. auto se = detail::scope_exit([&] {
  26738. svr.stop();
  26739. t.join();
  26740. });
  26741. svr.wait_until_ready();
  26742. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  26743. "/echo");
  26744. std::string cert;
  26745. read_file(SERVER_CERT_FILE, cert);
  26746. client.load_ca_cert_store(cert.c_str(), cert.size());
  26747. ASSERT_FALSE(client.connect());
  26748. }
  26749. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  26750. // SNI, so nothing binds the host name to the TLS session. These bind the
  26751. // server to "localhost" instead, the only shape that exercises the SNI and
  26752. // hostname-verification path with certificate verification left enabled.
  26753. class WebSocketSSLDnsHostTest : public ::testing::Test {
  26754. protected:
  26755. void Start(const char *cert_file) {
  26756. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  26757. SERVER_PRIVATE_KEY_FILE);
  26758. ASSERT_TRUE(server_->is_valid());
  26759. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26760. std::string msg;
  26761. while (ws.read(msg)) {
  26762. ws.send(msg);
  26763. }
  26764. });
  26765. port_ = server_->bind_to_any_port("localhost");
  26766. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26767. server_->wait_until_ready();
  26768. }
  26769. void TearDown() override {
  26770. if (server_) { server_->stop(); }
  26771. if (server_thread_.joinable()) { server_thread_.join(); }
  26772. }
  26773. std::string url() const {
  26774. return "wss://localhost:" + std::to_string(port_) + "/echo";
  26775. }
  26776. std::unique_ptr<SSLServer> server_;
  26777. std::thread server_thread_;
  26778. int port_ = 0;
  26779. };
  26780. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  26781. // out and the connection is usable
  26782. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  26783. Start(SERVER_CERT2_FILE);
  26784. ws::WebSocketClient client(url());
  26785. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26786. ASSERT_TRUE(client.connect());
  26787. ASSERT_TRUE(client.send("hello"));
  26788. std::string msg;
  26789. EXPECT_EQ(ws::Text, client.read(msg));
  26790. EXPECT_EQ("hello", msg);
  26791. client.close();
  26792. }
  26793. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  26794. // while the identity check must still reject "localhost"
  26795. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  26796. Start(SERVER_CERT_FILE);
  26797. ws::WebSocketClient client(url());
  26798. client.set_ca_cert_path(SERVER_CERT_FILE);
  26799. auto res = client.connect();
  26800. ASSERT_FALSE(res);
  26801. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  26802. EXPECT_EQ(-1, res.status());
  26803. }
  26804. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  26805. // disabled: the chain is still checked, only the identity check is skipped
  26806. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  26807. Start(SERVER_CERT_FILE);
  26808. ws::WebSocketClient client(url());
  26809. client.set_ca_cert_path(SERVER_CERT_FILE);
  26810. client.enable_server_hostname_verification(false);
  26811. ASSERT_TRUE(client.connect());
  26812. ASSERT_TRUE(client.send("hello"));
  26813. std::string msg;
  26814. EXPECT_EQ(ws::Text, client.read(msg));
  26815. EXPECT_EQ("hello", msg);
  26816. client.close();
  26817. }
  26818. // A CA that did not sign the server certificate fails the chain, even though
  26819. // the name would match
  26820. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  26821. Start(SERVER_CERT2_FILE);
  26822. ws::WebSocketClient client(url());
  26823. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26824. ASSERT_FALSE(client.connect());
  26825. }
  26826. // With verification disabled, neither the chain nor the name is checked
  26827. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  26828. Start(SERVER_CERT_FILE);
  26829. ws::WebSocketClient client(url());
  26830. client.enable_server_certificate_verification(false);
  26831. ASSERT_TRUE(client.connect());
  26832. ASSERT_TRUE(client.send("hello"));
  26833. std::string msg;
  26834. EXPECT_EQ(ws::Text, client.read(msg));
  26835. EXPECT_EQ("hello", msg);
  26836. client.close();
  26837. }
  26838. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  26839. protected:
  26840. void SetUp() override {
  26841. server_ = httplib::detail::make_unique<SSLServer>(
  26842. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  26843. ASSERT_TRUE(server_->is_valid());
  26844. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26845. std::string msg;
  26846. while (ws.read(msg)) {
  26847. ws.send(msg);
  26848. }
  26849. });
  26850. port_ = server_->bind_to_any_port("localhost");
  26851. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26852. server_->wait_until_ready();
  26853. }
  26854. void TearDown() override {
  26855. server_->stop();
  26856. if (server_thread_.joinable()) { server_thread_.join(); }
  26857. }
  26858. std::string url() const {
  26859. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26860. }
  26861. void ConnectWithClientCert(const std::string &client_cert_file,
  26862. const std::string &client_private_key_file,
  26863. const char *private_key_password) {
  26864. std::string cert_pem, key_pem;
  26865. read_file(client_cert_file, cert_pem);
  26866. read_file(client_private_key_file, key_pem);
  26867. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  26868. key_pem.c_str(), key_pem.size(),
  26869. private_key_password};
  26870. ConnectWithPem(pem);
  26871. }
  26872. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  26873. ws::WebSocketClient client(url(), pem);
  26874. ASSERT_TRUE(client.is_valid());
  26875. client.enable_server_certificate_verification(false);
  26876. ASSERT_TRUE(client.connect());
  26877. ASSERT_TRUE(client.send("hello"));
  26878. std::string msg;
  26879. EXPECT_EQ(ws::Text, client.read(msg));
  26880. EXPECT_EQ("hello", msg);
  26881. client.close();
  26882. }
  26883. std::unique_ptr<SSLServer> server_;
  26884. std::thread server_thread_;
  26885. int port_ = 0;
  26886. };
  26887. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  26888. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  26889. }
  26890. // Control for the tests above: the fixture's server really does require a
  26891. // client certificate, so it is the PEM the constructor installed that decides
  26892. // the outcome.
  26893. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  26894. ws::WebSocketClient client(url());
  26895. ASSERT_TRUE(client.is_valid());
  26896. client.enable_server_certificate_verification(false);
  26897. EXPECT_FALSE(client.connect());
  26898. }
  26899. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  26900. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  26901. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  26902. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  26903. }
  26904. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  26905. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  26906. std::string cert_pem, key_pem;
  26907. read_file(CLIENT_CERT_FILE, cert_pem);
  26908. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  26909. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  26910. std::vector<char> key(key_pem.begin(), key_pem.end());
  26911. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  26912. key.size(), nullptr};
  26913. ConnectWithPem(pem);
  26914. }
  26915. #endif
  26916. #if !defined(_WIN32)
  26917. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  26918. auto secret_dir = std::string("./symlink_test_secret");
  26919. auto served_dir = std::string("./symlink_test_served");
  26920. auto secret_file = secret_dir + "/secret.txt";
  26921. auto symlink_path = served_dir + "/escape";
  26922. // Setup: create directories and files
  26923. mkdir(secret_dir.c_str(), 0755);
  26924. mkdir(served_dir.c_str(), 0755);
  26925. {
  26926. std::ofstream ofs(secret_file);
  26927. ofs << "SECRET_DATA";
  26928. }
  26929. // Create symlink using absolute path so it resolves correctly
  26930. #ifdef PATH_MAX
  26931. char abs_secret[PATH_MAX];
  26932. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  26933. #else
  26934. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  26935. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  26936. ASSERT_NE(nullptr, abs_secret);
  26937. #endif
  26938. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  26939. auto se = detail::scope_exit([&] {
  26940. unlink(symlink_path.c_str());
  26941. unlink(secret_file.c_str());
  26942. rmdir(served_dir.c_str());
  26943. rmdir(secret_dir.c_str());
  26944. });
  26945. Server svr;
  26946. svr.set_mount_point("/", served_dir);
  26947. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26948. auto se2 = detail::scope_exit([&] {
  26949. svr.stop();
  26950. listen_thread.join();
  26951. });
  26952. svr.wait_until_ready();
  26953. Client cli("localhost", PORT);
  26954. // Symlink pointing outside base dir should be blocked
  26955. auto res = cli.Get("/escape/secret.txt");
  26956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26957. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26958. }
  26959. #else
  26960. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  26961. auto secret_dir = std::string("junction_test_secret");
  26962. auto served_dir = std::string("junction_test_served");
  26963. auto secret_file = secret_dir + "\\secret.txt";
  26964. auto junction_path = served_dir + "\\escape";
  26965. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  26966. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  26967. {
  26968. std::ofstream ofs(secret_file);
  26969. ofs << "SECRET_DATA";
  26970. }
  26971. // A junction needs no privilege to create, unlike a symlink
  26972. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  26973. ASSERT_EQ(0, std::system(cmd.c_str()));
  26974. auto se = detail::scope_exit([&] {
  26975. ::RemoveDirectoryA(junction_path.c_str());
  26976. std::remove(secret_file.c_str());
  26977. ::RemoveDirectoryA(served_dir.c_str());
  26978. ::RemoveDirectoryA(secret_dir.c_str());
  26979. });
  26980. Server svr;
  26981. svr.set_mount_point("/", served_dir);
  26982. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  26983. auto se2 = detail::scope_exit([&] {
  26984. svr.stop();
  26985. listen_thread.join();
  26986. });
  26987. svr.wait_until_ready();
  26988. Client cli("localhost", PORT);
  26989. // Junction pointing outside base dir should be blocked
  26990. auto res = cli.Get("/escape/secret.txt");
  26991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26992. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  26993. }
  26994. #endif
  26995. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  26996. // "GET /smuggled" request), reads the first response, and only then sends the
  26997. // embedded request as the body. Returns how many times /smuggled ran.
  26998. //
  26999. // The body is sent AFTER receiving the first response (as in the original
  27000. // PoC) so that the stream_line_reader cannot buffer it together with the
  27001. // headers of the first request.
  27002. static int count_smuggled_requests(const std::string &outer_head,
  27003. std::string &first_response) {
  27004. Server svr;
  27005. svr.set_mount_point("/", "./www");
  27006. std::atomic<int> smuggled_count(0);
  27007. svr.Get("/smuggled", [&](const Request &, Response &res) {
  27008. smuggled_count++;
  27009. res.set_content("oops", "text/plain");
  27010. });
  27011. svr.Post("/post", [&](const Request &req, Response &res) {
  27012. res.set_content(req.body, "text/plain");
  27013. });
  27014. auto port = svr.bind_to_any_port("localhost");
  27015. thread t = thread([&] { svr.listen_after_bind(); });
  27016. auto se = detail::scope_exit([&] {
  27017. svr.stop();
  27018. t.join();
  27019. });
  27020. svr.wait_until_ready();
  27021. auto error = Error::Success;
  27022. auto sock = detail::create_client_socket(
  27023. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  27024. /*connection_timeout_sec=*/2, 0,
  27025. /*read_timeout_sec=*/2, 0,
  27026. /*write_timeout_sec=*/2, 0, std::string(), error);
  27027. EXPECT_NE(INVALID_SOCKET, sock);
  27028. if (sock == INVALID_SOCKET) { return -1; }
  27029. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27030. // The "smuggled" request will be sent as the body of the outer request
  27031. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  27032. "Host: localhost\r\n"
  27033. "Connection: close\r\n"
  27034. "\r\n";
  27035. auto head = outer_head;
  27036. auto len = std::to_string(smuggled.size());
  27037. for (auto pos = head.find("{len}"); pos != std::string::npos;
  27038. pos = head.find("{len}", pos + len.size())) {
  27039. head.replace(pos, 5, len);
  27040. }
  27041. // Step 1: Send only the outer request headers (no body yet)
  27042. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  27043. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  27044. // Step 2: Read the first response
  27045. char buf[4096];
  27046. for (;;) {
  27047. auto n = recv(sock, buf, sizeof(buf), 0);
  27048. if (n <= 0) break;
  27049. first_response.append(buf, static_cast<size_t>(n));
  27050. // Stop once we have a complete response (headers + body)
  27051. auto hdr_end = first_response.find("\r\n\r\n");
  27052. if (hdr_end != std::string::npos) {
  27053. // Check for Content-Length to know when the body is complete
  27054. auto cl_pos = first_response.find("Content-Length:");
  27055. if (cl_pos != std::string::npos) {
  27056. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  27057. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  27058. auto cl = std::stoul(
  27059. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  27060. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  27061. } else {
  27062. break; // No Content-Length, assume headers-only response
  27063. }
  27064. }
  27065. }
  27066. // Step 3: Now send the body, which looks like a new HTTP request. On a
  27067. // vulnerable server the keep-alive loop reads this as a second request. The
  27068. // server may already have closed the connection, so the result is ignored.
  27069. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  27070. // Half-close so that a server which drained the body sees EOF and closes,
  27071. // instead of the read below waiting for the read timeout.
  27072. #ifdef _WIN32
  27073. ::shutdown(sock, SD_SEND);
  27074. #else
  27075. ::shutdown(sock, SHUT_WR);
  27076. #endif
  27077. // Step 4: Read until the server closes the connection
  27078. for (;;) {
  27079. auto n = recv(sock, buf, sizeof(buf), 0);
  27080. if (n <= 0) break;
  27081. }
  27082. return smuggled_count.load();
  27083. }
  27084. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  27085. // A GET request with Content-Length to a static file handler must have its
  27086. // body drained before the keep-alive connection is reused. Otherwise the
  27087. // unread body bytes are interpreted as the next HTTP request.
  27088. std::string first_response;
  27089. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27090. "Host: localhost\r\n"
  27091. "Content-Length: {len}\r\n"
  27092. "\r\n",
  27093. first_response));
  27094. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  27095. }
  27096. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  27097. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  27098. // be answered with 400 and the connection closed. Treating it as "no body"
  27099. // leaves the body to be parsed as the next request.
  27100. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  27101. const char *targets[] = {
  27102. "GET /file", // handler that never reads the body
  27103. "GET /not-found", // no handler matches (404)
  27104. "POST /post", // handler that reads the body
  27105. };
  27106. for (auto target : targets) {
  27107. for (auto value : values) {
  27108. std::string first_response;
  27109. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  27110. " HTTP/1.1\r\n"
  27111. "Host: localhost\r\n"
  27112. "Content-Length: " +
  27113. value + "\r\n\r\n",
  27114. first_response))
  27115. << target << " with Content-Length: " << value;
  27116. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27117. << target << " with Content-Length: " << value;
  27118. }
  27119. }
  27120. }
  27121. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27122. // A 400 for an unparseable request line leaves the rest of the message
  27123. // unread, so the connection must be closed rather than reused.
  27124. std::string first_response;
  27125. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27126. "Host: localhost\r\n"
  27127. "Content-Length: {len}\r\n"
  27128. "\r\n",
  27129. first_response));
  27130. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27131. }
  27132. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27133. // Same as above for a header block that fails to parse.
  27134. std::string first_response;
  27135. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27136. "Host: localhost\r\n"
  27137. "Bad Header\r\n"
  27138. "Content-Length: {len}\r\n"
  27139. "\r\n",
  27140. first_response));
  27141. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27142. }
  27143. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27144. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27145. // server must not read another request on that connection, even when the
  27146. // request had no body to drain.
  27147. std::string first_response;
  27148. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27149. "Host: localhost\r\n"
  27150. "\r\n",
  27151. first_response));
  27152. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27153. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27154. }
  27155. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27156. // A content reader that stops early leaves the stream inside the body.
  27157. // Draining the whole Content-Length from there, or reading the body again,
  27158. // reads into the next request, and whatever follows is parsed as a request
  27159. // of its own.
  27160. Server svr;
  27161. std::atomic<int> smuggled_count(0);
  27162. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27163. svr.Post("/upload", [](const Request &req, Response &res,
  27164. const ContentReader &content_reader) {
  27165. // Stop at the last chunk, so the whole body has been read however it
  27166. // arrives.
  27167. auto length = req.get_header_value_u64("Content-Length");
  27168. size_t total = 0;
  27169. auto consumed = content_reader([&](const char *, size_t n) {
  27170. total += n;
  27171. return total < length;
  27172. });
  27173. EXPECT_FALSE(consumed);
  27174. if (req.has_param("retry")) {
  27175. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27176. }
  27177. // Replace the 400 the aborted read set, which would close the connection.
  27178. res.set_redirect("/done");
  27179. });
  27180. auto port = svr.bind_to_any_port(HOST);
  27181. thread t = thread([&] { svr.listen_after_bind(); });
  27182. auto se = detail::scope_exit([&] {
  27183. svr.stop();
  27184. t.join();
  27185. });
  27186. svr.wait_until_ready();
  27187. // A front end sees the second request as a POST whose body is the GET. The
  27188. // first body is as long as the POST's headers, so draining it again reads
  27189. // exactly those and leaves the GET to be parsed next.
  27190. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27191. "Host: localhost\r\n"
  27192. "\r\n";
  27193. std::string second_head = "POST /post HTTP/1.1\r\n"
  27194. "Host: localhost\r\n"
  27195. "Content-Length: " +
  27196. std::to_string(inner.size()) +
  27197. "\r\n"
  27198. "\r\n";
  27199. for (auto target : {"/upload", "/upload?retry"}) {
  27200. smuggled_count = 0;
  27201. std::string request = "POST " + std::string(target) +
  27202. " HTTP/1.1\r\n"
  27203. "Host: localhost\r\n"
  27204. "Content-Length: " +
  27205. std::to_string(second_head.size()) +
  27206. "\r\n"
  27207. "\r\n" +
  27208. std::string(second_head.size(), 'A') + second_head +
  27209. inner;
  27210. std::string response;
  27211. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27212. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27213. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27214. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27215. EXPECT_EQ(0, smuggled_count.load()) << target;
  27216. }
  27217. }
  27218. // An error response closes the connection anyway, so the body is left unread
  27219. // with a redirect, such as one to a login page.
  27220. static void serve_redirects(Server &svr,
  27221. const std::function<void(int)> &client) {
  27222. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27223. res.set_redirect("/login");
  27224. return Server::HandlerResponse::Handled;
  27225. });
  27226. auto port = svr.bind_to_any_port(HOST);
  27227. ASSERT_GT(port, 0);
  27228. thread t = thread([&] { svr.listen_after_bind(); });
  27229. auto se = detail::scope_exit([&] {
  27230. svr.stop();
  27231. t.join();
  27232. ASSERT_FALSE(svr.is_running());
  27233. });
  27234. svr.wait_until_ready();
  27235. client(port);
  27236. }
  27237. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27238. Server svr;
  27239. serve_redirects(svr, [](int port) {
  27240. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27241. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27242. std::to_string(body.size()) + "\r\n\r\n" + body +
  27243. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27244. std::string resp;
  27245. ASSERT_TRUE(send_request(1, req, &resp, port));
  27246. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27247. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27248. });
  27249. }
  27250. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27251. Server svr;
  27252. svr.set_read_timeout(0, 200000);
  27253. serve_redirects(svr, [](int port) {
  27254. // A byte every 100 ms keeps each read within the read timeout, but not the
  27255. // body as a whole, so the server closes and the bytes sent after that fail.
  27256. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27257. "Content-Length: 10\r\n\r\n"};
  27258. parts.resize(11, "x");
  27259. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27260. });
  27261. }
  27262. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27263. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27264. // must be rejected with 400 Bad Request.
  27265. Server svr;
  27266. svr.Post("/test", [&](const Request &, Response &res) {
  27267. res.set_content("ok", "text/plain");
  27268. });
  27269. thread t = thread([&] { svr.listen(HOST, PORT); });
  27270. auto se = detail::scope_exit([&] {
  27271. svr.stop();
  27272. t.join();
  27273. ASSERT_FALSE(svr.is_running());
  27274. });
  27275. svr.wait_until_ready();
  27276. // Exact "chunked"
  27277. {
  27278. auto req = "POST /test HTTP/1.1\r\n"
  27279. "Host: localhost\r\n"
  27280. "Content-Length: 5\r\n"
  27281. "Transfer-Encoding: chunked\r\n"
  27282. "Connection: close\r\n"
  27283. "\r\n"
  27284. "hello";
  27285. std::string response;
  27286. ASSERT_TRUE(send_request(1, req, &response));
  27287. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27288. response.substr(0, response.find("\r\n")));
  27289. }
  27290. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27291. {
  27292. auto req = "POST /test HTTP/1.1\r\n"
  27293. "Host: localhost\r\n"
  27294. "Content-Length: 5\r\n"
  27295. "Transfer-Encoding: gzip, chunked\r\n"
  27296. "Connection: close\r\n"
  27297. "\r\n"
  27298. "hello";
  27299. std::string response;
  27300. ASSERT_TRUE(send_request(1, req, &response));
  27301. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27302. response.substr(0, response.find("\r\n")));
  27303. }
  27304. }
  27305. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27306. Server svr;
  27307. svr.Post("/test", [&](const Request &, Response &res) {
  27308. res.set_content("ok", "text/plain");
  27309. });
  27310. thread t = thread([&] { svr.listen(HOST, PORT); });
  27311. auto se = detail::scope_exit([&] {
  27312. svr.stop();
  27313. t.join();
  27314. ASSERT_FALSE(svr.is_running());
  27315. });
  27316. svr.wait_until_ready();
  27317. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27318. // length cannot be determined, so the server must answer 400 and close
  27319. // rather than treat the request as bodyless and leave the body in the
  27320. // socket for the next request to pick up.
  27321. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27322. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27323. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27324. std::string response;
  27325. ASSERT_TRUE(send_request(1, req, &response));
  27326. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27327. response.substr(0, response.find("\r\n")))
  27328. << transfer_encoding;
  27329. }
  27330. // RFC 9110 5.3: the codings may also be split across several
  27331. // Transfer-Encoding lines, which combine in the order they were received.
  27332. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27333. // just like the single-line "chunked, gzip" above.
  27334. {
  27335. auto req = "POST /test HTTP/1.1\r\n"
  27336. "Host: localhost\r\n"
  27337. "Transfer-Encoding: chunked\r\n"
  27338. "Transfer-Encoding: gzip\r\n"
  27339. "\r\n"
  27340. "0\r\n\r\n";
  27341. std::string response;
  27342. ASSERT_TRUE(send_request(1, req, &response));
  27343. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27344. response.substr(0, response.find("\r\n")));
  27345. }
  27346. }
  27347. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27348. Server svr;
  27349. svr.Post("/test", [&](const Request &, Response &res) {
  27350. res.set_content("ok", "text/plain");
  27351. });
  27352. auto port = svr.bind_to_any_port(HOST);
  27353. ASSERT_GT(port, 0);
  27354. thread t = thread([&] { svr.listen_after_bind(); });
  27355. auto se = detail::scope_exit([&] {
  27356. svr.stop();
  27357. t.join();
  27358. ASSERT_FALSE(svr.is_running());
  27359. });
  27360. svr.wait_until_ready();
  27361. for (auto transfer_encoding :
  27362. {"Transfer-Encoding: gzip, chunked\r\n",
  27363. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27364. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27365. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27366. transfer_encoding + "\r\n0\r\n\r\n";
  27367. std::string response;
  27368. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27369. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27370. response.substr(0, response.find("\r\n")))
  27371. << transfer_encoding;
  27372. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27373. << transfer_encoding;
  27374. }
  27375. }
  27376. // Regression for issue #2450: a DELETE without Content-Length on a
  27377. // keep-alive connection must not let the post-response drain consume the
  27378. // next request's bytes.
  27379. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27380. Server svr;
  27381. std::atomic<int> delete_count(0);
  27382. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27383. delete_count++;
  27384. res.status = StatusCode::NoContent_204;
  27385. });
  27386. auto port = svr.bind_to_any_port(HOST);
  27387. thread t = thread([&] { svr.listen_after_bind(); });
  27388. auto se = detail::scope_exit([&] {
  27389. svr.stop();
  27390. t.join();
  27391. });
  27392. svr.wait_until_ready();
  27393. auto error = Error::Success;
  27394. auto sock = detail::create_client_socket(
  27395. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27396. /*connection_timeout_sec=*/2, 0,
  27397. /*read_timeout_sec=*/2, 0,
  27398. /*write_timeout_sec=*/2, 0, std::string(), error);
  27399. ASSERT_NE(INVALID_SOCKET, sock);
  27400. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27401. auto send_request_and_read_response = [&](const std::string &req,
  27402. std::string &out) -> bool {
  27403. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27404. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27405. char buf[4096];
  27406. for (;;) {
  27407. auto n = recv(sock, buf, sizeof(buf), 0);
  27408. if (n <= 0) { return !out.empty(); }
  27409. out.append(buf, static_cast<size_t>(n));
  27410. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27411. }
  27412. };
  27413. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27414. "Host: localhost\r\n"
  27415. "\r\n";
  27416. std::string resp1;
  27417. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27418. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27419. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27420. "Host: localhost\r\n"
  27421. "Connection: close\r\n"
  27422. "\r\n";
  27423. std::string resp2;
  27424. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27425. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27426. EXPECT_EQ(2, delete_count.load());
  27427. }
  27428. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27429. Server svr;
  27430. svr.Post("/ingest", [&](const Request &, Response &res,
  27431. const ContentReader &content_reader) {
  27432. auto consumed = content_reader([](const char *, size_t) { return false; });
  27433. EXPECT_FALSE(consumed);
  27434. res.status = StatusCode::Conflict_409;
  27435. res.set_header("Connection", "close");
  27436. });
  27437. auto port = svr.bind_to_any_port(HOST);
  27438. thread t = thread([&] { svr.listen_after_bind(); });
  27439. auto se = detail::scope_exit([&] {
  27440. svr.stop();
  27441. t.join();
  27442. });
  27443. svr.wait_until_ready();
  27444. auto error = Error::Success;
  27445. auto sock = detail::create_client_socket(
  27446. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27447. /*connection_timeout_sec=*/2, 0,
  27448. /*read_timeout_sec=*/1, 0,
  27449. /*write_timeout_sec=*/2, 0, std::string(), error);
  27450. ASSERT_NE(INVALID_SOCKET, sock);
  27451. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27452. std::string request = "POST /ingest HTTP/1.1\r\n"
  27453. "Host: localhost\r\n"
  27454. "Transfer-Encoding: chunked\r\n"
  27455. "\r\n"
  27456. "4\r\n"
  27457. "data\r\n";
  27458. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27459. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27460. std::string response;
  27461. ssize_t received = 0;
  27462. do {
  27463. char buf[4096];
  27464. received = recv(sock, buf, sizeof(buf), 0);
  27465. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27466. } while (received > 0);
  27467. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27468. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27469. EXPECT_EQ(0, received);
  27470. }
  27471. namespace no_proxy_test {
  27472. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27473. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27474. // calling listen().
  27475. class ScopedServer {
  27476. public:
  27477. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27478. ~ScopedServer() {
  27479. svr_.stop();
  27480. if (th_.joinable()) { th_.join(); }
  27481. }
  27482. Server &svr() { return svr_; }
  27483. int port() const { return port_; }
  27484. void listen() {
  27485. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27486. svr_.wait_until_ready();
  27487. }
  27488. private:
  27489. Server svr_;
  27490. std::thread th_;
  27491. int port_ = 0;
  27492. };
  27493. class ProxyAndTargetServers {
  27494. public:
  27495. ProxyAndTargetServers() {
  27496. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27497. proxy_hits_++;
  27498. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27499. res.set_content("via-proxy", "text/plain");
  27500. });
  27501. target_.Get(".*", [this](const Request &req, Response &res) {
  27502. target_hits_++;
  27503. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27504. res.set_content("direct", "text/plain");
  27505. });
  27506. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27507. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27508. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27509. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27510. proxy_mock_.wait_until_ready();
  27511. target_.wait_until_ready();
  27512. }
  27513. ~ProxyAndTargetServers() {
  27514. proxy_mock_.stop();
  27515. target_.stop();
  27516. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27517. if (target_thread_.joinable()) { target_thread_.join(); }
  27518. }
  27519. Server &proxy_mock() { return proxy_mock_; }
  27520. Server &target() { return target_; }
  27521. int proxy_port() const { return proxy_port_; }
  27522. int target_port() const { return target_port_; }
  27523. int proxy_hits() const { return proxy_hits_.load(); }
  27524. int target_hits() const { return target_hits_.load(); }
  27525. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27526. void reset_counters() {
  27527. proxy_hits_ = 0;
  27528. target_hits_ = 0;
  27529. last_had_proxy_authz_ = false;
  27530. }
  27531. private:
  27532. Server proxy_mock_;
  27533. Server target_;
  27534. std::thread proxy_thread_;
  27535. std::thread target_thread_;
  27536. int proxy_port_ = 0;
  27537. int target_port_ = 0;
  27538. std::atomic<int> proxy_hits_{0};
  27539. std::atomic<int> target_hits_{0};
  27540. std::atomic<bool> last_had_proxy_authz_{false};
  27541. };
  27542. inline std::unique_ptr<Client> make_client(const std::string &host,
  27543. ProxyAndTargetServers &s) {
  27544. auto cli = detail::make_unique<Client>(host, s.target_port());
  27545. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27546. cli->set_proxy("127.0.0.1", s.proxy_port());
  27547. return cli;
  27548. }
  27549. } // namespace no_proxy_test
  27550. using no_proxy_test::make_client;
  27551. using no_proxy_test::ProxyAndTargetServers;
  27552. // A stream request carries the credentials a buffered request does
  27553. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27554. no_proxy_test::ScopedServer origin;
  27555. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27556. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27557. });
  27558. origin.listen();
  27559. Client cli("127.0.0.1", origin.port());
  27560. cli.set_basic_auth("user", "pass");
  27561. auto handle = cli.open_stream("GET", "/x");
  27562. ASSERT_TRUE(handle.is_valid());
  27563. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27564. Client bearer("127.0.0.1", origin.port());
  27565. bearer.set_bearer_token_auth("tok");
  27566. auto handle2 = bearer.open_stream("GET", "/x");
  27567. ASSERT_TRUE(handle2.is_valid());
  27568. EXPECT_EQ("Bearer tok", read_all(handle2));
  27569. }
  27570. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27571. // takes its own credentials, as for a buffered request
  27572. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27573. std::string target, authz, proxy_authz;
  27574. no_proxy_test::ScopedServer proxy;
  27575. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27576. target = req.target;
  27577. authz = req.get_header_value("Authorization");
  27578. proxy_authz = req.get_header_value("Proxy-Authorization");
  27579. res.set_content("ok", "text/plain");
  27580. });
  27581. proxy.listen();
  27582. Client cli("origin.example", 8080);
  27583. cli.set_proxy("127.0.0.1", proxy.port());
  27584. cli.set_proxy_basic_auth("puser", "ppass");
  27585. cli.set_basic_auth("user", "pass");
  27586. auto handle = cli.open_stream("GET", "/x");
  27587. ASSERT_TRUE(handle.is_valid());
  27588. EXPECT_EQ("ok", read_all(handle));
  27589. EXPECT_EQ("http://origin.example:8080/x", target);
  27590. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27591. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27592. }
  27593. // In absolute-form the path follows the authority, so a path that does not
  27594. // begin with '/' would make the proxy connect to another host
  27595. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27596. std::vector<std::string> targets;
  27597. no_proxy_test::ScopedServer proxy;
  27598. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27599. targets.push_back(req.target);
  27600. res.set_content("ok", "text/plain");
  27601. });
  27602. proxy.listen();
  27603. Client cli("origin.example", 8080);
  27604. cli.set_proxy("127.0.0.1", proxy.port());
  27605. cli.set_basic_auth("user", "pass");
  27606. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27607. auto res = cli.Get(path);
  27608. EXPECT_FALSE(res) << path;
  27609. auto handle = cli.open_stream("GET", path);
  27610. EXPECT_FALSE(handle.is_valid()) << path;
  27611. }
  27612. EXPECT_TRUE(targets.empty());
  27613. auto res = cli.Get("/x");
  27614. ASSERT_TRUE(res);
  27615. ASSERT_EQ(1u, targets.size());
  27616. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27617. }
  27618. TEST(NoProxyTest, ExactHostnameBypasses) {
  27619. ProxyAndTargetServers s;
  27620. auto cli = make_client("example.com", s);
  27621. cli->set_no_proxy({"example.com"});
  27622. auto res = cli->Get("/");
  27623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27624. EXPECT_EQ(0, s.proxy_hits());
  27625. EXPECT_EQ(1, s.target_hits());
  27626. }
  27627. TEST(NoProxyTest, SubdomainBypasses) {
  27628. ProxyAndTargetServers s;
  27629. auto cli = make_client("foo.example.com", s);
  27630. cli->set_no_proxy({"example.com"});
  27631. auto res = cli->Get("/");
  27632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27633. EXPECT_EQ(0, s.proxy_hits());
  27634. EXPECT_EQ(1, s.target_hits());
  27635. }
  27636. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27637. // Regression guard: "evilexample.com" must not be considered a subdomain
  27638. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27639. // check would let traffic bypass the proxy and leak credentials direct
  27640. // to the attacker host.
  27641. ProxyAndTargetServers s;
  27642. auto cli = make_client("evilexample.com", s);
  27643. cli->set_no_proxy({"example.com"});
  27644. auto res = cli->Get("/");
  27645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27646. EXPECT_GE(s.proxy_hits(), 1);
  27647. EXPECT_EQ(0, s.target_hits());
  27648. }
  27649. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27650. ProxyAndTargetServers s;
  27651. auto cli = make_client("example.com.evil.com", s);
  27652. cli->set_no_proxy({"example.com"});
  27653. auto res = cli->Get("/");
  27654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27655. EXPECT_GE(s.proxy_hits(), 1);
  27656. EXPECT_EQ(0, s.target_hits());
  27657. }
  27658. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27659. ProxyAndTargetServers s;
  27660. auto cli = make_client("example.com", s);
  27661. cli->set_no_proxy({".example.com"});
  27662. auto res = cli->Get("/");
  27663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27664. EXPECT_EQ(0, s.proxy_hits());
  27665. EXPECT_EQ(1, s.target_hits());
  27666. }
  27667. TEST(NoProxyTest, CaseInsensitiveHostname) {
  27668. ProxyAndTargetServers s;
  27669. auto cli = make_client("Example.COM", s);
  27670. cli->set_no_proxy({"EXAMPLE.com"});
  27671. auto res = cli->Get("/");
  27672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27673. EXPECT_EQ(0, s.proxy_hits());
  27674. EXPECT_EQ(1, s.target_hits());
  27675. }
  27676. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27677. ProxyAndTargetServers s;
  27678. auto cli = make_client("example.com.", s);
  27679. cli->set_no_proxy({"example.com"});
  27680. auto res = cli->Get("/");
  27681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27682. EXPECT_EQ(0, s.proxy_hits());
  27683. EXPECT_EQ(1, s.target_hits());
  27684. }
  27685. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27686. // Trailing dots must be normalized on BOTH sides — host and entry.
  27687. // An implementation that only strips the host-side trailing dot would
  27688. // fail to match host "example.com" against entry "example.com." because
  27689. // a literal substring search would compare 11 chars against 12.
  27690. ProxyAndTargetServers s;
  27691. auto cli = make_client("example.com", s);
  27692. cli->set_no_proxy({"example.com."});
  27693. auto res = cli->Get("/");
  27694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27695. EXPECT_EQ(0, s.proxy_hits());
  27696. EXPECT_EQ(1, s.target_hits());
  27697. }
  27698. TEST(NoProxyTest, WildcardBypassesEverything) {
  27699. ProxyAndTargetServers s;
  27700. auto cli = make_client("anything.invalid.test", s);
  27701. cli->set_no_proxy({"*"});
  27702. auto res = cli->Get("/");
  27703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27704. EXPECT_EQ(0, s.proxy_hits());
  27705. EXPECT_EQ(1, s.target_hits());
  27706. }
  27707. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  27708. ProxyAndTargetServers s;
  27709. Client cli("127.0.0.1", s.target_port());
  27710. cli.set_proxy("127.0.0.1", s.proxy_port());
  27711. cli.set_no_proxy({"127.0.0.1"});
  27712. auto res = cli.Get("/");
  27713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27714. EXPECT_EQ(0, s.proxy_hits());
  27715. EXPECT_EQ(1, s.target_hits());
  27716. }
  27717. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  27718. ProxyAndTargetServers s;
  27719. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  27720. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  27721. cli.set_proxy("127.0.0.1", s.proxy_port());
  27722. cli.set_no_proxy({"::1"});
  27723. auto res = cli.Get("/");
  27724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27725. EXPECT_EQ(0, s.proxy_hits());
  27726. EXPECT_EQ(1, s.target_hits());
  27727. }
  27728. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  27729. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  27730. // must still be recognized as IPv6 for CIDR matching. Implementations
  27731. // that detect IPv6 only when the host begins with '[' would parse the
  27732. // host as a hostname and miss the match.
  27733. ProxyAndTargetServers s;
  27734. Client cli("fe80::1", s.target_port());
  27735. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27736. cli.set_proxy("127.0.0.1", s.proxy_port());
  27737. cli.set_no_proxy({"fe80::/10"});
  27738. auto res = cli.Get("/");
  27739. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27740. EXPECT_EQ(0, s.proxy_hits());
  27741. EXPECT_EQ(1, s.target_hits());
  27742. }
  27743. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  27744. ProxyAndTargetServers s;
  27745. Client cli("::1", s.target_port());
  27746. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  27747. cli.set_proxy("127.0.0.1", s.proxy_port());
  27748. cli.set_no_proxy({"[::1]"});
  27749. auto res = cli.Get("/");
  27750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27751. EXPECT_EQ(0, s.proxy_hits());
  27752. EXPECT_EQ(1, s.target_hits());
  27753. }
  27754. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  27755. ProxyAndTargetServers s;
  27756. Client cli("fe80::1", s.target_port());
  27757. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  27758. cli.set_proxy("127.0.0.1", s.proxy_port());
  27759. cli.set_no_proxy({"[fe80::]/10"});
  27760. auto res = cli.Get("/");
  27761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27762. EXPECT_EQ(0, s.proxy_hits());
  27763. EXPECT_EQ(1, s.target_hits());
  27764. }
  27765. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  27766. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  27767. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  27768. // tricks via address-family conversion.
  27769. ProxyAndTargetServers s;
  27770. Client cli("::ffff:127.0.0.1", s.target_port());
  27771. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  27772. cli.set_proxy("127.0.0.1", s.proxy_port());
  27773. cli.set_no_proxy({"127.0.0.1"});
  27774. auto res = cli.Get("/");
  27775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27776. EXPECT_GE(s.proxy_hits(), 1);
  27777. EXPECT_EQ(0, s.target_hits());
  27778. }
  27779. TEST(NoProxyTest, IPv4CidrMatch) {
  27780. ProxyAndTargetServers s;
  27781. Client cli("127.0.0.1", s.target_port());
  27782. cli.set_proxy("127.0.0.1", s.proxy_port());
  27783. cli.set_no_proxy({"127.0.0.0/8"});
  27784. auto res = cli.Get("/");
  27785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27786. EXPECT_EQ(0, s.proxy_hits());
  27787. EXPECT_EQ(1, s.target_hits());
  27788. }
  27789. TEST(NoProxyTest, IPv4CidrNonMatch) {
  27790. ProxyAndTargetServers s;
  27791. Client cli("127.0.0.1", s.target_port());
  27792. cli.set_proxy("127.0.0.1", s.proxy_port());
  27793. cli.set_no_proxy({"10.0.0.0/8"});
  27794. auto res = cli.Get("/");
  27795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27796. EXPECT_GE(s.proxy_hits(), 1);
  27797. EXPECT_EQ(0, s.target_hits());
  27798. }
  27799. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  27800. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  27801. // IPv4 target matches.
  27802. ProxyAndTargetServers s;
  27803. Client cli("127.0.0.1", s.target_port());
  27804. cli.set_proxy("127.0.0.1", s.proxy_port());
  27805. cli.set_no_proxy({"0.0.0.0/0"});
  27806. auto res = cli.Get("/");
  27807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27808. EXPECT_EQ(0, s.proxy_hits());
  27809. EXPECT_EQ(1, s.target_hits());
  27810. }
  27811. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  27812. ProxyAndTargetServers s;
  27813. Client cli("127.0.0.1", s.target_port());
  27814. cli.set_proxy("127.0.0.1", s.proxy_port());
  27815. cli.set_no_proxy({"127.0.0.1"});
  27816. auto res = cli.Get("/");
  27817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27818. EXPECT_EQ(0, s.proxy_hits());
  27819. EXPECT_EQ(1, s.target_hits());
  27820. }
  27821. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  27822. ProxyAndTargetServers s;
  27823. Client cli("127.0.0.1", s.target_port());
  27824. cli.set_proxy("127.0.0.1", s.proxy_port());
  27825. cli.set_no_proxy({"127.0.0.0/33"});
  27826. auto res = cli.Get("/");
  27827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27828. EXPECT_GE(s.proxy_hits(), 1);
  27829. EXPECT_EQ(0, s.target_hits());
  27830. }
  27831. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  27832. // Empty prefix after the slash must be rejected, not silently treated as /32.
  27833. ProxyAndTargetServers s;
  27834. Client cli("127.0.0.1", s.target_port());
  27835. cli.set_proxy("127.0.0.1", s.proxy_port());
  27836. cli.set_no_proxy({"127.0.0.1/"});
  27837. auto res = cli.Get("/");
  27838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27839. EXPECT_GE(s.proxy_hits(), 1);
  27840. EXPECT_EQ(0, s.target_hits());
  27841. }
  27842. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  27843. ProxyAndTargetServers s;
  27844. auto cli = make_client("internal.corp", s);
  27845. cli->set_proxy_basic_auth("u", "p");
  27846. cli->set_no_proxy({"internal.corp"});
  27847. auto res = cli->Get("/");
  27848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27849. EXPECT_EQ(1, s.target_hits());
  27850. EXPECT_EQ(0, s.proxy_hits());
  27851. EXPECT_FALSE(s.last_had_proxy_authz())
  27852. << "Proxy-Authorization must not be sent direct to the target";
  27853. }
  27854. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  27855. ProxyAndTargetServers s;
  27856. auto cli = make_client("public.example", s);
  27857. cli->set_proxy_basic_auth("u", "p");
  27858. cli->set_no_proxy({"internal.corp"}); // does not match
  27859. auto res = cli->Get("/");
  27860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27861. EXPECT_GE(s.proxy_hits(), 1);
  27862. EXPECT_TRUE(s.last_had_proxy_authz());
  27863. }
  27864. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  27865. std::atomic<int> hits{0};
  27866. std::atomic<int> hits_with_authz{0};
  27867. no_proxy_test::ScopedServer proxy_mock;
  27868. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  27869. hits++;
  27870. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  27871. if (req.target.find("/redir") != std::string::npos) {
  27872. res.set_redirect("http://other.example/landed");
  27873. } else {
  27874. res.set_content("via-proxy", "text/plain");
  27875. }
  27876. });
  27877. proxy_mock.listen();
  27878. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  27879. hits = 0;
  27880. hits_with_authz = 0;
  27881. Client cli("public.example", 80);
  27882. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27883. cli.set_proxy_basic_auth(c.first, c.second);
  27884. cli.set_follow_location(true);
  27885. // The redirect to another host goes through the proxy as well
  27886. auto res = cli.Get("/redir");
  27887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27888. EXPECT_EQ(2, hits.load());
  27889. EXPECT_EQ(2, hits_with_authz.load());
  27890. }
  27891. }
  27892. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  27893. ProxyAndTargetServers s;
  27894. auto cli = make_client("anything.test", s);
  27895. auto res = cli->Get("/");
  27896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27897. EXPECT_GE(s.proxy_hits(), 1);
  27898. EXPECT_EQ(0, s.target_hits());
  27899. }
  27900. TEST(NoProxyTest, PortSpecificEntryRejected) {
  27901. ProxyAndTargetServers s;
  27902. auto cli = make_client("example.com", s);
  27903. cli->set_no_proxy({"example.com:8080"});
  27904. auto res = cli->Get("/");
  27905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27906. EXPECT_GE(s.proxy_hits(), 1);
  27907. EXPECT_EQ(0, s.target_hits());
  27908. }
  27909. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  27910. ProxyAndTargetServers s;
  27911. auto cli = make_client("anything.test", s);
  27912. cli->set_no_proxy({"", " ", "\t"});
  27913. auto res = cli->Get("/");
  27914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27915. EXPECT_GE(s.proxy_hits(), 1);
  27916. EXPECT_EQ(0, s.target_hits());
  27917. }
  27918. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  27919. // An entry with leading/trailing whitespace must still match — env-style
  27920. // values are commonly pasted with stray spaces and an implementation
  27921. // that feeds the raw token directly to inet_pton would fail to match
  27922. // valid CIDRs because of the spaces.
  27923. ProxyAndTargetServers s;
  27924. Client cli("127.0.0.1", s.target_port());
  27925. cli.set_proxy("127.0.0.1", s.proxy_port());
  27926. cli.set_no_proxy({" 127.0.0.0/8 "});
  27927. auto res = cli.Get("/");
  27928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27929. EXPECT_EQ(0, s.proxy_hits());
  27930. EXPECT_EQ(1, s.target_hits());
  27931. }
  27932. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  27933. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  27934. // go direct and must NOT carry Proxy-Authorization.
  27935. std::atomic<int> proxy_hits{0};
  27936. std::atomic<int> target_hits{0};
  27937. std::atomic<bool> target_saw_authz{false};
  27938. no_proxy_test::ScopedServer proxy_mock, target;
  27939. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  27940. proxy_hits++;
  27941. res.status = 302;
  27942. res.set_header("Location", "http://127.0.0.1:" +
  27943. std::to_string(target.port()) + "/landed");
  27944. });
  27945. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27946. target_hits++;
  27947. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  27948. res.set_content("direct", "text/plain");
  27949. });
  27950. proxy_mock.listen();
  27951. target.listen();
  27952. Client cli("public.example", target.port());
  27953. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  27954. cli.set_proxy("127.0.0.1", proxy_mock.port());
  27955. cli.set_proxy_basic_auth("u", "p");
  27956. cli.set_no_proxy({"127.0.0.1"});
  27957. cli.set_follow_location(true);
  27958. auto res = cli.Get("/redir");
  27959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27960. EXPECT_GE(proxy_hits.load(), 1);
  27961. EXPECT_GE(target_hits.load(), 1);
  27962. EXPECT_FALSE(target_saw_authz.load());
  27963. }
  27964. #ifdef CPPHTTPLIB_SSL_ENABLED
  27965. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  27966. // Direct origin replying 407 must not trigger the digest retry; otherwise
  27967. // proxy creds would be sent to the (possibly hostile) origin.
  27968. std::atomic<int> target_hits{0};
  27969. std::atomic<bool> target_saw_proxy_authz{false};
  27970. no_proxy_test::ScopedServer target;
  27971. target.svr().Get(".*", [&](const Request &req, Response &res) {
  27972. target_hits++;
  27973. if (req.has_header("Proxy-Authorization")) {
  27974. target_saw_proxy_authz = true;
  27975. }
  27976. res.status = StatusCode::ProxyAuthenticationRequired_407;
  27977. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  27978. "nonce=\"abc\", algorithm=MD5");
  27979. });
  27980. target.listen();
  27981. // The proxy address is set to the target's port: the bypass MUST kick in;
  27982. // if it doesn't, the test still routes "via proxy" to the same server and
  27983. // the Proxy-Authorization assertion below catches the leak.
  27984. Client cli("evil.example", target.port());
  27985. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  27986. cli.set_proxy("127.0.0.1", target.port());
  27987. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27988. cli.set_no_proxy({"evil.example"});
  27989. auto res = cli.Get("/x");
  27990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27991. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  27992. EXPECT_EQ(1, target_hits.load());
  27993. EXPECT_FALSE(target_saw_proxy_authz.load());
  27994. }
  27995. #endif
  27996. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  27997. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  27998. std::atomic<int> proxy_hits{0};
  27999. std::atomic<int> bypass_hits{0};
  28000. std::atomic<bool> proxy_saw_c_url{false};
  28001. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  28002. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28003. proxy_hits++;
  28004. if (req.path.find("/start") != std::string::npos) {
  28005. res.status = 302;
  28006. res.set_header("Location", "http://127.0.0.1:" +
  28007. std::to_string(bypass_server.port()) +
  28008. "/middle");
  28009. return;
  28010. }
  28011. if (req.path.find("/end") != std::string::npos) {
  28012. proxy_saw_c_url = true;
  28013. res.set_content("c-via-proxy", "text/plain");
  28014. return;
  28015. }
  28016. res.set_content("unexpected", "text/plain");
  28017. });
  28018. // public.example's "advertised" port is arbitrary (the request never lands
  28019. // there — it goes through the proxy), but use a dynamic value to stay
  28020. // friendly with sharded parallel runs.
  28021. int public_port = bypass_server.port();
  28022. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  28023. bypass_hits++;
  28024. res.status = 302;
  28025. res.set_header("Location", "http://public.example:" +
  28026. std::to_string(public_port) + "/end");
  28027. });
  28028. proxy_mock.listen();
  28029. bypass_server.listen();
  28030. Client cli("public.example", public_port);
  28031. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28032. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28033. cli.set_no_proxy({"127.0.0.1"});
  28034. cli.set_follow_location(true);
  28035. auto res = cli.Get("/start");
  28036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28037. EXPECT_EQ(StatusCode::OK_200, res->status);
  28038. EXPECT_EQ("c-via-proxy", res->body);
  28039. EXPECT_GE(proxy_hits.load(), 2);
  28040. EXPECT_GE(bypass_hits.load(), 1);
  28041. EXPECT_TRUE(proxy_saw_c_url.load());
  28042. }
  28043. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  28044. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  28045. // request reconnects to the correct endpoint.
  28046. std::atomic<int> proxy_hits{0};
  28047. std::atomic<int> target_hits{0};
  28048. no_proxy_test::ScopedServer proxy_mock, target;
  28049. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28050. proxy_hits++;
  28051. res.set_content("via-proxy", "text/plain");
  28052. });
  28053. target.svr().Get(".*", [&](const Request &, Response &res) {
  28054. target_hits++;
  28055. res.set_content("direct", "text/plain");
  28056. });
  28057. proxy_mock.listen();
  28058. target.listen();
  28059. Client cli("public.example", target.port());
  28060. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28061. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28062. cli.set_keep_alive(true);
  28063. auto res1 = cli.Get("/a");
  28064. ASSERT_TRUE(res1);
  28065. EXPECT_EQ("via-proxy", res1->body);
  28066. EXPECT_EQ(1, proxy_hits.load());
  28067. EXPECT_EQ(0, target_hits.load());
  28068. cli.set_no_proxy({"public.example"});
  28069. auto res2 = cli.Get("/b");
  28070. ASSERT_TRUE(res2);
  28071. EXPECT_EQ("direct", res2->body);
  28072. EXPECT_EQ(1, proxy_hits.load());
  28073. EXPECT_EQ(1, target_hits.load());
  28074. }
  28075. // Forward declarations (see the base64_encode note).
  28076. namespace httplib {
  28077. namespace detail {
  28078. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  28079. int shutdown_socket(socket_t sock) noexcept;
  28080. } // namespace detail
  28081. } // namespace httplib
  28082. namespace proxy_tunnel_test {
  28083. const char *const kTunnelEstablished =
  28084. "HTTP/1.1 200 Connection established\r\n\r\n";
  28085. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  28086. using ConnectReply = std::function<std::string(const std::string &head)>;
  28087. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  28088. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  28089. class ScopedConnectProxy {
  28090. public:
  28091. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  28092. : forward_port_(forward_port), reply_(std::move(reply)) {
  28093. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  28094. if (listen_sock_ == INVALID_SOCKET) { return; }
  28095. auto a = loopback(0);
  28096. auto addr = reinterpret_cast<sockaddr *>(&a);
  28097. socklen_t alen = sizeof(a);
  28098. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  28099. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  28100. ::listen(listen_sock_, 4) != 0) {
  28101. return;
  28102. }
  28103. port_ = ntohs(a.sin_port);
  28104. th_ = std::thread([this] { run(); });
  28105. }
  28106. ~ScopedConnectProxy() {
  28107. if (th_.joinable()) {
  28108. stop_ = true;
  28109. auto wake = connect_to(port_);
  28110. th_.join();
  28111. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28112. }
  28113. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28114. }
  28115. int port() const { return port_; }
  28116. int connect_hits() const { return connect_hits_.load(); }
  28117. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28118. std::string connect_request() const {
  28119. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28120. return connect_request_;
  28121. }
  28122. private:
  28123. static sockaddr_in loopback(int port) {
  28124. sockaddr_in a{};
  28125. a.sin_family = AF_INET;
  28126. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28127. a.sin_port = htons(static_cast<unsigned short>(port));
  28128. return a;
  28129. }
  28130. static socket_t connect_to(int port) {
  28131. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28132. if (sock == INVALID_SOCKET) { return sock; }
  28133. auto a = loopback(port);
  28134. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28135. detail::close_socket(sock);
  28136. return INVALID_SOCKET;
  28137. }
  28138. return sock;
  28139. }
  28140. static bool send_all(socket_t sock, const char *data, size_t size) {
  28141. while (size > 0) {
  28142. auto n = detail::send_socket(sock, data, size, 0);
  28143. if (n <= 0) { return false; }
  28144. data += n;
  28145. size -= static_cast<size_t>(n);
  28146. }
  28147. return true;
  28148. }
  28149. void run() {
  28150. for (;;) {
  28151. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28152. if (stop_) {
  28153. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28154. return;
  28155. }
  28156. if (client == INVALID_SOCKET) { continue; }
  28157. serve(client);
  28158. detail::close_socket(client);
  28159. }
  28160. }
  28161. void serve(socket_t client) {
  28162. std::string head;
  28163. char buf[2048];
  28164. while (head.find("\r\n\r\n") == std::string::npos) {
  28165. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28166. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28167. if (n <= 0) { return; }
  28168. head.append(buf, static_cast<size_t>(n));
  28169. }
  28170. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28171. connect_hits_++;
  28172. {
  28173. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28174. connect_request_ = head;
  28175. }
  28176. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28177. if (!send_all(client, res.data(), res.size()) ||
  28178. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28179. return;
  28180. }
  28181. auto origin = connect_to(forward_port_);
  28182. if (origin == INVALID_SOCKET) { return; }
  28183. // When either side stops, shut both down so the other pump returns too.
  28184. auto pump = [&](socket_t from, socket_t to) {
  28185. char b[8192];
  28186. for (;;) {
  28187. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28188. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28189. }
  28190. detail::shutdown_socket(client);
  28191. detail::shutdown_socket(origin);
  28192. };
  28193. std::thread up([&] { pump(client, origin); });
  28194. pump(origin, client);
  28195. up.join();
  28196. detail::close_socket(origin);
  28197. }
  28198. int forward_port_;
  28199. ConnectReply reply_;
  28200. socket_t listen_sock_ = INVALID_SOCKET;
  28201. int port_ = 0;
  28202. std::thread th_;
  28203. std::atomic<bool> stop_{false};
  28204. std::atomic<int> connect_hits_{0};
  28205. mutable std::mutex connect_request_mutex_;
  28206. std::string connect_request_;
  28207. };
  28208. } // namespace proxy_tunnel_test
  28209. #ifdef CPPHTTPLIB_SSL_ENABLED
  28210. namespace proxy_tunnel_test {
  28211. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28212. class ScopedSSLServer {
  28213. public:
  28214. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28215. port_ = svr_.bind_to_any_port("127.0.0.1");
  28216. }
  28217. ~ScopedSSLServer() {
  28218. svr_.stop();
  28219. if (th_.joinable()) { th_.join(); }
  28220. }
  28221. SSLServer &svr() { return svr_; }
  28222. int port() const { return port_; }
  28223. void listen() {
  28224. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28225. svr_.wait_until_ready();
  28226. }
  28227. private:
  28228. SSLServer svr_;
  28229. std::thread th_;
  28230. int port_ = 0;
  28231. };
  28232. // Sends one request through the CONNECT proxy to the TLS origin with a
  28233. // credential configured for each hop, and checks that each credential reaches
  28234. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28235. // origin's (every header in origin_headers) on the tunnelled request.
  28236. void CredentialsStayWithTheirHop(
  28237. const std::function<void(SSLClient &)> &set_credentials,
  28238. const std::string &scheme,
  28239. const std::vector<std::string> &origin_headers = {"Authorization"},
  28240. bool stream = false) {
  28241. std::atomic<int> origin_hits{0};
  28242. std::atomic<bool> origin_saw_proxy_authz{false};
  28243. std::atomic<bool> origin_saw_headers{false};
  28244. ScopedSSLServer origin;
  28245. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28246. origin_hits++;
  28247. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28248. origin_saw_headers =
  28249. std::all_of(origin_headers.begin(), origin_headers.end(),
  28250. [&](const std::string &h) { return req.has_header(h); });
  28251. res.set_content("ok", "text/plain");
  28252. });
  28253. origin.listen();
  28254. ScopedConnectProxy proxy(origin.port());
  28255. ASSERT_NE(0, proxy.port());
  28256. // Pinned to 127.0.0.1 for the same reason as the test below.
  28257. SSLClient cli("127.0.0.1", origin.port());
  28258. cli.enable_server_certificate_verification(false);
  28259. cli.set_proxy("127.0.0.1", proxy.port());
  28260. set_credentials(cli);
  28261. if (stream) {
  28262. auto handle = cli.open_stream("GET", "/x");
  28263. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28264. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28265. } else {
  28266. auto res = cli.Get("/x");
  28267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28268. EXPECT_EQ(StatusCode::OK_200, res->status);
  28269. }
  28270. EXPECT_EQ(1, origin_hits.load());
  28271. EXPECT_EQ(1, proxy.connect_hits());
  28272. EXPECT_TRUE(origin_saw_headers.load());
  28273. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28274. << "Proxy-Authorization must not be sent inside the tunnel";
  28275. auto connect_req = proxy.connect_request();
  28276. EXPECT_NE(std::string::npos,
  28277. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28278. for (const auto &h : origin_headers) {
  28279. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28280. << h << " must not be sent to the proxy on CONNECT";
  28281. }
  28282. }
  28283. } // namespace proxy_tunnel_test
  28284. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28285. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28286. [](SSLClient &cli) {
  28287. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28288. cli.set_basic_auth("origin-user", "origin-pass");
  28289. },
  28290. "Basic");
  28291. }
  28292. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28293. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28294. [](SSLClient &cli) {
  28295. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28296. cli.set_basic_auth("origin-user", "origin-pass");
  28297. },
  28298. "Basic", {"Authorization"}, true);
  28299. }
  28300. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28301. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28302. [](SSLClient &cli) {
  28303. cli.set_proxy_bearer_token_auth("proxy-token");
  28304. cli.set_bearer_token_auth("origin-token");
  28305. },
  28306. "Bearer");
  28307. }
  28308. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28309. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28310. [](SSLClient &cli) {
  28311. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28312. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28313. {"Cookie", "sid=origin-session"},
  28314. {"X-Api-Key", "origin-key"}});
  28315. },
  28316. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28317. }
  28318. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28319. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28320. // retry; otherwise proxy creds would be sent to the origin.
  28321. std::atomic<int> origin_hits{0};
  28322. std::atomic<bool> origin_saw_proxy_authz{false};
  28323. proxy_tunnel_test::ScopedSSLServer origin;
  28324. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28325. origin_hits++;
  28326. if (req.has_header("Proxy-Authorization")) {
  28327. origin_saw_proxy_authz = true;
  28328. }
  28329. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28330. res.set_header("Proxy-Authenticate",
  28331. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28332. "algorithm=MD5");
  28333. });
  28334. origin.listen();
  28335. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28336. ASSERT_NE(0, proxy.port());
  28337. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28338. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28339. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28340. // and answer with its own status, making this test flaky.
  28341. SSLClient cli("127.0.0.1", origin.port());
  28342. cli.enable_server_certificate_verification(false);
  28343. cli.set_proxy("127.0.0.1", proxy.port());
  28344. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28345. auto res = cli.Get("/x");
  28346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28347. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28348. EXPECT_EQ(1, origin_hits.load());
  28349. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28350. EXPECT_EQ(1, proxy.connect_hits());
  28351. }
  28352. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28353. std::string origin_sni;
  28354. std::string origin_host;
  28355. proxy_tunnel_test::ScopedSSLServer origin;
  28356. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28357. origin_sni = req.sni();
  28358. origin_host = req.get_header_value("Host");
  28359. res.set_content("ok", "text/plain");
  28360. });
  28361. origin.listen();
  28362. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28363. ASSERT_NE(0, proxy.port());
  28364. SSLClient cli("origin.example", origin.port());
  28365. cli.enable_server_certificate_verification(false);
  28366. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28367. cli.set_proxy("127.0.0.1", proxy.port());
  28368. auto res = cli.Get("/x");
  28369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28370. EXPECT_EQ(StatusCode::OK_200, res->status);
  28371. auto port = std::to_string(origin.port());
  28372. auto target = "127.0.0.1:" + port;
  28373. auto connect_req = proxy.connect_request();
  28374. EXPECT_EQ(1, proxy.connect_hits());
  28375. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28376. EXPECT_NE(std::string::npos,
  28377. connect_req.find("\r\nHost: " + target + "\r\n"));
  28378. EXPECT_EQ("origin.example", origin_sni);
  28379. EXPECT_EQ("origin.example:" + port, origin_host);
  28380. }
  28381. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28382. proxy_tunnel_test::ScopedSSLServer origin;
  28383. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28384. res.set_content("ok", "text/plain");
  28385. });
  28386. origin.listen();
  28387. proxy_tunnel_test::ScopedConnectProxy proxy(
  28388. origin.port(), [](const std::string &head) -> std::string {
  28389. if (head.find(
  28390. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28391. std::string::npos) {
  28392. return proxy_tunnel_test::kTunnelEstablished;
  28393. }
  28394. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28395. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28396. "nonce=\"abc\", algorithm=MD5\r\n"
  28397. "Content-Length: 0\r\n\r\n";
  28398. });
  28399. ASSERT_NE(0, proxy.port());
  28400. SSLClient cli("origin.example", origin.port());
  28401. cli.enable_server_certificate_verification(false);
  28402. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28403. cli.set_proxy("127.0.0.1", proxy.port());
  28404. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28405. auto res = cli.Get("/x");
  28406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28407. EXPECT_EQ(StatusCode::OK_200, res->status);
  28408. // The retried CONNECT is the one the proxy saw last.
  28409. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28410. auto connect_req = proxy.connect_request();
  28411. EXPECT_EQ(2, proxy.connect_hits());
  28412. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28413. EXPECT_NE(std::string::npos,
  28414. connect_req.find("\r\nHost: " + target + "\r\n"));
  28415. }
  28416. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28417. proxy_tunnel_test::ScopedSSLServer origin;
  28418. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28419. res.set_content("ok", "text/plain");
  28420. });
  28421. origin.listen();
  28422. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28423. ASSERT_NE(0, proxy.port());
  28424. SSLClient cli("origin.example", origin.port());
  28425. cli.enable_server_certificate_verification(false);
  28426. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28427. cli.set_proxy("127.0.0.1", proxy.port());
  28428. auto res = cli.Get("/x");
  28429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28430. EXPECT_EQ(StatusCode::OK_200, res->status);
  28431. auto target = "origin.example:" + std::to_string(origin.port());
  28432. auto connect_req = proxy.connect_request();
  28433. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28434. EXPECT_NE(std::string::npos,
  28435. connect_req.find("\r\nHost: " + target + "\r\n"));
  28436. }
  28437. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28438. proxy_tunnel_test::ScopedSSLServer origin;
  28439. auto port = std::to_string(origin.port());
  28440. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28441. res.set_redirect("https://next.example:" + port + "/y");
  28442. });
  28443. origin.svr().Get("/y", [](const Request &, Response &res) {
  28444. res.set_content("ok", "text/plain");
  28445. });
  28446. origin.listen();
  28447. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28448. ASSERT_NE(0, proxy.port());
  28449. SSLClient cli("origin.example", origin.port());
  28450. cli.enable_server_certificate_verification(false);
  28451. cli.set_tunnel_hostname_addr_map(
  28452. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28453. cli.set_proxy("127.0.0.1", proxy.port());
  28454. cli.set_follow_location(true);
  28455. auto res = cli.Get("/x");
  28456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28457. EXPECT_EQ("ok", res->body);
  28458. // The last CONNECT is the redirect client's.
  28459. ASSERT_EQ(2, proxy.connect_hits());
  28460. auto target = "127.0.0.1:" + port;
  28461. auto connect_req = proxy.connect_request();
  28462. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28463. EXPECT_NE(std::string::npos,
  28464. connect_req.find("\r\nHost: " + target + "\r\n"));
  28465. }
  28466. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28467. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28468. std::atomic<int> origin_hits{0};
  28469. proxy_tunnel_test::ScopedSSLServer origin;
  28470. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28471. origin_hits++;
  28472. res.set_content("ok", "text/plain");
  28473. });
  28474. origin.listen();
  28475. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28476. ASSERT_NE(0, proxy.port());
  28477. SSLClient cli("127.0.0.1", origin.port());
  28478. cli.enable_server_certificate_verification(false);
  28479. cli.set_proxy("127.0.0.1", proxy.port());
  28480. cli.set_keep_alive(true);
  28481. cli.set_session_verifier(
  28482. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28483. auto res = cli.Get("/x");
  28484. EXPECT_FALSE(res);
  28485. ASSERT_FALSE(cli.is_socket_open());
  28486. res = cli.Get("/x");
  28487. EXPECT_FALSE(res);
  28488. EXPECT_EQ(2, proxy.connect_hits());
  28489. auto handle = cli.open_stream("GET", "/x");
  28490. EXPECT_FALSE(handle.is_valid());
  28491. EXPECT_EQ(3, proxy.connect_hits());
  28492. EXPECT_EQ(0, origin_hits.load());
  28493. }
  28494. #endif
  28495. namespace proxy_tunnel_test {
  28496. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28497. // anything else gets a 407 with `challenge`.
  28498. ConnectReply require_proxy_auth(const std::string &expected,
  28499. const std::string &challenge) {
  28500. return [=](const std::string &head) -> std::string {
  28501. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28502. std::string::npos) {
  28503. return kTunnelEstablished;
  28504. }
  28505. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28506. "Proxy-Authenticate: " +
  28507. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28508. };
  28509. }
  28510. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28511. // request, then echoes.
  28512. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28513. ws.send(
  28514. "authorization:" + req.get_header_value("Authorization") +
  28515. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28516. std::string msg;
  28517. while (ws.read(msg)) {
  28518. ws.send(msg);
  28519. }
  28520. }
  28521. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28522. class ScopedWebSocketOrigin {
  28523. public:
  28524. ScopedWebSocketOrigin() {
  28525. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28526. server_.listen();
  28527. }
  28528. int port() const { return server_.port(); }
  28529. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28530. std::string url() const {
  28531. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28532. }
  28533. private:
  28534. no_proxy_test::ScopedServer server_;
  28535. };
  28536. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28537. // passed as a constructor header, and checks that each reaches only its hop.
  28538. void WebSocketCredentialsStayWithTheirHop(
  28539. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28540. const std::string &proxy_authz, const std::string &origin_authz) {
  28541. ScopedWebSocketOrigin origin;
  28542. ScopedConnectProxy proxy(
  28543. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28544. ASSERT_NE(0, proxy.port());
  28545. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28546. client.set_proxy("127.0.0.1", proxy.port());
  28547. set_proxy_credentials(client);
  28548. auto res = client.connect();
  28549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28550. std::string msg;
  28551. ASSERT_TRUE(client.read(msg));
  28552. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28553. client.close();
  28554. EXPECT_EQ(1, proxy.connect_hits());
  28555. EXPECT_EQ(std::string::npos,
  28556. proxy.connect_request().find("\r\nAuthorization: "))
  28557. << "origin credentials must not be sent to the proxy";
  28558. }
  28559. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28560. void WebSocketSetterCredentialsStayWithTheirHop(
  28561. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28562. const std::string &proxy_authz, const std::string &origin_authz) {
  28563. ScopedWebSocketOrigin origin;
  28564. ScopedConnectProxy proxy(
  28565. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28566. ASSERT_NE(0, proxy.port());
  28567. ws::WebSocketClient client(origin.url());
  28568. client.set_proxy("127.0.0.1", proxy.port());
  28569. set_credentials(client);
  28570. auto res = client.connect();
  28571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28572. std::string msg;
  28573. ASSERT_TRUE(client.read(msg));
  28574. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28575. client.close();
  28576. EXPECT_EQ(1, proxy.connect_hits());
  28577. EXPECT_EQ(std::string::npos,
  28578. proxy.connect_request().find("\r\nAuthorization: "))
  28579. << "origin credentials must not be sent to the proxy";
  28580. }
  28581. } // namespace proxy_tunnel_test
  28582. namespace {
  28583. // Connects `client` and returns the Authorization header its upgrade
  28584. // request carried, or "<failed>" when the connection could not be opened.
  28585. std::string websocket_authorization(ws::WebSocketClient &client) {
  28586. if (!client.connect()) { return "<failed>"; }
  28587. std::string msg;
  28588. if (!client.read(msg)) { return "<failed>"; }
  28589. client.close();
  28590. auto prefix = std::string("authorization:");
  28591. auto end = msg.find("|proxy-authorization:");
  28592. return msg.substr(prefix.size(), end - prefix.size());
  28593. }
  28594. } // namespace
  28595. TEST(WebSocketClientAuthTest, BasicAuth) {
  28596. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28597. ws::WebSocketClient client(origin.url());
  28598. client.set_basic_auth("user", "pass");
  28599. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28600. websocket_authorization(client));
  28601. }
  28602. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28603. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28604. ws::WebSocketClient client(origin.url());
  28605. client.set_basic_auth("user", "");
  28606. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28607. websocket_authorization(client));
  28608. }
  28609. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28610. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28611. ws::WebSocketClient client(origin.url());
  28612. client.set_bearer_token_auth("token123");
  28613. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28614. }
  28615. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28616. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28617. ws::WebSocketClient client(origin.url());
  28618. client.set_bearer_token_auth("token123");
  28619. client.set_basic_auth("user", "pass");
  28620. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28621. websocket_authorization(client));
  28622. }
  28623. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28624. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28625. ws::WebSocketClient client(origin.url(),
  28626. {{"Authorization", "Bearer from-header"}});
  28627. client.set_bearer_token_auth("from-setter");
  28628. client.set_basic_auth("user", "pass");
  28629. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28630. }
  28631. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28632. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28633. ws::WebSocketClient client(origin.url());
  28634. EXPECT_EQ("", websocket_authorization(client));
  28635. client.set_bearer_token_auth("first");
  28636. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28637. client.set_bearer_token_auth("second");
  28638. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28639. client.set_bearer_token_auth("");
  28640. EXPECT_EQ("", websocket_authorization(client));
  28641. }
  28642. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28643. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28644. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28645. ASSERT_NE(0, proxy.port());
  28646. ws::WebSocketClient client(origin.url());
  28647. client.set_proxy("127.0.0.1", proxy.port());
  28648. auto res = client.connect();
  28649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28650. std::string msg;
  28651. ASSERT_TRUE(client.read(msg));
  28652. ASSERT_TRUE(client.send("hello"));
  28653. ASSERT_TRUE(client.read(msg));
  28654. EXPECT_EQ("hello", msg);
  28655. client.close();
  28656. EXPECT_EQ(1, proxy.connect_hits());
  28657. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28658. auto connect_req = proxy.connect_request();
  28659. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28660. EXPECT_NE(std::string::npos,
  28661. connect_req.find("\r\nHost: " + target + "\r\n"));
  28662. }
  28663. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28664. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28665. [](ws::WebSocketClient &cli) {
  28666. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28667. },
  28668. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28669. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28670. }
  28671. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28672. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28673. [](ws::WebSocketClient &cli) {
  28674. cli.set_proxy_bearer_token_auth("proxy-token");
  28675. },
  28676. "Bearer proxy-token", "Bearer origin-token");
  28677. }
  28678. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28679. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28680. [](ws::WebSocketClient &cli) {
  28681. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28682. cli.set_basic_auth("origin-user", "origin-pass");
  28683. },
  28684. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28685. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28686. }
  28687. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28688. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28689. [](ws::WebSocketClient &cli) {
  28690. cli.set_proxy_bearer_token_auth("proxy-token");
  28691. cli.set_bearer_token_auth("origin-token");
  28692. },
  28693. "Bearer proxy-token", "Bearer origin-token");
  28694. }
  28695. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  28696. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28697. proxy_tunnel_test::ScopedConnectProxy proxy(
  28698. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28699. "Basic " + detail::base64_encode("proxy-user:"),
  28700. "Basic realm=\"proxy\""));
  28701. ASSERT_NE(0, proxy.port());
  28702. ws::WebSocketClient client(origin.url());
  28703. client.set_proxy("127.0.0.1", proxy.port());
  28704. client.set_proxy_basic_auth("proxy-user", "");
  28705. auto res = client.connect();
  28706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28707. client.close();
  28708. EXPECT_EQ(1, proxy.connect_hits());
  28709. }
  28710. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  28711. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28712. proxy_tunnel_test::ScopedConnectProxy proxy(
  28713. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28714. "Bearer proxy-token", "Basic realm=\"proxy\""));
  28715. ASSERT_NE(0, proxy.port());
  28716. ws::WebSocketClient client(origin.url());
  28717. client.set_proxy("127.0.0.1", proxy.port());
  28718. auto res = client.connect();
  28719. EXPECT_FALSE(res);
  28720. EXPECT_EQ(Error::ProxyConnection, res.error());
  28721. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  28722. EXPECT_EQ("Basic realm=\"proxy\"",
  28723. res.get_header_value("Proxy-Authenticate"));
  28724. EXPECT_FALSE(client.is_open());
  28725. }
  28726. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  28727. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28728. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28729. ASSERT_NE(0, proxy.port());
  28730. ws::WebSocketClient client(origin.url());
  28731. client.set_proxy("127.0.0.1", proxy.port());
  28732. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28733. client.set_no_proxy({"127.0.0.1"});
  28734. auto res = client.connect();
  28735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28736. std::string msg;
  28737. ASSERT_TRUE(client.read(msg));
  28738. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28739. << "proxy credentials must not reach a bypassed origin";
  28740. client.close();
  28741. EXPECT_EQ(0, proxy.connect_hits());
  28742. }
  28743. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  28744. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28745. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28746. ASSERT_NE(0, proxy.port());
  28747. ws::WebSocketClient client(origin.url());
  28748. client.set_proxy("127.0.0.1", proxy.port());
  28749. ASSERT_TRUE(client.connect());
  28750. ASSERT_TRUE(client.connect());
  28751. client.close();
  28752. EXPECT_EQ(2, proxy.connect_hits());
  28753. }
  28754. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28755. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28756. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28757. ASSERT_NE(0, proxy.port());
  28758. auto port = std::to_string(origin.port());
  28759. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28760. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28761. client.set_proxy("127.0.0.1", proxy.port());
  28762. auto res = client.connect();
  28763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28764. std::string msg;
  28765. ASSERT_TRUE(client.read(msg));
  28766. client.close();
  28767. EXPECT_EQ(1, proxy.connect_hits());
  28768. auto target = "127.0.0.1:" + port;
  28769. auto connect_req = proxy.connect_request();
  28770. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28771. EXPECT_NE(std::string::npos,
  28772. connect_req.find("\r\nHost: " + target + "\r\n"));
  28773. }
  28774. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28775. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28776. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28777. ASSERT_NE(0, proxy.port());
  28778. auto port = std::to_string(origin.port());
  28779. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  28780. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28781. client.set_proxy("127.0.0.1", proxy.port());
  28782. auto res = client.connect();
  28783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28784. client.close();
  28785. auto target = "origin.example:" + port;
  28786. auto connect_req = proxy.connect_request();
  28787. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28788. EXPECT_NE(std::string::npos,
  28789. connect_req.find("\r\nHost: " + target + "\r\n"));
  28790. }
  28791. #ifdef CPPHTTPLIB_SSL_ENABLED
  28792. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  28793. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28794. proxy_tunnel_test::ScopedConnectProxy proxy(
  28795. origin.port(), [](const std::string &head) -> std::string {
  28796. if (head.find(
  28797. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28798. std::string::npos) {
  28799. return proxy_tunnel_test::kTunnelEstablished;
  28800. }
  28801. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28802. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28803. "nonce=\"abc\", algorithm=MD5\r\n"
  28804. "Content-Length: 0\r\n\r\n";
  28805. });
  28806. ASSERT_NE(0, proxy.port());
  28807. ws::WebSocketClient client(origin.url());
  28808. client.set_proxy("127.0.0.1", proxy.port());
  28809. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28810. auto res = client.connect();
  28811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28812. std::string msg;
  28813. ASSERT_TRUE(client.read(msg));
  28814. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  28815. client.close();
  28816. EXPECT_EQ(2, proxy.connect_hits());
  28817. }
  28818. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  28819. proxy_tunnel_test::ScopedSSLServer origin;
  28820. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  28821. origin.listen();
  28822. proxy_tunnel_test::ScopedConnectProxy proxy(
  28823. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28824. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  28825. ASSERT_NE(0, proxy.port());
  28826. ws::WebSocketClient client(
  28827. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  28828. client.enable_server_certificate_verification(false);
  28829. client.set_proxy("127.0.0.1", proxy.port());
  28830. client.set_proxy_bearer_token_auth("proxy-token");
  28831. auto res = client.connect();
  28832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28833. std::string msg;
  28834. ASSERT_TRUE(client.read(msg));
  28835. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  28836. << "Proxy-Authorization must not be sent inside the tunnel";
  28837. client.close();
  28838. EXPECT_EQ(1, proxy.connect_hits());
  28839. }
  28840. #endif
  28841. // ---------------------------------------------------------------------------
  28842. // Poller
  28843. // ---------------------------------------------------------------------------
  28844. namespace poller_test {
  28845. struct PollerBackend {
  28846. const char *name;
  28847. std::unique_ptr<detail::Poller> (*create)();
  28848. };
  28849. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  28850. *os << backend.name;
  28851. }
  28852. // Every backend runs the same contract tests. A new one is added here only.
  28853. std::vector<PollerBackend> poller_backends() {
  28854. return {
  28855. {"poll", &detail::PollPoller::create},
  28856. #ifdef __linux__
  28857. {"epoll", &detail::EpollPoller::create},
  28858. #endif
  28859. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  28860. {"kqueue", &detail::KqueuePoller::create},
  28861. #endif
  28862. };
  28863. }
  28864. // A descriptor whose readability the test controls.
  28865. struct TestSocketPair {
  28866. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  28867. TestSocketPair() { detail::create_socket_pair(fd); }
  28868. ~TestSocketPair() {
  28869. for (auto s : fd) {
  28870. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  28871. }
  28872. }
  28873. bool ok() const { return fd[0] != INVALID_SOCKET; }
  28874. socket_t reader() const { return fd[0]; }
  28875. void make_readable() {
  28876. const char c = 1;
  28877. detail::send_socket(fd[1], &c, 1, 0);
  28878. }
  28879. void close_writer() {
  28880. detail::close_socket(fd[1]);
  28881. fd[1] = INVALID_SOCKET;
  28882. }
  28883. };
  28884. using Tokens = std::vector<detail::Poller::Token>;
  28885. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  28886. protected:
  28887. void SetUp() override {
  28888. poller_ = GetParam().create();
  28889. ASSERT_TRUE(poller_ != nullptr);
  28890. }
  28891. Tokens wait_for(int timeout_ms) {
  28892. Tokens ready;
  28893. poller_->wait(timeout_ms, ready);
  28894. std::sort(ready.begin(), ready.end());
  28895. return ready;
  28896. }
  28897. std::unique_ptr<detail::Poller> poller_;
  28898. };
  28899. } // namespace poller_test
  28900. using poller_test::PollerTest;
  28901. using poller_test::TestSocketPair;
  28902. using poller_test::Tokens;
  28903. INSTANTIATE_TEST_SUITE_P(
  28904. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  28905. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  28906. return std::string(p.param.name);
  28907. });
  28908. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  28909. TestSocketPair sp;
  28910. ASSERT_TRUE(sp.ok());
  28911. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  28912. EXPECT_EQ(Tokens{}, wait_for(0));
  28913. sp.make_readable();
  28914. EXPECT_EQ(Tokens{7}, wait_for(1000));
  28915. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  28916. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  28917. EXPECT_EQ(Tokens{8}, wait_for(1000));
  28918. }
  28919. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  28920. TestSocketPair sp;
  28921. ASSERT_TRUE(sp.ok());
  28922. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28923. poller_->disarm(sp.reader());
  28924. poller_->disarm(sp.reader()); // disarming twice is harmless
  28925. sp.make_readable();
  28926. EXPECT_EQ(Tokens{}, wait_for(0));
  28927. }
  28928. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  28929. TestSocketPair sp;
  28930. ASSERT_TRUE(sp.ok());
  28931. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  28932. auto start = std::chrono::steady_clock::now();
  28933. EXPECT_EQ(Tokens{}, wait_for(30));
  28934. auto elapsed = std::chrono::steady_clock::now() - start;
  28935. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  28936. EXPECT_LT(elapsed, std::chrono::seconds(1));
  28937. }
  28938. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  28939. std::vector<std::unique_ptr<TestSocketPair>> sps;
  28940. for (detail::Poller::Token i = 0; i < 8; i++) {
  28941. sps.emplace_back(new TestSocketPair());
  28942. ASSERT_TRUE(sps.back()->ok());
  28943. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  28944. }
  28945. sps[0]->make_readable();
  28946. sps[3]->make_readable();
  28947. sps[7]->make_readable();
  28948. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  28949. // The others are still armed, the delivered ones are not.
  28950. sps[1]->make_readable();
  28951. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28952. EXPECT_EQ(Tokens{}, wait_for(0));
  28953. }
  28954. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  28955. TestSocketPair s0, s1, s2;
  28956. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  28957. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  28958. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  28959. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  28960. // A delivery may move another entry inside the poller.
  28961. s0.make_readable();
  28962. EXPECT_EQ(Tokens{0}, wait_for(1000));
  28963. // The entries left must still be found by descriptor.
  28964. poller_->disarm(s2.reader());
  28965. s1.make_readable();
  28966. s2.make_readable();
  28967. EXPECT_EQ(Tokens{1}, wait_for(1000));
  28968. }
  28969. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  28970. TestSocketPair sp;
  28971. ASSERT_TRUE(sp.ok());
  28972. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  28973. sp.close_writer();
  28974. EXPECT_EQ(Tokens{5}, wait_for(1000));
  28975. char c;
  28976. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  28977. }
  28978. TEST_P(PollerTest, WakeEndsABlockedWait) {
  28979. std::thread waker([&] {
  28980. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  28981. poller_->wake();
  28982. });
  28983. Tokens ready;
  28984. auto start = std::chrono::steady_clock::now();
  28985. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  28986. waker.join();
  28987. EXPECT_TRUE(ready.empty());
  28988. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  28989. }
  28990. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  28991. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  28992. Tokens ready;
  28993. EXPECT_TRUE(poller_->wait(1000, ready));
  28994. }
  28995. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  28996. for (int i = 0; i < 1000; i++) {
  28997. poller_->wake();
  28998. }
  28999. Tokens ready;
  29000. EXPECT_TRUE(poller_->wait(0, ready));
  29001. EXPECT_FALSE(poller_->wait(0, ready));
  29002. poller_->wake();
  29003. EXPECT_TRUE(poller_->wait(0, ready));
  29004. }
  29005. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  29006. // Two threads publish changes and wake() after each, as a reactor's workers
  29007. // do. Every change must be seen without a wait() timing out. A lost wake()
  29008. // needs an unlucky interleaving, hence the rounds.
  29009. for (int round = 0; round < 5; round++) {
  29010. SCOPED_TRACE(round);
  29011. const int per_thread = 20000;
  29012. std::atomic<int> posted{0};
  29013. auto post = [&] {
  29014. for (int i = 0; i < per_thread; i++) {
  29015. posted++;
  29016. poller_->wake();
  29017. }
  29018. };
  29019. std::thread t1(post), t2(post);
  29020. auto lost = false;
  29021. Tokens ready;
  29022. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  29023. if (!poller_->wait(1000, ready)) {
  29024. lost = true;
  29025. break;
  29026. }
  29027. }
  29028. t1.join();
  29029. t2.join();
  29030. ASSERT_FALSE(lost);
  29031. }
  29032. }
  29033. TEST(PollerFactoryTest, MakePollerWorks) {
  29034. auto poller = detail::make_poller();
  29035. ASSERT_TRUE(poller != nullptr);
  29036. poller->wake();
  29037. std::vector<detail::Poller::Token> ready;
  29038. EXPECT_TRUE(poller->wait(1000, ready));
  29039. }
  29040. // ---------------------------------------------------------------------------
  29041. // Keep-alive parking
  29042. // ---------------------------------------------------------------------------
  29043. namespace parking_test {
  29044. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  29045. // runs once the port is bound and listening, before the server accepts.
  29046. struct RunningServer {
  29047. explicit RunningServer(
  29048. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  29049. : svr_(svr) {
  29050. port = svr_.bind_to_any_port("127.0.0.1");
  29051. if (before_listen) { before_listen(port); }
  29052. thread = std::thread([this] { svr_.listen_after_bind(); });
  29053. svr_.wait_until_ready();
  29054. }
  29055. ~RunningServer() {
  29056. svr_.stop();
  29057. if (thread.joinable()) { thread.join(); }
  29058. }
  29059. Server &svr_;
  29060. int port = 0;
  29061. std::thread thread;
  29062. };
  29063. struct Sockets {
  29064. std::vector<socket_t> socks;
  29065. ~Sockets() {
  29066. for (auto s : socks) {
  29067. detail::close_socket(s);
  29068. }
  29069. }
  29070. socket_t connect(int port) {
  29071. auto error = Error::Success;
  29072. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  29073. false, false, nullptr, 2, 0, 2, 0, 2,
  29074. 0, std::string(), error);
  29075. if (s != INVALID_SOCKET) { socks.push_back(s); }
  29076. return s;
  29077. }
  29078. };
  29079. std::chrono::steady_clock::time_point in_ms(int ms) {
  29080. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  29081. }
  29082. bool readable_by(socket_t sock,
  29083. std::chrono::steady_clock::time_point deadline) {
  29084. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  29085. deadline - std::chrono::steady_clock::now())
  29086. .count();
  29087. return left > 0 && detail::select_read(sock, 0, left) > 0;
  29088. }
  29089. bool send_get(socket_t sock, const std::string &path = "/") {
  29090. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  29091. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  29092. static_cast<ssize_t>(req.size());
  29093. }
  29094. // Reads one response whose body is "ok".
  29095. bool receives_ok(socket_t sock, int timeout_ms) {
  29096. auto deadline = in_ms(timeout_ms);
  29097. std::string buf;
  29098. while (readable_by(sock, deadline)) {
  29099. char tmp[1024];
  29100. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  29101. if (n <= 0) { return false; }
  29102. buf.append(tmp, static_cast<size_t>(n));
  29103. auto end = buf.find("\r\n\r\n");
  29104. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  29105. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  29106. buf.compare(end + 4, 2, "ok") == 0;
  29107. }
  29108. }
  29109. return false;
  29110. }
  29111. bool get_ok(socket_t sock, int timeout_ms) {
  29112. return send_get(sock) && receives_ok(sock, timeout_ms);
  29113. }
  29114. // Whether the server closes `sock` by `deadline`.
  29115. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29116. char c;
  29117. return readable_by(sock, deadline) &&
  29118. detail::read_socket(sock, &c, 1, 0) <= 0;
  29119. }
  29120. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29121. auto deadline = in_ms(timeout_ms);
  29122. while (!cond()) {
  29123. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29124. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29125. }
  29126. return true;
  29127. }
  29128. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29129. svr.new_task_queue = std::move(new_task_queue);
  29130. svr.set_keep_alive_parking(true);
  29131. svr.Get("/", [](const Request &, Response &res) {
  29132. res.set_content("ok", "text/plain");
  29133. });
  29134. }
  29135. std::function<TaskQueue *(void)> threads(size_t n) {
  29136. return [n] { return new ThreadPool(n); };
  29137. }
  29138. // Counts what the event loop managed to queue, so that a test can wait for it.
  29139. class CountingTaskQueue final : public TaskQueue {
  29140. public:
  29141. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29142. std::atomic<int> &full)
  29143. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29144. bool enqueue(std::function<void()> fn) override {
  29145. auto queued = pool_.enqueue([this, fn]() {
  29146. fn();
  29147. // Holds the worker back from taking the next job.
  29148. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29149. });
  29150. (queued ? ok_ : full_)++;
  29151. return queued;
  29152. }
  29153. void shutdown() override { pool_.shutdown(); }
  29154. std::atomic<int> pause_after_ms{0};
  29155. private:
  29156. ThreadPool pool_;
  29157. std::atomic<int> &ok_;
  29158. std::atomic<int> &full_;
  29159. };
  29160. // Holds handlers until it opens, or for 3 seconds at most.
  29161. class Gate {
  29162. public:
  29163. void wait() {
  29164. std::unique_lock<std::mutex> lock(m_);
  29165. entered_++;
  29166. cv_.notify_all();
  29167. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29168. }
  29169. void open() {
  29170. std::lock_guard<std::mutex> guard(m_);
  29171. open_ = true;
  29172. cv_.notify_all();
  29173. }
  29174. int entered() {
  29175. std::lock_guard<std::mutex> guard(m_);
  29176. return entered_;
  29177. }
  29178. private:
  29179. std::mutex m_;
  29180. std::condition_variable cv_;
  29181. bool open_ = false;
  29182. int entered_ = 0;
  29183. };
  29184. } // namespace parking_test
  29185. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29186. using namespace parking_test;
  29187. Server svr;
  29188. serve_ok(svr, threads(1));
  29189. RunningServer running(svr);
  29190. Sockets socks;
  29191. // One kept-alive connection that has been served, and many that have not
  29192. // sent anything yet. None of them may keep the only worker.
  29193. auto served = socks.connect(running.port);
  29194. ASSERT_TRUE(get_ok(served, 2000));
  29195. for (int i = 0; i < 49; i++) {
  29196. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29197. }
  29198. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29199. EXPECT_TRUE(get_ok(served, 1000));
  29200. }
  29201. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29202. using namespace parking_test;
  29203. Server svr;
  29204. serve_ok(svr, threads(1));
  29205. svr.set_keep_alive_timeout(1);
  29206. RunningServer running(svr);
  29207. Sockets socks;
  29208. for (int i = 0; i < 3; i++) {
  29209. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29210. }
  29211. // One worker waiting on each in turn would take about 3 seconds.
  29212. auto deadline = in_ms(2000);
  29213. for (auto s : socks.socks) {
  29214. EXPECT_TRUE(sees_eof(s, deadline));
  29215. }
  29216. }
  29217. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29218. using namespace parking_test;
  29219. std::atomic<int> queued{0}, full{0};
  29220. Server svr;
  29221. // One worker and room for one queued task.
  29222. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29223. Gate gate;
  29224. svr.Get("/block", [&](const Request &, Response &res) {
  29225. gate.wait();
  29226. res.set_content("ok", "text/plain");
  29227. });
  29228. RunningServer running(svr);
  29229. // Before the server stops, so that a failed run does not wait for the
  29230. // handler's timeout.
  29231. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29232. Sockets socks;
  29233. auto a = socks.connect(running.port);
  29234. ASSERT_TRUE(get_ok(a, 2000));
  29235. // B keeps the only worker busy.
  29236. auto b = socks.connect(running.port);
  29237. ASSERT_TRUE(send_get(b, "/block"));
  29238. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29239. // A new connection C fills the queue.
  29240. auto c = socks.connect(running.port);
  29241. ASSERT_TRUE(send_get(c));
  29242. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29243. // A's next request finds the queue full, but A has been served before, so it
  29244. // waits instead of being cut off.
  29245. ASSERT_TRUE(send_get(a));
  29246. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29247. gate.open();
  29248. EXPECT_TRUE(receives_ok(b, 2000));
  29249. EXPECT_TRUE(receives_ok(c, 2000));
  29250. EXPECT_TRUE(receives_ok(a, 2000));
  29251. }
  29252. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29253. using namespace parking_test;
  29254. std::atomic<int> queued{0}, full{0};
  29255. CountingTaskQueue *queue = nullptr;
  29256. Server svr;
  29257. // Two workers and room for one queued task.
  29258. serve_ok(svr,
  29259. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29260. Gate first, second;
  29261. svr.Get("/first", [&](const Request &, Response &res) {
  29262. first.wait();
  29263. res.set_content("ok", "text/plain");
  29264. });
  29265. svr.Get("/second", [&](const Request &, Response &res) {
  29266. second.wait();
  29267. res.set_content("ok", "text/plain");
  29268. });
  29269. RunningServer running(svr);
  29270. auto open_gates = detail::scope_exit([&] {
  29271. first.open();
  29272. second.open();
  29273. });
  29274. Sockets socks;
  29275. auto a = socks.connect(running.port);
  29276. ASSERT_TRUE(get_ok(a, 2000));
  29277. // B and D take both workers, and C fills the queue. One at a time: the
  29278. // queue has room for one job only until a worker takes it.
  29279. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29280. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29281. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29282. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29283. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29284. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29285. // A's next request waits in the backlog.
  29286. ASSERT_TRUE(send_get(a));
  29287. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29288. // B's worker finishes, then takes C off the queue only later, which makes
  29289. // room for A.
  29290. queue->pause_after_ms = 200;
  29291. first.open();
  29292. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29293. queue->pause_after_ms = 0;
  29294. second.open();
  29295. EXPECT_TRUE(receives_ok(a, 2000));
  29296. }
  29297. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29298. using namespace parking_test;
  29299. Server svr;
  29300. serve_ok(svr, threads(1));
  29301. svr.set_keep_alive_timeout(0);
  29302. // The request is on the socket before the server accepts the connection,
  29303. // so it does not race the 10 ms floor. Without the floor the connection is
  29304. // closed unread.
  29305. Sockets socks;
  29306. auto sock = INVALID_SOCKET;
  29307. RunningServer running(svr, [&](int port) {
  29308. sock = socks.connect(port);
  29309. send_get(sock);
  29310. });
  29311. EXPECT_TRUE(receives_ok(sock, 1000));
  29312. }
  29313. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29314. using namespace parking_test;
  29315. for (int round = 0; round < 5; round++) {
  29316. SCOPED_TRACE(round);
  29317. Server svr;
  29318. serve_ok(svr, threads(2));
  29319. RunningServer running(svr);
  29320. Sockets socks;
  29321. for (int i = 0; i < 20; i++) {
  29322. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29323. }
  29324. auto start = std::chrono::steady_clock::now();
  29325. svr.stop();
  29326. running.thread.join();
  29327. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29328. std::chrono::milliseconds(500));
  29329. auto deadline = in_ms(1000);
  29330. for (auto s : socks.socks) {
  29331. EXPECT_TRUE(sees_eof(s, deadline));
  29332. }
  29333. }
  29334. }
  29335. #ifdef CPPHTTPLIB_SSL_ENABLED
  29336. namespace parking_test {
  29337. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29338. // that has opened a connection ahead of time. Freeing the session sends no
  29339. // close_notify, so the connection stays quiet.
  29340. bool handshake_only(socket_t sock) {
  29341. auto ctx = tls::create_client_context();
  29342. tls::set_verify_client(ctx, false);
  29343. auto session = tls::create_session(ctx, sock);
  29344. auto se = detail::scope_exit([&] {
  29345. tls::free_session(session);
  29346. tls::free_context(ctx);
  29347. });
  29348. tls::TlsError err;
  29349. return session &&
  29350. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29351. }
  29352. Client tls_client(int port) {
  29353. Client cli("https://127.0.0.1:" + std::to_string(port));
  29354. cli.enable_server_certificate_verification(false);
  29355. cli.set_keep_alive(true);
  29356. cli.set_connection_timeout(1);
  29357. cli.set_read_timeout(1);
  29358. return cli;
  29359. }
  29360. bool tls_get_ok(Client &cli) {
  29361. auto res = cli.Get("/");
  29362. return res && res->body == "ok";
  29363. }
  29364. } // namespace parking_test
  29365. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29366. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29367. struct {
  29368. unsigned long version;
  29369. bool safe;
  29370. } cases[] = {
  29371. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29372. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29373. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29374. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29375. };
  29376. for (const auto &c : cases) {
  29377. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29378. << std::hex << c.version;
  29379. }
  29380. }
  29381. #endif
  29382. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29383. using namespace parking_test;
  29384. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29385. ASSERT_TRUE(svr.is_valid());
  29386. serve_ok(svr, threads(1));
  29387. svr.set_read_timeout(1); // so that a failing run does not take long
  29388. RunningServer running(svr);
  29389. Sockets socks;
  29390. // One served connection, some that have not started their handshake, and
  29391. // one that has finished it and gone quiet. None may keep the only worker.
  29392. auto served = tls_client(running.port);
  29393. ASSERT_TRUE(tls_get_ok(served));
  29394. for (int i = 0; i < 10; i++) {
  29395. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29396. }
  29397. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29398. auto other = tls_client(running.port);
  29399. EXPECT_TRUE(tls_get_ok(other));
  29400. EXPECT_TRUE(tls_get_ok(served));
  29401. }
  29402. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29403. using namespace parking_test;
  29404. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29405. ASSERT_TRUE(svr.is_valid());
  29406. serve_ok(svr, threads(1));
  29407. RunningServer running(svr);
  29408. Sockets socks;
  29409. auto plain = socks.connect(running.port);
  29410. ASSERT_TRUE(send_get(plain));
  29411. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29412. EXPECT_NE(0, svr.ssl_last_error());
  29413. }
  29414. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29415. using namespace parking_test;
  29416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29417. ASSERT_TRUE(svr.is_valid());
  29418. serve_ok(svr, threads(2));
  29419. RunningServer running(svr);
  29420. std::vector<Client> clients;
  29421. for (int i = 0; i < 5; i++) {
  29422. clients.push_back(tls_client(running.port));
  29423. ASSERT_TRUE(tls_get_ok(clients.back()));
  29424. }
  29425. auto start = std::chrono::steady_clock::now();
  29426. svr.stop();
  29427. running.thread.join();
  29428. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29429. std::chrono::milliseconds(500));
  29430. }
  29431. #endif