test.cc 1.0 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015
  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. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  71. namespace impl {
  72. SecTrustSettingsResult
  73. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  74. } // namespace impl
  75. #endif
  76. } // namespace tls
  77. } // namespace httplib
  78. #endif
  79. using namespace std;
  80. using namespace httplib;
  81. const char *HOST = "localhost";
  82. static int get_base_port() {
  83. const char *shard = getenv("GTEST_SHARD_INDEX");
  84. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  85. }
  86. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  87. // New standalone tests MUST use svr.bind_to_any_port() instead.
  88. const int PORT = get_base_port();
  89. const string LONG_QUERY_VALUE = string(25000, '@');
  90. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  91. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  92. const string TOO_LONG_QUERY_URL =
  93. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  94. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  95. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  96. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  97. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  98. return file.name == key;
  99. });
  100. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  101. return *it;
  102. #else
  103. if (it != items.end()) { return *it; }
  104. throw std::runtime_error("invalid multipart form data name error");
  105. #endif
  106. }
  107. static void read_file(const std::string &path, std::string &out) {
  108. std::ifstream fs(path, std::ios_base::binary);
  109. if (!fs) {
  110. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  111. return;
  112. #else
  113. throw std::runtime_error("File not found: " + path);
  114. #endif
  115. }
  116. fs.seekg(0, std::ios_base::end);
  117. auto size = fs.tellg();
  118. fs.seekg(0);
  119. out.resize(static_cast<size_t>(size));
  120. fs.read(&out[0], static_cast<std::streamsize>(size));
  121. }
  122. class UnixSocketTest : public ::testing::Test {
  123. protected:
  124. void TearDown() override { std::remove(pathname_.c_str()); }
  125. void client_GET(const std::string &addr) {
  126. httplib::Client cli{addr};
  127. cli.set_address_family(AF_UNIX);
  128. ASSERT_TRUE(cli.is_valid());
  129. const auto &result = cli.Get(pattern_);
  130. ASSERT_TRUE(result) << "error: " << result.error();
  131. const auto &resp = result.value();
  132. EXPECT_EQ(resp.status, StatusCode::OK_200);
  133. EXPECT_EQ(resp.body, content_);
  134. }
  135. static std::string make_sock_path() {
  136. const char *shard = getenv("GTEST_SHARD_INDEX");
  137. return shard ? std::string("./httplib-server-") + shard + ".sock"
  138. : "./httplib-server.sock";
  139. }
  140. const std::string pathname_{make_sock_path()};
  141. const std::string pattern_{"/hi"};
  142. const std::string content_{"Hello World!"};
  143. };
  144. TEST_F(UnixSocketTest, pathname) {
  145. httplib::Server svr;
  146. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  147. res.set_content(content_, "text/plain");
  148. });
  149. std::thread t{[&] {
  150. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  151. }};
  152. auto se = detail::scope_exit([&] {
  153. svr.stop();
  154. t.join();
  155. ASSERT_FALSE(svr.is_running());
  156. });
  157. svr.wait_until_ready();
  158. ASSERT_TRUE(svr.is_running());
  159. client_GET(pathname_);
  160. // ".//x.sock", which is not taken for a URL
  161. client_GET("./" + pathname_.substr(1));
  162. }
  163. #if defined(__linux__) || \
  164. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  165. TEST_F(UnixSocketTest, PeerPid) {
  166. httplib::Server svr;
  167. std::string remote_port_val;
  168. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  169. res.set_content(content_, "text/plain");
  170. remote_port_val = std::to_string(req.remote_port);
  171. });
  172. std::thread t{[&] {
  173. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  174. }};
  175. auto se = detail::scope_exit([&] {
  176. svr.stop();
  177. t.join();
  178. ASSERT_FALSE(svr.is_running());
  179. });
  180. svr.wait_until_ready();
  181. ASSERT_TRUE(svr.is_running());
  182. client_GET(pathname_);
  183. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  184. }
  185. #endif
  186. #ifdef __linux__
  187. TEST_F(UnixSocketTest, abstract) {
  188. constexpr char svr_path[]{"\x00httplib-server.sock"};
  189. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  190. httplib::Server svr;
  191. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  192. res.set_content(content_, "text/plain");
  193. });
  194. std::thread t{[&] {
  195. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  196. }};
  197. auto se = detail::scope_exit([&] {
  198. svr.stop();
  199. t.join();
  200. ASSERT_FALSE(svr.is_running());
  201. });
  202. svr.wait_until_ready();
  203. ASSERT_TRUE(svr.is_running());
  204. client_GET(abstract_addr);
  205. }
  206. #endif
  207. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  208. httplib::Server svr;
  209. std::string received_host_header;
  210. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  211. // Capture the Host header sent by the client
  212. auto host_iter = req.headers.find("Host");
  213. if (host_iter != req.headers.end()) {
  214. received_host_header = host_iter->second;
  215. }
  216. res.set_content(content_, "text/plain");
  217. });
  218. std::thread t{[&] {
  219. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  220. }};
  221. auto se = detail::scope_exit([&] {
  222. svr.stop();
  223. t.join();
  224. ASSERT_FALSE(svr.is_running());
  225. });
  226. svr.wait_until_ready();
  227. ASSERT_TRUE(svr.is_running());
  228. // Test that Host header is automatically set to "localhost" for Unix socket
  229. // connections
  230. httplib::Client cli{pathname_};
  231. cli.set_address_family(AF_UNIX);
  232. ASSERT_TRUE(cli.is_valid());
  233. const auto &result = cli.Get(pattern_);
  234. ASSERT_TRUE(result) << "error: " << result.error();
  235. const auto &resp = result.value();
  236. EXPECT_EQ(resp.status, StatusCode::OK_200);
  237. EXPECT_EQ(resp.body, content_);
  238. // Verify that Host header was automatically set to "localhost"
  239. EXPECT_EQ(received_host_header, "localhost");
  240. }
  241. #ifndef _WIN32
  242. TEST(SocketStream, wait_writable_UNIX) {
  243. int fds[2];
  244. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  245. const auto asSocketStream = [&](socket_t fd,
  246. std::function<bool(Stream &)> func) {
  247. return detail::process_client_socket(
  248. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  249. };
  250. asSocketStream(fds[0], [&](Stream &s0) {
  251. EXPECT_EQ(s0.socket(), fds[0]);
  252. EXPECT_TRUE(s0.wait_writable());
  253. EXPECT_TRUE(s0.is_peer_alive());
  254. EXPECT_EQ(0, close(fds[1]));
  255. EXPECT_FALSE(s0.is_peer_alive());
  256. return true;
  257. });
  258. EXPECT_EQ(0, close(fds[0]));
  259. }
  260. TEST(SocketStream, wait_writable_INET) {
  261. sockaddr_in addr;
  262. memset(&addr, 0, sizeof(addr));
  263. addr.sin_family = AF_INET;
  264. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  265. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  266. int disconnected_svr_sock = -1;
  267. std::thread svr{[&] {
  268. const int s = socket(AF_INET, SOCK_STREAM, 0);
  269. ASSERT_LE(0, s);
  270. // PORT + 1 is shared with the SSL redirect tests and with
  271. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  272. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  273. // because that happens on a worker thread the ASSERT does not stop the
  274. // test: it runs on and fails at the disconnected_svr_sock check instead.
  275. default_socket_options(s);
  276. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  277. ASSERT_EQ(0, listen(s, 1));
  278. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  282. std::thread cli{[&] {
  283. const int s = socket(AF_INET, SOCK_STREAM, 0);
  284. ASSERT_LE(0, s);
  285. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  286. ASSERT_EQ(0, close(s));
  287. }};
  288. cli.join();
  289. svr.join();
  290. ASSERT_NE(disconnected_svr_sock, -1);
  291. const auto asSocketStream = [&](socket_t fd,
  292. std::function<bool(Stream &)> func) {
  293. return detail::process_client_socket(
  294. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  295. };
  296. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  297. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  298. // wait_writable() returns true because select_write() only checks if the
  299. // send buffer has space. Peer disconnection is detected later by send().
  300. EXPECT_TRUE(ss.wait_writable());
  301. return true;
  302. });
  303. ASSERT_EQ(0, close(disconnected_svr_sock));
  304. }
  305. #endif // #ifndef _WIN32
  306. TEST(SetSocketOptTest, TcpNoDelay) {
  307. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  308. ASSERT_NE(sock, INVALID_SOCKET);
  309. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  310. int val = 0;
  311. socklen_t len = sizeof(val);
  312. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  313. reinterpret_cast<char *>(&val), &len));
  314. EXPECT_NE(val, 0);
  315. detail::close_socket(sock);
  316. }
  317. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  318. // accept() reports failures through WSAGetLastError() on Windows and through
  319. // errno everywhere else. Asking the wrong one is what made the accept loop
  320. // treat every recoverable failure as fatal on Windows.
  321. struct Classification {
  322. bool resource;
  323. bool transient;
  324. };
  325. auto classify = [](int err) {
  326. #ifdef _WIN32
  327. WSASetLastError(err);
  328. #else
  329. errno = err;
  330. #endif
  331. // Read both before asserting: an assertion may clobber the error slot.
  332. Classification c;
  333. c.resource = detail::is_accept_resource_error();
  334. c.transient = detail::is_accept_transient_error();
  335. return c;
  336. };
  337. #ifdef _WIN32
  338. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  339. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  340. WSAECONNRESET, WSAECONNABORTED};
  341. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  342. #else
  343. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  344. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  345. ECONNABORTED};
  346. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  347. #endif
  348. for (auto err : resource_errors) {
  349. const auto c = classify(err);
  350. EXPECT_TRUE(c.resource) << "error " << err;
  351. EXPECT_FALSE(c.transient) << "error " << err;
  352. }
  353. for (auto err : transient_errors) {
  354. const auto c = classify(err);
  355. EXPECT_TRUE(c.transient) << "error " << err;
  356. EXPECT_FALSE(c.resource) << "error " << err;
  357. }
  358. for (auto err : fatal_errors) {
  359. const auto c = classify(err);
  360. EXPECT_FALSE(c.resource) << "error " << err;
  361. EXPECT_FALSE(c.transient) << "error " << err;
  362. }
  363. #ifdef _WIN32
  364. WSASetLastError(0);
  365. #else
  366. errno = 0;
  367. #endif
  368. }
  369. TEST(ClientTest, MoveConstructible) {
  370. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  371. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  372. }
  373. TEST(ClientTest, MoveAssignable) {
  374. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  375. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  376. }
  377. #ifdef _WIN32
  378. TEST(StartupTest, WSAStartup) {
  379. WSADATA wsaData;
  380. int ret = WSAStartup(0x0002, &wsaData);
  381. ASSERT_EQ(0, ret);
  382. }
  383. #endif
  384. TEST(DecodePathTest, PercentCharacter) {
  385. EXPECT_EQ(
  386. decode_path_component(
  387. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  388. U8("descrip=Gastos áéíóúñÑ 6"));
  389. }
  390. TEST(DecodePathTest, PercentCharacterNUL) {
  391. string expected;
  392. expected.push_back('x');
  393. expected.push_back('\0');
  394. expected.push_back('x');
  395. EXPECT_EQ(decode_path_component("x%00x"), expected);
  396. }
  397. TEST(DecodePathTest, UnicodeEncoding) {
  398. // %u0041 = 'A' (1-byte UTF-8)
  399. EXPECT_EQ("A", decode_path_component("%u0041"));
  400. // %u00E9 = 'é' (2-byte UTF-8)
  401. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  402. // %u3042 = 'あ' (3-byte UTF-8)
  403. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  404. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  405. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  406. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  407. // neighbours)
  408. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  409. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  410. }
  411. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  412. // A sign or whitespace inside the two-character escape window must not be
  413. // accepted as a valid percent-encoding; the sequence is passed through
  414. // literally, matching decode_uri_component / decode_path_component.
  415. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  416. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  417. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  418. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  419. // Well-formed escapes still decode.
  420. EXPECT_EQ("-", decode_query_component("%2D", false));
  421. EXPECT_EQ("A", decode_query_component("%41", false));
  422. }
  423. TEST(SanitizeFilenameTest, VariousPatterns) {
  424. // Path traversal
  425. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  426. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  427. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  428. // Normal and edge cases
  429. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  430. EXPECT_EQ("filename.txt",
  431. httplib::sanitize_filename("/path/to/filename.txt"));
  432. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  433. EXPECT_EQ("", httplib::sanitize_filename(".."));
  434. EXPECT_EQ("", httplib::sanitize_filename(""));
  435. // Null bytes stripped
  436. EXPECT_EQ("safe.txt",
  437. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  438. // Whitespace-only rejected
  439. EXPECT_EQ("", httplib::sanitize_filename(" "));
  440. }
  441. // Forward declaration (see the base64_encode note below): split builds move the
  442. // definition into httplib.cc, so re-declaring it here lets the test link.
  443. namespace httplib {
  444. namespace detail {
  445. bool is_chunked_transfer_encoding(const Headers &headers);
  446. } // namespace detail
  447. } // namespace httplib
  448. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  449. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  450. auto make = [](std::initializer_list<const char *> lines) {
  451. Headers h;
  452. for (auto te : lines) {
  453. if (te) { h.emplace("Transfer-Encoding", te); }
  454. }
  455. return h;
  456. };
  457. // Sole coding, matched case-insensitively.
  458. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  460. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  461. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  462. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  463. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  464. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  465. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  466. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  467. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  470. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  471. // were received, into one list. Headers preserves that order, so the answer
  472. // is decided by the last coding of the last line and the order the lines
  473. // arrived in is significant.
  474. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  475. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  476. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  477. // The split can fall anywhere in the list.
  478. EXPECT_TRUE(
  479. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  480. EXPECT_FALSE(
  481. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  482. // A trailing line naming no coding leaves the list ending in nothing, so it
  483. // must not inherit the chunked from the line before it.
  484. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  485. }
  486. // Forward declarations (see the base64_encode note below).
  487. namespace httplib {
  488. namespace detail {
  489. bool parse_status_line(const char *line, std::string &version, int &status,
  490. std::string &reason);
  491. std::string file_extension(const std::string &path);
  492. std::string
  493. find_content_type(const std::string &path,
  494. const std::map<std::string, std::string> &user_data,
  495. const std::string &default_content_type);
  496. bool can_compress_content_type(const std::string &content_type);
  497. bool is_prohibited_header_name(const std::string &name);
  498. bool is_valid_path(const std::string &path);
  499. #ifdef CPPHTTPLIB_SSL_ENABLED
  500. bool match_hostname(const std::string &pattern, const std::string &hostname);
  501. #endif
  502. } // namespace detail
  503. } // namespace httplib
  504. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  505. struct {
  506. const char *line;
  507. const char *version;
  508. int status;
  509. const char *reason;
  510. } cases[] = {
  511. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  512. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  513. // The reason phrase may be empty, or left out along with its space.
  514. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  515. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  516. };
  517. for (const auto &c : cases) {
  518. std::string version;
  519. int status = 0;
  520. std::string reason = "unset";
  521. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  522. << c.line;
  523. EXPECT_EQ(c.version, version);
  524. EXPECT_EQ(c.status, status);
  525. EXPECT_EQ(c.reason, reason);
  526. }
  527. }
  528. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  529. const char *lines[] = {
  530. "HTTP/2 200 OK\r\n",
  531. "HTTP/1.2 200 OK\r\n",
  532. "HTTP/1.1 20 OK\r\n",
  533. "HTTP/1.1 2000 OK\r\n",
  534. "HTTP/1.1 2x0 OK\r\n",
  535. "HTTP/1.1 200 OK\r\n",
  536. "HTTP/1.1 200OK\r\n",
  537. "HTTP/1.1 200 O\rK\r\n",
  538. "HTTP/1.1 200 OK",
  539. "HTTP/1.1 200 OK\r\nX",
  540. "",
  541. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  542. "HTTP/1.1 200 OK\n",
  543. #endif
  544. };
  545. for (auto line : lines) {
  546. std::string version;
  547. int status = 0;
  548. std::string reason;
  549. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  550. << line;
  551. }
  552. }
  553. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  554. // Long enough to overflow the stack when matched with std::regex.
  555. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  556. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  557. std::string version;
  558. int status = 0;
  559. std::string reason;
  560. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  561. EXPECT_EQ(200, status);
  562. EXPECT_EQ(long_reason, reason);
  563. }
  564. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  565. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  566. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  567. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  568. EXPECT_EQ("", detail::file_extension("noext"));
  569. EXPECT_EQ("", detail::file_extension("a."));
  570. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  571. EXPECT_EQ("", detail::file_extension("a.b-c"));
  572. // Long enough to overflow the stack when matched with std::regex.
  573. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  574. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  575. }
  576. #ifdef CPPHTTPLIB_SSL_ENABLED
  577. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  578. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  579. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  580. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  581. // A wildcard needs two labels after it, in the leftmost label only
  582. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  583. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  584. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  585. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  586. EXPECT_FALSE(
  587. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  588. // No name may have an empty label
  589. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  590. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  591. }
  592. #endif
  593. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  594. detail::case_ignore::hash hash;
  595. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  596. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  597. // Long enough to overflow the stack if hashed one call per character.
  598. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  599. }
  600. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  601. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  602. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  603. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  604. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  605. // Same 26-bit hash as html, svg and js.
  606. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  607. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  608. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  609. }
  610. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  611. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  612. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  613. }
  614. }
  615. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  616. // name anywhere else.
  617. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  618. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  619. #ifdef _WIN32
  620. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  621. #else
  622. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  623. #endif
  624. }
  625. }
  626. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  627. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  628. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  629. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  630. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  631. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  632. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  633. // Same 26-bit hash as application/json.
  634. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  635. }
  636. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  637. Request req;
  638. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  639. EXPECT_TRUE(req.is_multipart_form_data());
  640. std::string boundary;
  641. EXPECT_TRUE(detail::parse_multipart_boundary(
  642. req.get_header_value("Content-Type"), boundary));
  643. EXPECT_EQ("x", boundary);
  644. }
  645. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  646. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  647. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  648. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  649. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  650. // Same 26-bit hash as REMOTE_ADDR.
  651. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  652. }
  653. // Forward declaration: in split builds split.py strips `inline` and moves the
  654. // definition into httplib.cc, so detail::base64_encode is not visible from the
  655. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  656. // in both header-only and split builds.
  657. namespace httplib {
  658. namespace detail {
  659. std::string base64_encode(const std::string &in);
  660. } // namespace detail
  661. } // namespace httplib
  662. TEST(Base64EncodeTest, KnownAnswers) {
  663. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  664. // where the accumulator's top bit is already set before the next shift.
  665. EXPECT_EQ("", detail::base64_encode(""));
  666. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  667. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  668. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  669. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  670. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  671. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  672. // High bytes keep the top bit set across several rounds.
  673. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  674. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  675. }
  676. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  677. string unescapedCharacters = "-_.!~*'()";
  678. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  679. }
  680. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  681. string reservedCharacters = ";,/?:@&=+$";
  682. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  683. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  684. }
  685. TEST(ClientQueryOrder, PreserveOrder) {
  686. // This test reproduces Issue #2259: client may reorder query parameters
  687. // when sending a GET request. The expected behavior is that the client
  688. // preserves the original query string order when the caller supplied it
  689. // as part of the path.
  690. Server svr;
  691. svr.Get("/", [&](const Request &req, Response &res) {
  692. // Echo back the raw target so the test can assert ordering
  693. res.set_content(req.target, "text/plain");
  694. });
  695. std::thread t{[&] { svr.listen(HOST, PORT); }};
  696. auto se = detail::scope_exit([&] {
  697. svr.stop();
  698. t.join();
  699. ASSERT_FALSE(svr.is_running());
  700. });
  701. svr.wait_until_ready();
  702. Client cli(HOST, PORT);
  703. ASSERT_TRUE(cli.is_valid());
  704. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  705. auto res = cli.Get(original);
  706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  707. // Expect the echoed target to exactly match the original path (order
  708. // preserved)
  709. EXPECT_EQ(res->body, original);
  710. }
  711. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  712. string chineseCharacters = U8("中国語");
  713. string russianCharacters = U8("дом");
  714. string brazilianCharacters = U8("óculos");
  715. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  716. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  717. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  718. "%D0%B4%D0%BE%D0%BC");
  719. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  720. }
  721. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  722. string unescapedCharacters = "-_.!~*'()";
  723. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  724. }
  725. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  726. string reservedCharacters = ";,/?:@&=+$";
  727. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  728. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  729. }
  730. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  731. string chineseCharacters = U8("中国語");
  732. string russianCharacters = U8("дом");
  733. string brazilianCharacters = U8("óculos");
  734. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  735. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  736. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  737. "%D0%B4%D0%BE%D0%BC");
  738. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  739. }
  740. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  741. // Issue #2082 use case: encoding path component with ampersand
  742. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  743. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  744. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  745. }
  746. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  747. string unescapedCharacters = "-_.!~*'()";
  748. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  749. }
  750. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  751. string reservedCharacters = ";,/?:@&=+$#";
  752. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  753. }
  754. TEST(EncodeUriTest, TestUTF8Characters) {
  755. string chineseCharacters = U8("中国語");
  756. string russianCharacters = U8("дом");
  757. string brazilianCharacters = U8("óculos");
  758. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  759. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  760. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  761. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  762. }
  763. TEST(EncodeUriTest, TestCompleteUri) {
  764. string uri =
  765. "https://example.com/path/to/resource?query=value&param=test#fragment";
  766. EXPECT_EQ(
  767. httplib::encode_uri(uri),
  768. "https://example.com/path/to/resource?query=value&param=test#fragment");
  769. }
  770. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  771. string uri =
  772. "https://example.com/path with spaces/file name.html?q=hello world";
  773. EXPECT_EQ(httplib::encode_uri(uri),
  774. "https://example.com/path%20with%20spaces/"
  775. "file%20name.html?q=hello%20world");
  776. }
  777. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  778. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  779. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  780. }
  781. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  782. string unescapedCharacters = "-_.!~*'()";
  783. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  784. }
  785. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  786. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  787. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  788. string encodedBrazilian = "%C3%B3culos";
  789. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  790. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  791. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  792. }
  793. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  794. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  795. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  796. "Piri Tommy Villiers - on & on");
  797. }
  798. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  799. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  800. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  801. }
  802. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  803. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  804. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  805. }
  806. TEST(DecodeUriTest, TestUTF8Characters) {
  807. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  808. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  809. string encodedBrazilian = "%C3%B3culos";
  810. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  811. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  812. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  813. }
  814. TEST(DecodeUriTest, TestCompleteUri) {
  815. string encodedUri = "https://example.com/path%20with%20spaces/"
  816. "file%20name.html?q=hello%20world";
  817. EXPECT_EQ(
  818. httplib::decode_uri(encodedUri),
  819. "https://example.com/path with spaces/file name.html?q=hello world");
  820. }
  821. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  822. string original =
  823. "https://example.com/path with spaces/file name.html?q=hello world";
  824. string encoded = httplib::encode_uri(original);
  825. string decoded = httplib::decode_uri(encoded);
  826. EXPECT_EQ(decoded, original);
  827. }
  828. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  829. // decode_uri is the inverse of encode_uri: an escaped reserved character
  830. // stays encoded so it is not promoted into a real delimiter, while
  831. // non-reserved escapes still decode (like JS decodeURI).
  832. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  833. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  834. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  835. "%3F%3A%40%26%3D%2B%24%2C%3B");
  836. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  837. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  838. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  839. "http://example.com/a%2Fb");
  840. // decode_uri_component still decodes the reserved character.
  841. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  842. }
  843. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  844. string original = "Piri Tommy Villiers - on & on";
  845. string encoded = httplib::encode_uri_component(original);
  846. string decoded = httplib::decode_uri_component(encoded);
  847. EXPECT_EQ(decoded, original);
  848. }
  849. TEST(TrimTests, TrimStringTests) {
  850. EXPECT_EQ("abc", detail::trim_copy("abc"));
  851. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  852. EXPECT_TRUE(detail::trim_copy("").empty());
  853. }
  854. TEST(AsciiTest, LocaleIndependentClassification) {
  855. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  856. // which consult the global C locale: std::isalnum(0xC5) can return true
  857. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  858. // helpers must classify every byte by the ASCII grammar alone.
  859. for (int i = 0; i < 256; i++) {
  860. auto c = static_cast<char>(i);
  861. auto is_digit = i >= '0' && i <= '9';
  862. auto is_upper = i >= 'A' && i <= 'Z';
  863. auto is_lower = i >= 'a' && i <= 'z';
  864. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  865. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  866. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  867. << "byte " << i;
  868. }
  869. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  870. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  871. // Non-ASCII bytes must be percent-encoded, never passed through as
  872. // alphanumeric.
  873. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  874. }
  875. TEST(FromCharsTest, Double) {
  876. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  877. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  878. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  879. auto parse = [](const std::string &s, double &v) {
  880. return detail::from_chars(s.data(), s.data() + s.size(), v);
  881. };
  882. double v = -1.0;
  883. // Representative quality values.
  884. EXPECT_EQ(parse("0", v).ec, std::errc{});
  885. EXPECT_DOUBLE_EQ(v, 0.0);
  886. EXPECT_EQ(parse("1", v).ec, std::errc{});
  887. EXPECT_DOUBLE_EQ(v, 1.0);
  888. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  889. EXPECT_DOUBLE_EQ(v, 0.8);
  890. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  891. EXPECT_DOUBLE_EQ(v, 0.001);
  892. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  893. EXPECT_DOUBLE_EQ(v, 1.0);
  894. // A missing integer or fractional part is tolerated.
  895. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  896. EXPECT_DOUBLE_EQ(v, 0.5);
  897. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  898. EXPECT_DOUBLE_EQ(v, 5.0);
  899. // Values outside [0, 1] still parse; the caller range-checks them.
  900. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  901. EXPECT_DOUBLE_EQ(v, 123.456);
  902. // Stops at the first byte that is not part of the number and reports where.
  903. std::string trailing = "0.9, text/html";
  904. auto r = parse(trailing, v);
  905. EXPECT_EQ(r.ec, std::errc{});
  906. EXPECT_DOUBLE_EQ(v, 0.9);
  907. EXPECT_EQ(*r.ptr, ',');
  908. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  909. // outright, and an 'e'/'E' simply ends the number.
  910. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  911. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  912. std::string exp_input = "1.5e3";
  913. r = parse(exp_input, v);
  914. EXPECT_EQ(r.ec, std::errc{});
  915. EXPECT_DOUBLE_EQ(v, 1.5);
  916. EXPECT_EQ(*r.ptr, 'e');
  917. // Invalid inputs.
  918. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  919. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  920. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  921. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  922. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  923. // Pathological but well-formed inputs must stay bounded (no overflow, no
  924. // out-of-bounds table access) and stay within [0, 1] for the caller.
  925. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  926. std::errc{});
  927. EXPECT_DOUBLE_EQ(v, 0.0);
  928. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  929. std::errc{});
  930. EXPECT_GE(v, 0.0);
  931. EXPECT_LE(v, 1.0);
  932. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  933. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  934. }
  935. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  936. // Simple case without quality values
  937. std::vector<std::string> result1;
  938. EXPECT_TRUE(detail::parse_accept_header(
  939. "text/html,application/json,text/plain", result1));
  940. EXPECT_EQ(result1.size(), 3U);
  941. EXPECT_EQ(result1[0], "text/html");
  942. EXPECT_EQ(result1[1], "application/json");
  943. EXPECT_EQ(result1[2], "text/plain");
  944. // With quality values
  945. std::vector<std::string> result2;
  946. EXPECT_TRUE(detail::parse_accept_header(
  947. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  948. EXPECT_EQ(result2.size(), 3U);
  949. EXPECT_EQ(result2[0], "application/json"); // highest q value
  950. EXPECT_EQ(result2[1], "text/html");
  951. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  952. }
  953. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  954. // Mixed with and without quality values
  955. std::vector<std::string> result;
  956. EXPECT_TRUE(detail::parse_accept_header(
  957. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  958. EXPECT_EQ(result.size(), 3U);
  959. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  960. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  961. EXPECT_EQ(result[2], "application/json"); // q=0.5
  962. }
  963. TEST(ParseAcceptHeaderTest, EdgeCases) {
  964. // Empty header
  965. std::vector<std::string> empty_result;
  966. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  967. EXPECT_TRUE(empty_result.empty());
  968. // Single type
  969. std::vector<std::string> single_result;
  970. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  971. EXPECT_EQ(single_result.size(), 1U);
  972. EXPECT_EQ(single_result[0], "application/json");
  973. // Wildcard types
  974. std::vector<std::string> wildcard_result;
  975. EXPECT_TRUE(detail::parse_accept_header(
  976. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  977. EXPECT_EQ(wildcard_result.size(), 3U);
  978. EXPECT_EQ(wildcard_result[0], "application/json");
  979. EXPECT_EQ(wildcard_result[1], "text/*");
  980. EXPECT_EQ(wildcard_result[2], "*/*");
  981. }
  982. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  983. // Common browser Accept header
  984. std::vector<std::string> browser_result;
  985. EXPECT_TRUE(
  986. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  987. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  988. browser_result));
  989. EXPECT_EQ(browser_result.size(), 6U);
  990. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  991. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  992. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  993. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  994. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  995. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  996. // API client header
  997. std::vector<std::string> api_result;
  998. EXPECT_TRUE(detail::parse_accept_header(
  999. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1000. api_result));
  1001. EXPECT_EQ(api_result.size(), 3U);
  1002. EXPECT_EQ(api_result[0], "application/json");
  1003. EXPECT_EQ(api_result[1], "application/xml");
  1004. EXPECT_EQ(api_result[2], "text/plain");
  1005. }
  1006. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1007. // Quality value with 3 decimal places
  1008. std::vector<std::string> decimal_result;
  1009. EXPECT_TRUE(detail::parse_accept_header(
  1010. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1011. EXPECT_EQ(decimal_result.size(), 2U);
  1012. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1013. EXPECT_EQ(decimal_result[1], "text/html");
  1014. // Zero quality (should still be included but with lowest priority)
  1015. std::vector<std::string> zero_q_result;
  1016. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1017. zero_q_result));
  1018. EXPECT_EQ(zero_q_result.size(), 2U);
  1019. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1020. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1021. // No spaces around commas
  1022. std::vector<std::string> no_space_result;
  1023. EXPECT_TRUE(detail::parse_accept_header(
  1024. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1025. no_space_result));
  1026. EXPECT_EQ(no_space_result.size(), 3U);
  1027. EXPECT_EQ(no_space_result[0], "text/html");
  1028. EXPECT_EQ(no_space_result[1], "application/json");
  1029. EXPECT_EQ(no_space_result[2], "text/plain");
  1030. }
  1031. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1032. // Quality values always use '.' as the decimal separator, so parsing must
  1033. // not depend on the process locale. An embedding application may have
  1034. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1035. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1036. std::string saved = cur ? cur : "C";
  1037. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1038. "fr_FR.UTF-8"};
  1039. bool switched = false;
  1040. for (const auto loc : comma_locales) {
  1041. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1042. std::localeconv()->decimal_point[0] == ',') {
  1043. switched = true;
  1044. break;
  1045. }
  1046. }
  1047. if (!switched) {
  1048. std::setlocale(LC_NUMERIC, saved.c_str());
  1049. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1050. }
  1051. // The higher-weighted type appears later in the list, so a correct parse
  1052. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1053. // sensitive parse reads both weights as 0 and leaves the original order.
  1054. std::vector<std::string> result;
  1055. EXPECT_TRUE(detail::parse_accept_header(
  1056. "application/json;q=0.1,text/html;q=0.9", result));
  1057. ASSERT_EQ(result.size(), 2U);
  1058. EXPECT_EQ(result[0], "text/html");
  1059. EXPECT_EQ(result[1], "application/json");
  1060. std::setlocale(LC_NUMERIC, saved.c_str());
  1061. }
  1062. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1063. std::vector<std::string> result;
  1064. // Invalid quality value (> 1.0)
  1065. EXPECT_FALSE(
  1066. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1067. // Invalid quality value (< 0.0)
  1068. EXPECT_FALSE(
  1069. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1070. // Invalid quality value (not a number)
  1071. EXPECT_FALSE(detail::parse_accept_header(
  1072. "text/html;q=invalid,application/json", result));
  1073. // A valid numeric prefix does not make the entire quality value valid.
  1074. EXPECT_FALSE(detail::parse_accept_header(
  1075. "text/html;q=0.5junk,application/json", result));
  1076. // Empty quality value
  1077. EXPECT_FALSE(
  1078. detail::parse_accept_header("text/html;q=,application/json", result));
  1079. // Invalid media type format (no slash and not wildcard)
  1080. EXPECT_FALSE(
  1081. detail::parse_accept_header("invalidtype,application/json", result));
  1082. // Valid cases should still work
  1083. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1084. EXPECT_EQ(result.size(), 1U);
  1085. EXPECT_EQ(result[0], "*/*");
  1086. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1087. EXPECT_EQ(result.size(), 1U);
  1088. EXPECT_EQ(result[0], "*");
  1089. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1090. EXPECT_EQ(result.size(), 1U);
  1091. EXPECT_EQ(result[0], "text/*");
  1092. }
  1093. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1094. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1095. // and must not be answered with 400 Bad Request.
  1096. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1097. struct {
  1098. const char *value;
  1099. std::vector<std::string> expected;
  1100. } cases[] = {
  1101. {",application/json", {"application/json"}},
  1102. {"text/html,", {"text/html"}},
  1103. {"text/html,,*/*", {"text/html", "*/*"}},
  1104. // An empty element may be spelled with whitespace in it
  1105. {"text/html, , application/json", {"text/html", "application/json"}},
  1106. // Nothing but empty elements is an empty list, which means the same
  1107. // thing as no Accept header at all
  1108. {",,,", {}},
  1109. // Quality values still apply across ignored empty elements
  1110. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1111. };
  1112. for (const auto &c : cases) {
  1113. std::vector<std::string> result;
  1114. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1115. << "value: " << c.value;
  1116. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1117. }
  1118. // An invalid entry is still rejected when empty elements surround it
  1119. std::vector<std::string> result;
  1120. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1121. }
  1122. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1123. // or ';' inside one does not end the list element or the parameter. Section
  1124. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1125. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1126. struct {
  1127. const char *value;
  1128. std::vector<std::string> expected;
  1129. } cases[] = {
  1130. {"text/html;profile=\"a,b\",application/json",
  1131. {"text/html", "application/json"}},
  1132. // A "q=" inside a quoted value is not the weight
  1133. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1134. {"text/html", "application/json"}},
  1135. // The weight after a quoted value still applies
  1136. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1137. {"application/json", "text/html"}},
  1138. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1139. {"application/json", "text/html"}},
  1140. {"text/html;profile=\"a\\\"b\",application/json",
  1141. {"text/html", "application/json"}},
  1142. // An escaped backslash does not escape the '"' after it
  1143. {"text/html;profile=\"a\\\\\",application/json",
  1144. {"text/html", "application/json"}},
  1145. };
  1146. for (const auto &c : cases) {
  1147. std::vector<std::string> result;
  1148. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1149. << "value: " << c.value;
  1150. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1151. }
  1152. }
  1153. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1154. Server svr;
  1155. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1156. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1157. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1158. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1159. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1160. res.set_content("ok", "text/plain");
  1161. });
  1162. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1163. EXPECT_TRUE(false);
  1164. res.set_content("bad request", "text/plain");
  1165. });
  1166. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1167. auto se = detail::scope_exit([&] {
  1168. svr.stop();
  1169. listen_thread.join();
  1170. ASSERT_FALSE(svr.is_running());
  1171. });
  1172. svr.wait_until_ready();
  1173. Client cli("localhost", PORT);
  1174. {
  1175. auto res = cli.Get(
  1176. "/accept_ok",
  1177. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1179. EXPECT_EQ(StatusCode::OK_200, res->status);
  1180. }
  1181. {
  1182. auto res = cli.Get("/accept_bad_request",
  1183. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1185. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1186. }
  1187. }
  1188. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1189. Server svr;
  1190. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1191. res.set_content("ok", "text/plain");
  1192. });
  1193. std::atomic<int> start_count{0};
  1194. std::atomic<bool> running_when_called{false};
  1195. svr.set_start_handler([&]() {
  1196. running_when_called = svr.is_running();
  1197. start_count++;
  1198. });
  1199. auto port = svr.bind_to_any_port(HOST);
  1200. std::thread t([&]() { svr.listen_after_bind(); });
  1201. auto se = detail::scope_exit([&] {
  1202. svr.stop();
  1203. t.join();
  1204. ASSERT_FALSE(svr.is_running());
  1205. });
  1206. svr.wait_until_ready();
  1207. // A successful request proves the accept loop is running, which the start
  1208. // handler precedes; so by now the handler must have run exactly once.
  1209. Client cli(HOST, port);
  1210. cli.set_connection_timeout(std::chrono::seconds(5));
  1211. auto res = cli.Get("/");
  1212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1213. EXPECT_EQ(StatusCode::OK_200, res->status);
  1214. EXPECT_EQ(1, start_count.load());
  1215. EXPECT_TRUE(running_when_called.load());
  1216. }
  1217. TEST(DivideTest, DivideStringTests) {
  1218. auto divide = [](const std::string &str, char d) {
  1219. std::string lhs;
  1220. std::string rhs;
  1221. detail::divide(str, d,
  1222. [&](const char *lhs_data, std::size_t lhs_size,
  1223. const char *rhs_data, std::size_t rhs_size) {
  1224. lhs.assign(lhs_data, lhs_size);
  1225. rhs.assign(rhs_data, rhs_size);
  1226. });
  1227. return std::make_pair(std::move(lhs), std::move(rhs));
  1228. };
  1229. {
  1230. const auto res = divide("", '=');
  1231. EXPECT_EQ(res.first, "");
  1232. EXPECT_EQ(res.second, "");
  1233. }
  1234. {
  1235. const auto res = divide("=", '=');
  1236. EXPECT_EQ(res.first, "");
  1237. EXPECT_EQ(res.second, "");
  1238. }
  1239. {
  1240. const auto res = divide(" ", '=');
  1241. EXPECT_EQ(res.first, " ");
  1242. EXPECT_EQ(res.second, "");
  1243. }
  1244. {
  1245. const auto res = divide("a", '=');
  1246. EXPECT_EQ(res.first, "a");
  1247. EXPECT_EQ(res.second, "");
  1248. }
  1249. {
  1250. const auto res = divide("a=", '=');
  1251. EXPECT_EQ(res.first, "a");
  1252. EXPECT_EQ(res.second, "");
  1253. }
  1254. {
  1255. const auto res = divide("=b", '=');
  1256. EXPECT_EQ(res.first, "");
  1257. EXPECT_EQ(res.second, "b");
  1258. }
  1259. {
  1260. const auto res = divide("a=b", '=');
  1261. EXPECT_EQ(res.first, "a");
  1262. EXPECT_EQ(res.second, "b");
  1263. }
  1264. {
  1265. const auto res = divide("a=b=", '=');
  1266. EXPECT_EQ(res.first, "a");
  1267. EXPECT_EQ(res.second, "b=");
  1268. }
  1269. {
  1270. const auto res = divide("a=b=c", '=');
  1271. EXPECT_EQ(res.first, "a");
  1272. EXPECT_EQ(res.second, "b=c");
  1273. }
  1274. }
  1275. TEST(SplitTest, ParseQueryString) {
  1276. string s = "key1=val1&key2=val2&key3=val3";
  1277. Params dic;
  1278. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1279. [&](const char *b, const char *e) {
  1280. string key, val;
  1281. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1282. if (key.empty()) {
  1283. key.assign(b2, e2);
  1284. } else {
  1285. val.assign(b2, e2);
  1286. }
  1287. });
  1288. dic.emplace(key, val);
  1289. });
  1290. EXPECT_EQ("val1", dic.find("key1")->second);
  1291. EXPECT_EQ("val2", dic.find("key2")->second);
  1292. EXPECT_EQ("val3", dic.find("key3")->second);
  1293. }
  1294. TEST(SplitTest, ParseInvalidQueryTests) {
  1295. {
  1296. string s = " ";
  1297. Params dict;
  1298. detail::parse_query_text(s, dict);
  1299. EXPECT_TRUE(dict.empty());
  1300. }
  1301. {
  1302. string s = " = =";
  1303. Params dict;
  1304. detail::parse_query_text(s, dict);
  1305. EXPECT_TRUE(dict.empty());
  1306. }
  1307. }
  1308. TEST(ParseQueryTest, ParseQueryString) {
  1309. {
  1310. std::string s = "key1=val1&key2=val2&key3=val3";
  1311. Params dic;
  1312. detail::parse_query_text(s, dic);
  1313. EXPECT_EQ("val1", dic.find("key1")->second);
  1314. EXPECT_EQ("val2", dic.find("key2")->second);
  1315. EXPECT_EQ("val3", dic.find("key3")->second);
  1316. }
  1317. {
  1318. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1319. Params dic;
  1320. detail::parse_query_text(s, dic);
  1321. EXPECT_EQ("", dic.find("key1")->second);
  1322. EXPECT_EQ("val1", dic.find("key2")->second);
  1323. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1324. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1325. }
  1326. }
  1327. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1328. Params dic;
  1329. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1330. dic.emplace("key1", "val1");
  1331. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1332. dic.emplace("key2", "val2");
  1333. dic.emplace("key3", "val3");
  1334. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1335. }
  1336. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1337. Params params;
  1338. params.emplace("a", "1");
  1339. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1340. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1341. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1342. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1343. // Long enough to overflow the stack when matched with std::regex.
  1344. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1345. EXPECT_EQ("/p?" + long_query + "&a=1",
  1346. append_query_params("/p?" + long_query, params));
  1347. }
  1348. // Joins every entry of a Headers or Params into "key=value " so a whole
  1349. // traversal can be compared in one assertion. Both are instantiations of the
  1350. // same insertion-ordered container, so one helper serves both.
  1351. template <typename Map> static std::string entries_to_string(const Map &m) {
  1352. std::string s;
  1353. for (const auto &entry : m) {
  1354. s += entry.first + "=" + entry.second + " ";
  1355. }
  1356. return s;
  1357. }
  1358. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1359. // Params used to be a std::multimap, which sorted by name and handed the
  1360. // caller's query back alphabetised. A client signing its query string could
  1361. // not reproduce the order it asked for.
  1362. Params dic;
  1363. dic.emplace("zulu", "1");
  1364. dic.emplace("alpha", "2");
  1365. dic.emplace("mike", "3");
  1366. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1367. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1368. }
  1369. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1370. Params dic;
  1371. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1372. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1373. }
  1374. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1375. Request req;
  1376. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1377. req.params);
  1378. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1379. EXPECT_EQ("first", req.get_param_value("tag"));
  1380. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1381. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1382. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1383. EXPECT_EQ("", req.get_param_value("tag", 3));
  1384. }
  1385. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1386. // Params shares its container with Headers, which matches field names
  1387. // case-insensitively. Parameter names must not pick that up.
  1388. Params dic;
  1389. dic.emplace("Key", "upper");
  1390. dic.emplace("key", "lower");
  1391. EXPECT_EQ(2U, dic.size());
  1392. EXPECT_EQ(1U, dic.count("Key"));
  1393. EXPECT_EQ(1U, dic.count("key"));
  1394. EXPECT_EQ("upper", dic.find("Key")->second);
  1395. EXPECT_EQ("lower", dic.find("key")->second);
  1396. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1397. }
  1398. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1399. Server svr;
  1400. std::string order;
  1401. svr.Get("/order", [&](const Request &req, Response &res) {
  1402. order = entries_to_string(req.params);
  1403. res.set_content("ok", "text/plain");
  1404. });
  1405. auto port = svr.bind_to_any_port(HOST);
  1406. thread t = thread([&] { svr.listen_after_bind(); });
  1407. auto se = detail::scope_exit([&] {
  1408. svr.stop();
  1409. t.join();
  1410. ASSERT_FALSE(svr.is_running());
  1411. });
  1412. svr.wait_until_ready();
  1413. Client cli(HOST, port);
  1414. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1415. ASSERT_TRUE(res);
  1416. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1417. }
  1418. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1419. Server svr;
  1420. std::string field_order, file_order;
  1421. svr.Post("/order", [&](const Request &req, Response &res) {
  1422. for (const auto &field : req.form.fields) {
  1423. field_order += field.first + "=" + field.second.content + " ";
  1424. }
  1425. for (const auto &file : req.form.files) {
  1426. file_order += file.first + "=" + file.second.filename + " ";
  1427. }
  1428. res.set_content("ok", "text/plain");
  1429. });
  1430. auto port = svr.bind_to_any_port(HOST);
  1431. thread t = thread([&] { svr.listen_after_bind(); });
  1432. auto se = detail::scope_exit([&] {
  1433. svr.stop();
  1434. t.join();
  1435. ASSERT_FALSE(svr.is_running());
  1436. });
  1437. svr.wait_until_ready();
  1438. UploadFormDataItems items = {
  1439. {"zulu", "1", "", ""},
  1440. {"alpha", "2", "", ""},
  1441. {"mike", "3", "", ""},
  1442. {"zebra", "z", "z.txt", "text/plain"},
  1443. {"apple", "a", "a.txt", "text/plain"},
  1444. };
  1445. Client cli(HOST, port);
  1446. auto res = cli.Post("/order", items);
  1447. ASSERT_TRUE(res);
  1448. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1449. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1450. }
  1451. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1452. Server svr;
  1453. std::vector<std::string> values;
  1454. std::string first, second, out_of_range, order;
  1455. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1456. values = req.form.get_fields("tag");
  1457. first = req.form.get_field("tag", 0);
  1458. second = req.form.get_field("tag", 1);
  1459. out_of_range = req.form.get_field("tag", 2);
  1460. for (const auto &field : req.form.fields) {
  1461. order += field.first + "=" + field.second.content + " ";
  1462. }
  1463. res.set_content("ok", "text/plain");
  1464. });
  1465. auto port = svr.bind_to_any_port(HOST);
  1466. thread t = thread([&] { svr.listen_after_bind(); });
  1467. auto se = detail::scope_exit([&] {
  1468. svr.stop();
  1469. t.join();
  1470. ASSERT_FALSE(svr.is_running());
  1471. });
  1472. svr.wait_until_ready();
  1473. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1474. // not adjacent in the container.
  1475. UploadFormDataItems items = {
  1476. {"tag", "first", "", ""},
  1477. {"other", "x", "", ""},
  1478. {"tag", "second", "", ""},
  1479. };
  1480. Client cli(HOST, port);
  1481. auto res = cli.Post("/repeated", items);
  1482. ASSERT_TRUE(res);
  1483. ASSERT_EQ(2U, values.size());
  1484. EXPECT_EQ("first", values[0]);
  1485. EXPECT_EQ("second", values[1]);
  1486. EXPECT_EQ("first", first);
  1487. EXPECT_EQ("second", second);
  1488. // std::multimap already kept entries sharing a name in insertion order, so
  1489. // everything above passes without this change too. The whole traversal is
  1490. // what tells the two apart: sorting by name would hoist "other" to the front
  1491. // and the two "tag" parts would end up adjacent.
  1492. EXPECT_EQ("tag=first other=x tag=second ", order);
  1493. // Advancing past the last entry of a name used to run off the container;
  1494. // the container's saturating increment makes it return the default instead.
  1495. EXPECT_EQ("", out_of_range);
  1496. }
  1497. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1498. Server svr;
  1499. std::string file_names;
  1500. svr.Post("/upload", [&](const Request &req, Response &res) {
  1501. for (const auto &file : req.form.files) {
  1502. file_names += file.first + "|" + file.second.filename + " ";
  1503. }
  1504. res.set_content("ok", "text/plain");
  1505. });
  1506. auto port = svr.bind_to_any_port(HOST);
  1507. thread t = thread([&] { svr.listen_after_bind(); });
  1508. auto se = detail::scope_exit([&] {
  1509. svr.stop();
  1510. t.join();
  1511. ASSERT_FALSE(svr.is_running());
  1512. });
  1513. svr.wait_until_ready();
  1514. // A trailing backslash would otherwise escape the closing quote.
  1515. UploadFormDataItems items = {
  1516. {"dir\\", "x", "a.txt", "text/plain"},
  1517. {"b", "y", "a\\\\b.txt", "text/plain"},
  1518. };
  1519. Client cli(HOST, port);
  1520. auto res = cli.Post("/upload", items);
  1521. ASSERT_TRUE(res);
  1522. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1523. }
  1524. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1525. // Server::read_content() keeps a FormFields::iterator alive across the
  1526. // content callbacks that fill the part it points at. The container is
  1527. // vector-backed, so a later emplace can reallocate and invalidate an older
  1528. // iterator; 64 parts grow the vector through seven reallocations, which
  1529. // checks that every part's content still lands in its own entry.
  1530. const size_t part_count = 64;
  1531. // One formula for both the parts sent and the values expected back, so the
  1532. // two cannot drift apart.
  1533. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1534. auto content_of = [](size_t i) {
  1535. return std::string(64, static_cast<char>('a' + (i % 26)));
  1536. };
  1537. Server svr;
  1538. std::vector<std::pair<std::string, std::string>> received;
  1539. svr.Post("/many", [&](const Request &req, Response &res) {
  1540. for (const auto &field : req.form.fields) {
  1541. received.emplace_back(field.first, field.second.content);
  1542. }
  1543. res.set_content("ok", "text/plain");
  1544. });
  1545. auto port = svr.bind_to_any_port(HOST);
  1546. thread t = thread([&] { svr.listen_after_bind(); });
  1547. auto se = detail::scope_exit([&] {
  1548. svr.stop();
  1549. t.join();
  1550. ASSERT_FALSE(svr.is_running());
  1551. });
  1552. svr.wait_until_ready();
  1553. UploadFormDataItems items;
  1554. for (size_t i = 0; i < part_count; i++) {
  1555. items.push_back({name_of(i), content_of(i), "", ""});
  1556. }
  1557. Client cli(HOST, port);
  1558. auto res = cli.Post("/many", items);
  1559. ASSERT_TRUE(res);
  1560. ASSERT_EQ(part_count, received.size());
  1561. for (size_t i = 0; i < part_count; i++) {
  1562. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1563. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1564. }
  1565. }
  1566. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1567. string content_type = "multipart/form-data; boundary=something";
  1568. string boundary;
  1569. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1570. EXPECT_TRUE(ret);
  1571. EXPECT_EQ(boundary, "something");
  1572. }
  1573. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1574. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1575. string boundary;
  1576. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1577. EXPECT_TRUE(ret);
  1578. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1579. }
  1580. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1581. string content_type =
  1582. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1583. string boundary;
  1584. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1585. EXPECT_TRUE(ret);
  1586. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1587. }
  1588. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1589. string content_type =
  1590. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1591. string boundary;
  1592. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1593. EXPECT_TRUE(ret);
  1594. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1595. }
  1596. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1597. const string boundary(70, 'a');
  1598. string content_type = "multipart/form-data; boundary=" + boundary;
  1599. string parsed;
  1600. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1601. EXPECT_TRUE(ret);
  1602. EXPECT_EQ(parsed, boundary);
  1603. }
  1604. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1605. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1606. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1607. string parsed;
  1608. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1609. EXPECT_FALSE(ret);
  1610. }
  1611. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1612. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1613. // is 72 characters on the wire and still valid.
  1614. const string boundary(70, 'a');
  1615. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1616. string parsed;
  1617. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1618. EXPECT_EQ(parsed, boundary);
  1619. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1620. parsed.clear();
  1621. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1622. }
  1623. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1624. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1625. // The parameter parser must not treat that '=' as the key/value separator.
  1626. string content_type =
  1627. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1628. "charset=UTF-8";
  1629. string parsed;
  1630. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1631. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1632. }
  1633. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1634. // A ';' inside the quoted-string is part of the value, not a parameter
  1635. // separator, so it must not truncate the boundary.
  1636. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1637. string parsed;
  1638. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1639. EXPECT_EQ(parsed, "a;b");
  1640. }
  1641. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1642. string parsed;
  1643. EXPECT_TRUE(detail::parse_multipart_boundary(
  1644. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1645. EXPECT_EQ("a\\b", parsed);
  1646. EXPECT_TRUE(detail::parse_multipart_boundary(
  1647. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1648. EXPECT_EQ("a\"b", parsed);
  1649. }
  1650. TEST(ParseDispositionParamsTest, QuotedValues) {
  1651. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1652. // ';' and '=' are ordinary characters inside one.
  1653. struct {
  1654. const char *value;
  1655. std::vector<std::pair<const char *, const char *>> expected;
  1656. } cases[] = {
  1657. {"name=\"file1\"; filename=\"a.txt\"",
  1658. {{"name", "file1"}, {"filename", "a.txt"}}},
  1659. // Whitespace around '=' and ';' is still trimmed
  1660. {"name=\"file2\" ;filename = \"a.html\"",
  1661. {{"name", "file2"}, {"filename", "a.html"}}},
  1662. // '=' inside the value used to leave only the text after the last one
  1663. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1664. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1665. {"name=\"x=y\"", {{"name", "x=y"}}},
  1666. // ';' inside the value used to truncate the pair and leave a bogus one
  1667. {"name=\"file3\"; filename=\"a;b.txt\"",
  1668. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1669. // An unquoted value keeps working, and so does filename*
  1670. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1671. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1672. // A parameter with no key is dropped rather than turned into one whose
  1673. // key is the value
  1674. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1675. // An escaped quote does not end the value
  1676. {"name=\"a\\\"; filename=evil.php\"",
  1677. {{"name", "a\"; filename=evil.php"}}},
  1678. // Other backslashes, as in a Windows path, are kept
  1679. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1680. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1681. };
  1682. for (const auto &c : cases) {
  1683. Params params;
  1684. detail::parse_disposition_params(c.value, params);
  1685. for (const auto &kv : c.expected) {
  1686. auto it = params.find(kv.first);
  1687. ASSERT_NE(it, params.end())
  1688. << "value: " << c.value << ", key: " << kv.first;
  1689. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1690. }
  1691. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1692. }
  1693. }
  1694. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1695. Server svr;
  1696. std::string filename;
  1697. std::string content;
  1698. svr.Post("/upload", [&](const Request &req, Response &) {
  1699. const auto &file = req.form.get_file("file");
  1700. filename = file.filename;
  1701. content = file.content;
  1702. });
  1703. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1704. auto se = detail::scope_exit([&] {
  1705. svr.stop();
  1706. thread.join();
  1707. ASSERT_FALSE(svr.is_running());
  1708. });
  1709. svr.wait_until_ready();
  1710. std::string body = "--B\r\n"
  1711. "Content-Disposition: form-data; name=\"file\"; "
  1712. "filename=\"a.txt\"\r\n"
  1713. "Content-Type: text/plain\r\n"
  1714. "\r\n"
  1715. "hello\r\n"
  1716. "--B--\r\n";
  1717. Client cli(HOST, PORT);
  1718. auto res = cli.Post(
  1719. "/upload",
  1720. [&](size_t offset, DataSink &sink) {
  1721. if (offset < body.size()) {
  1722. sink.write(&body[offset], 1);
  1723. } else {
  1724. sink.done();
  1725. }
  1726. return true;
  1727. },
  1728. "multipart/form-data; boundary=B");
  1729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1730. EXPECT_EQ(StatusCode::OK_200, res->status);
  1731. EXPECT_EQ("a.txt", filename);
  1732. EXPECT_EQ("hello", content);
  1733. }
  1734. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1735. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1736. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1737. Server svr;
  1738. std::string field_value, file_name, file_filename;
  1739. bool has_field = false, has_file = false;
  1740. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1741. has_field = req.form.has_field("x=y");
  1742. field_value = req.form.get_field("x=y");
  1743. has_file = req.form.has_file("file1");
  1744. const auto &file = req.form.get_file("file1");
  1745. file_name = file.name;
  1746. file_filename = file.filename;
  1747. res.set_content("ok", "text/plain");
  1748. });
  1749. auto port = svr.bind_to_any_port(HOST);
  1750. thread t = thread([&] { svr.listen_after_bind(); });
  1751. auto se = detail::scope_exit([&] {
  1752. svr.stop();
  1753. t.join();
  1754. ASSERT_FALSE(svr.is_running());
  1755. });
  1756. svr.wait_until_ready();
  1757. UploadFormDataItems items = {
  1758. {"x=y", "field-value", "", ""},
  1759. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1760. };
  1761. Client cli(HOST, port);
  1762. auto res = cli.Post("/quoted", items);
  1763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1764. ASSERT_EQ(StatusCode::OK_200, res->status);
  1765. EXPECT_TRUE(has_field);
  1766. EXPECT_EQ("field-value", field_value);
  1767. EXPECT_TRUE(has_file);
  1768. EXPECT_EQ("file1", file_name);
  1769. EXPECT_EQ("a;b=report.pdf", file_filename);
  1770. }
  1771. TEST(GetHeaderValueTest, DefaultValue) {
  1772. Headers headers = {{"Dummy", "Dummy"}};
  1773. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1774. EXPECT_STREQ("text/plain", val);
  1775. }
  1776. TEST(GetHeaderValueTest, DefaultValueInt) {
  1777. Headers headers = {{"Dummy", "Dummy"}};
  1778. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1779. EXPECT_EQ(100ull, val);
  1780. }
  1781. TEST(GetHeaderValueTest, RegularValue) {
  1782. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1783. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1784. EXPECT_STREQ("text/html", val);
  1785. }
  1786. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1787. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1788. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1789. EXPECT_STREQ("text/html", val);
  1790. }
  1791. TEST(GetHeaderValueTest, SetContent) {
  1792. Response res;
  1793. res.set_content("html", "text/html");
  1794. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1795. res.set_content("text", "text/plain");
  1796. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1797. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1798. }
  1799. TEST(GetHeaderValueTest, RegularValueInt) {
  1800. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1801. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1802. EXPECT_EQ(100ull, val);
  1803. }
  1804. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1805. Headers headers = {{"Content-Length", "x"}};
  1806. auto is_invalid_value = false;
  1807. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1808. is_invalid_value);
  1809. EXPECT_EQ(0ull, val);
  1810. EXPECT_TRUE(is_invalid_value);
  1811. }
  1812. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1813. // An all-digit value that overflows size_t must be reported as invalid, not
  1814. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1815. // a large length to a small one on 32-bit builds, leaving the framing length
  1816. // wrong while is_invalid_value stayed false.
  1817. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1818. auto is_invalid_value = false;
  1819. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1820. is_invalid_value);
  1821. EXPECT_TRUE(is_invalid_value);
  1822. // A well-formed length is unaffected.
  1823. Headers ok = {{"Content-Length", "1234"}};
  1824. is_invalid_value = false;
  1825. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1826. is_invalid_value);
  1827. EXPECT_EQ(1234ull, val);
  1828. EXPECT_FALSE(is_invalid_value);
  1829. }
  1830. TEST(GetHeaderValueTest, Range) {
  1831. {
  1832. Headers headers = {make_range_header({{1, -1}})};
  1833. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1834. EXPECT_STREQ("bytes=1-", val);
  1835. }
  1836. {
  1837. Headers headers = {make_range_header({{-1, 1}})};
  1838. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1839. EXPECT_STREQ("bytes=-1", val);
  1840. }
  1841. {
  1842. Headers headers = {make_range_header({{1, 10}})};
  1843. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1844. EXPECT_STREQ("bytes=1-10", val);
  1845. }
  1846. {
  1847. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1848. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1849. EXPECT_STREQ("bytes=1-10, 100-", val);
  1850. }
  1851. {
  1852. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1853. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1854. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1855. }
  1856. {
  1857. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1858. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1859. EXPECT_STREQ("bytes=0-0, -1", val);
  1860. }
  1861. }
  1862. TEST(BearerTokenAuthTest, SchemeValidation) {
  1863. // A value shorter than "Bearer " must not throw from the fixed-length
  1864. // substr, and a non-Bearer scheme must not be reported as a token.
  1865. struct {
  1866. const char *value;
  1867. const char *expected;
  1868. } cases[] = {
  1869. {"x", ""},
  1870. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1871. {"Bearer abc123", "abc123"},
  1872. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1873. };
  1874. for (const auto &c : cases) {
  1875. Request req;
  1876. req.set_header("Authorization", c.value);
  1877. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1878. }
  1879. }
  1880. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1881. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1882. // to depend on the standard library (libstdc++ handed back duplicates in
  1883. // reverse insertion order, libc++ in insertion order).
  1884. Request req;
  1885. req.set_header("Accept-Encoding", "gzip");
  1886. req.set_header("Accept-Encoding", "deflate");
  1887. req.set_header("Accept-Encoding", "br");
  1888. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1889. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1890. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1891. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1892. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1893. }
  1894. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1895. Request req;
  1896. req.set_header("X-Test", "only");
  1897. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1898. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1899. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1900. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1901. }
  1902. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1903. Request req;
  1904. req.set_header("X-First", "1");
  1905. req.set_header("X-Test", "2");
  1906. req.params.emplace("first", "1");
  1907. req.params.emplace("test", "2");
  1908. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1909. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1910. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1911. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1912. // The second one is negative when read as a signed value
  1913. const auto max_id = (std::numeric_limits<size_t>::max)();
  1914. for (auto id : {max_id / 2, max_id}) {
  1915. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1916. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1917. EXPECT_EQ("", req.get_param_value("test", id));
  1918. EXPECT_EQ("", req.form.get_field("test", id));
  1919. EXPECT_EQ("", req.form.get_file("test", id).content);
  1920. }
  1921. }
  1922. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1923. Headers headers;
  1924. headers.emplace("Host", "example.com");
  1925. headers.emplace("Accept-Encoding", "gzip");
  1926. headers.emplace("User-Agent", "test");
  1927. headers.emplace("Accept-Encoding", "deflate");
  1928. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1929. "Accept-Encoding=deflate ",
  1930. entries_to_string(headers));
  1931. }
  1932. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1933. Headers headers = {{"Content-Type", "text/html"},
  1934. {"CONTENT-TYPE", "text/xml"}};
  1935. EXPECT_EQ(2U, headers.count("content-type"));
  1936. auto it = headers.find("content-type");
  1937. ASSERT_TRUE(it != headers.end());
  1938. EXPECT_EQ("text/html", it->second);
  1939. }
  1940. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1941. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1942. // drop only those fields and leave everything positioned between them.
  1943. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1944. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1945. auto rng = headers.equal_range("a");
  1946. headers.erase(rng.first, rng.second);
  1947. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1948. }
  1949. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1950. Headers headers = {
  1951. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1952. EXPECT_EQ(3U, headers.erase("A"));
  1953. EXPECT_EQ(0U, headers.count("A"));
  1954. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1955. }
  1956. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1957. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1958. headers.emplace_front("Host", "example.com");
  1959. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1960. entries_to_string(headers));
  1961. }
  1962. TEST(ParseHeaderValueTest, Range) {
  1963. {
  1964. Ranges ranges;
  1965. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1966. EXPECT_TRUE(ret);
  1967. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1968. }
  1969. {
  1970. Ranges ranges;
  1971. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1972. EXPECT_TRUE(ret);
  1973. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1974. }
  1975. {
  1976. Ranges ranges;
  1977. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1978. EXPECT_TRUE(ret);
  1979. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1980. }
  1981. {
  1982. Ranges ranges;
  1983. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1984. EXPECT_FALSE(ret);
  1985. }
  1986. {
  1987. Ranges ranges;
  1988. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1989. EXPECT_TRUE(ret);
  1990. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1991. }
  1992. {
  1993. Ranges ranges;
  1994. auto ret =
  1995. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1996. EXPECT_TRUE(ret);
  1997. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1998. }
  1999. {
  2000. Ranges ranges;
  2001. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2002. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2003. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2004. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2005. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2006. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2007. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2008. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2009. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2010. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2011. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2012. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2013. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2014. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2015. EXPECT_FALSE(
  2016. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2017. EXPECT_TRUE(ranges.empty());
  2018. }
  2019. {
  2020. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2021. // remainder of the representation, so it stays accepted.
  2022. Ranges ranges;
  2023. auto ret =
  2024. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2025. EXPECT_TRUE(ret);
  2026. ASSERT_EQ(1u, ranges.size());
  2027. EXPECT_EQ(0, ranges[0].first);
  2028. EXPECT_EQ(-1, ranges[0].second);
  2029. }
  2030. // RFC 9110 14.1: range unit names are case-insensitive.
  2031. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2032. Ranges ranges;
  2033. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2034. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2035. }
  2036. }
  2037. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2038. Request req;
  2039. req.set_header("Accept-Encoding", "gzip");
  2040. Response res;
  2041. res.set_header("Content-Type", "text/plain");
  2042. auto ret = detail::encoding_type(req, res);
  2043. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2044. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2045. #else
  2046. EXPECT_TRUE(ret == detail::EncodingType::None);
  2047. #endif
  2048. }
  2049. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2050. Request req;
  2051. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2052. Response res;
  2053. res.set_header("Content-Type", "text/plain");
  2054. auto ret = detail::encoding_type(req, res);
  2055. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2056. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2057. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2058. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2059. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2060. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2061. #else
  2062. EXPECT_TRUE(ret == detail::EncodingType::None);
  2063. #endif
  2064. }
  2065. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2066. Request req;
  2067. req.set_header("Accept-Encoding",
  2068. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2069. Response res;
  2070. res.set_header("Content-Type", "text/plain");
  2071. auto ret = detail::encoding_type(req, res);
  2072. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2073. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2074. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2075. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2076. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2077. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2078. #else
  2079. EXPECT_TRUE(ret == detail::EncodingType::None);
  2080. #endif
  2081. }
  2082. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2083. // All supported encodings rejected with q=0 should return None
  2084. Request req;
  2085. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2086. Response res;
  2087. res.set_header("Content-Type", "text/plain");
  2088. auto ret = detail::encoding_type(req, res);
  2089. EXPECT_TRUE(ret == detail::EncodingType::None);
  2090. }
  2091. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2092. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2093. Request req;
  2094. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2095. Response res;
  2096. res.set_header("Content-Type", "text/plain");
  2097. auto ret = detail::encoding_type(req, res);
  2098. EXPECT_TRUE(ret == detail::EncodingType::None);
  2099. }
  2100. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2101. Request req;
  2102. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2103. Response res;
  2104. res.set_header("Content-Type", "text/plain");
  2105. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2106. }
  2107. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2108. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2109. Request req;
  2110. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2111. Response res;
  2112. res.set_header("Content-Type", "text/plain");
  2113. auto ret = detail::encoding_type(req, res);
  2114. EXPECT_TRUE(ret == detail::EncodingType::None);
  2115. }
  2116. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2117. // RFC 7231: Accept-Encoding values are case-insensitive
  2118. Request req;
  2119. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2120. Response res;
  2121. res.set_header("Content-Type", "text/plain");
  2122. auto ret = detail::encoding_type(req, res);
  2123. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2124. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2125. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2126. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2127. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2128. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2129. #else
  2130. EXPECT_TRUE(ret == detail::EncodingType::None);
  2131. #endif
  2132. }
  2133. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2134. // q value should determine priority, not hardcoded order
  2135. Request req;
  2136. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2137. Response res;
  2138. res.set_header("Content-Type", "text/plain");
  2139. auto ret = detail::encoding_type(req, res);
  2140. // gzip has highest q=1.0, so it should be selected even though
  2141. // br and zstd are also supported
  2142. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2143. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2144. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2145. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2146. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2147. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2148. #else
  2149. EXPECT_TRUE(ret == detail::EncodingType::None);
  2150. #endif
  2151. }
  2152. TEST(BufferStreamTest, read) {
  2153. detail::BufferStream strm1;
  2154. Stream &strm = strm1;
  2155. EXPECT_EQ(5, strm.write("hello"));
  2156. char buf[512];
  2157. EXPECT_EQ(2, strm.read(buf, 2));
  2158. EXPECT_EQ('h', buf[0]);
  2159. EXPECT_EQ('e', buf[1]);
  2160. EXPECT_EQ(2, strm.read(buf, 2));
  2161. EXPECT_EQ('l', buf[0]);
  2162. EXPECT_EQ('l', buf[1]);
  2163. EXPECT_EQ(1, strm.read(buf, 1));
  2164. EXPECT_EQ('o', buf[0]);
  2165. EXPECT_EQ(0, strm.read(buf, 1));
  2166. }
  2167. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2168. auto host = "www.httpwatch.com";
  2169. auto ip = hosted_at(host);
  2170. EXPECT_EQ("23.96.13.243", ip);
  2171. std::vector<std::string> addrs;
  2172. hosted_at(host, addrs);
  2173. EXPECT_EQ(1u, addrs.size());
  2174. }
  2175. #if 0 // It depends on each test environment...
  2176. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2177. auto host = "www.youtube.com";
  2178. std::vector<std::string> addrs;
  2179. hosted_at(host, addrs);
  2180. EXPECT_EQ(20u, addrs.size());
  2181. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2182. EXPECT_TRUE(it != addrs.end());
  2183. }
  2184. #endif
  2185. class ChunkedEncodingTest : public ::testing::Test {
  2186. protected:
  2187. ChunkedEncodingTest()
  2188. : cli_(HOST, PORT)
  2189. #ifdef CPPHTTPLIB_SSL_ENABLED
  2190. ,
  2191. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2192. #endif
  2193. {
  2194. cli_.set_connection_timeout(2);
  2195. #ifdef CPPHTTPLIB_SSL_ENABLED
  2196. cli_.enable_server_certificate_verification(false);
  2197. #endif
  2198. }
  2199. virtual void SetUp() {
  2200. read_file("./image.jpg", image_data_);
  2201. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2202. res.set_content("Hello World!", "text/plain");
  2203. });
  2204. svr_.Get(
  2205. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2206. res.set_chunked_content_provider(
  2207. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2208. size_t remaining = image_data_.size() - offset;
  2209. if (remaining == 0) {
  2210. sink.done();
  2211. } else {
  2212. constexpr size_t CHUNK_SIZE = 1024;
  2213. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2214. sink.write(&image_data_[offset], send_size);
  2215. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2216. }
  2217. return true;
  2218. });
  2219. });
  2220. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2221. svr_.wait_until_ready();
  2222. }
  2223. virtual void TearDown() {
  2224. svr_.stop();
  2225. if (!request_threads_.empty()) {
  2226. std::this_thread::sleep_for(std::chrono::seconds(1));
  2227. for (auto &t : request_threads_) {
  2228. t.join();
  2229. }
  2230. }
  2231. t_.join();
  2232. }
  2233. #ifdef CPPHTTPLIB_SSL_ENABLED
  2234. SSLClient cli_;
  2235. SSLServer svr_;
  2236. #else
  2237. Client cli_;
  2238. Server svr_;
  2239. #endif
  2240. thread t_;
  2241. std::vector<thread> request_threads_;
  2242. std::string image_data_;
  2243. };
  2244. TEST_F(ChunkedEncodingTest, NormalGet) {
  2245. auto res = cli_.Get("/chunked");
  2246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2247. std::string out;
  2248. read_file("./image.jpg", out);
  2249. EXPECT_EQ(StatusCode::OK_200, res->status);
  2250. EXPECT_EQ(out, res->body);
  2251. }
  2252. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2253. std::string body;
  2254. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2255. body.append(data, data_length);
  2256. return true;
  2257. });
  2258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2259. std::string out;
  2260. read_file("./image.jpg", out);
  2261. EXPECT_EQ(StatusCode::OK_200, res->status);
  2262. EXPECT_EQ(out, body);
  2263. }
  2264. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2265. std::string body;
  2266. auto res = cli_.Get(
  2267. "/chunked",
  2268. [&](const Response &response) {
  2269. EXPECT_EQ(StatusCode::OK_200, response.status);
  2270. return true;
  2271. },
  2272. [&](const char *data, size_t data_length) {
  2273. body.append(data, data_length);
  2274. return true;
  2275. });
  2276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2277. std::string out;
  2278. read_file("./image.jpg", out);
  2279. EXPECT_EQ(StatusCode::OK_200, res->status);
  2280. EXPECT_EQ(out, body);
  2281. }
  2282. TEST(RangeTest, FromHTTPBin_Online) {
  2283. auto host = "httpbingo.org";
  2284. auto path = std::string{"/range/32"};
  2285. #ifdef CPPHTTPLIB_SSL_ENABLED
  2286. auto port = 443;
  2287. SSLClient cli(host, port);
  2288. #else
  2289. auto port = 80;
  2290. Client cli(host, port);
  2291. #endif
  2292. cli.set_connection_timeout(5);
  2293. {
  2294. auto res = cli.Get(path);
  2295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2296. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2297. EXPECT_EQ(StatusCode::OK_200, res->status);
  2298. }
  2299. {
  2300. Headers headers = {make_range_header({{1, -1}})};
  2301. auto res = cli.Get(path, headers);
  2302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2303. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2304. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2305. }
  2306. {
  2307. Headers headers = {make_range_header({{1, 10}})};
  2308. auto res = cli.Get(path, headers);
  2309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2310. EXPECT_EQ("bcdefghijk", res->body);
  2311. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2312. }
  2313. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2314. // entire resource, while the original httpbin returned 200. Both are
  2315. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2316. {
  2317. Headers headers = {make_range_header({{0, 31}})};
  2318. auto res = cli.Get(path, headers);
  2319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2320. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2321. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2322. res->status == StatusCode::PartialContent_206);
  2323. }
  2324. {
  2325. Headers headers = {make_range_header({{0, -1}})};
  2326. auto res = cli.Get(path, headers);
  2327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2328. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2329. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2330. res->status == StatusCode::PartialContent_206);
  2331. }
  2332. // go-httpbin returns 206 with clamped range for over-range requests,
  2333. // while the original httpbin returned 416. Both behaviors are observed
  2334. // in real servers, so we only verify the request succeeds.
  2335. {
  2336. Headers headers = {make_range_header({{0, 32}})};
  2337. auto res = cli.Get(path, headers);
  2338. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2339. }
  2340. }
  2341. TEST(RangeTest, IgnoredForPost) {
  2342. Server svr;
  2343. svr.Post("/", [](const Request &, Response &res) {
  2344. res.set_content("abcdefg", "text/plain");
  2345. });
  2346. auto port = svr.bind_to_any_port(HOST);
  2347. ASSERT_GT(port, 0);
  2348. thread t = thread([&] { svr.listen_after_bind(); });
  2349. auto se = detail::scope_exit([&] {
  2350. svr.stop();
  2351. t.join();
  2352. ASSERT_FALSE(svr.is_running());
  2353. });
  2354. svr.wait_until_ready();
  2355. Client cli(HOST, port);
  2356. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2357. auto res = cli.Post("/", Headers{{"Range", range}});
  2358. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2359. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2360. EXPECT_EQ("abcdefg", res->body) << range;
  2361. }
  2362. }
  2363. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2364. auto host = "unresolvableaddress.local";
  2365. auto path = std::string{"/"};
  2366. #ifdef CPPHTTPLIB_SSL_ENABLED
  2367. auto port = 443;
  2368. SSLClient cli(host, port);
  2369. #else
  2370. auto port = 80;
  2371. Client cli(host, port);
  2372. #endif
  2373. cli.set_connection_timeout(1);
  2374. {
  2375. auto res = cli.Get(path);
  2376. ASSERT_FALSE(res);
  2377. }
  2378. std::this_thread::sleep_for(std::chrono::seconds(8));
  2379. }
  2380. #if defined(__linux__) && defined(__GLIBC__) && \
  2381. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2382. // Forward declaration: in split builds split.py strips `inline` and moves the
  2383. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2384. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2385. // against the symbol in both header-only and split builds.
  2386. namespace httplib {
  2387. namespace detail {
  2388. int getaddrinfo_with_timeout(const char *node, const char *service,
  2389. const struct addrinfo *hints,
  2390. struct addrinfo **res, time_t timeout_sec);
  2391. } // namespace detail
  2392. } // namespace httplib
  2393. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2394. //
  2395. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2396. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2397. // gai_suspend() call hits the connection timeout the function calls
  2398. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2399. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2400. // still alive and still references the now-destroyed stack frame.
  2401. //
  2402. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2403. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2404. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2405. // and runs them in a container.
  2406. namespace {
  2407. bool should_run_issue_2431_tests() {
  2408. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2409. return v && *v && std::string(v) != "0";
  2410. }
  2411. std::string unique_unresolvable_host(int n) {
  2412. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2413. // glibc still asks the configured nameserver — which is exactly the path
  2414. // we want to exercise. A unique label per call avoids the resolver cache.
  2415. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2416. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2417. std::to_string(n) + ".invalid";
  2418. }
  2419. } // namespace
  2420. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2421. if (!should_run_issue_2431_tests()) {
  2422. GTEST_SKIP()
  2423. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2424. }
  2425. for (int i = 0; i < 8; ++i) {
  2426. struct addrinfo hints;
  2427. memset(&hints, 0, sizeof(hints));
  2428. hints.ai_family = AF_UNSPEC;
  2429. hints.ai_socktype = SOCK_STREAM;
  2430. auto host = unique_unresolvable_host(i);
  2431. struct addrinfo *result = nullptr;
  2432. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2433. &result, /*timeout_sec=*/1);
  2434. if (rc == 0 && result) { freeaddrinfo(result); }
  2435. }
  2436. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2437. // stack region they still believe holds their gaicb.
  2438. std::this_thread::sleep_for(std::chrono::seconds(3));
  2439. }
  2440. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2441. if (!should_run_issue_2431_tests()) {
  2442. GTEST_SKIP()
  2443. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2444. }
  2445. std::atomic<bool> stop{false};
  2446. std::vector<std::thread> threads;
  2447. for (int t = 0; t < 8; ++t) {
  2448. threads.emplace_back([t, &stop] {
  2449. int i = 0;
  2450. while (!stop.load(std::memory_order_relaxed)) {
  2451. struct addrinfo hints;
  2452. memset(&hints, 0, sizeof(hints));
  2453. hints.ai_family = AF_UNSPEC;
  2454. hints.ai_socktype = SOCK_STREAM;
  2455. auto host = unique_unresolvable_host(t * 100000 + i++);
  2456. struct addrinfo *result = nullptr;
  2457. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2458. &result, /*timeout_sec=*/1);
  2459. if (rc == 0 && result) { freeaddrinfo(result); }
  2460. }
  2461. });
  2462. }
  2463. std::this_thread::sleep_for(std::chrono::seconds(8));
  2464. stop.store(true, std::memory_order_relaxed);
  2465. for (auto &th : threads) {
  2466. th.join();
  2467. }
  2468. std::this_thread::sleep_for(std::chrono::seconds(3));
  2469. }
  2470. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2471. if (!should_run_issue_2431_tests()) {
  2472. GTEST_SKIP()
  2473. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2474. }
  2475. std::atomic<bool> stop{false};
  2476. std::vector<std::thread> threads;
  2477. for (int t = 0; t < 8; ++t) {
  2478. threads.emplace_back([t, &stop] {
  2479. int i = 0;
  2480. while (!stop.load(std::memory_order_relaxed)) {
  2481. auto host = unique_unresolvable_host(t * 100000 + i++);
  2482. Client cli(host, 80);
  2483. cli.set_connection_timeout(1, 0);
  2484. cli.set_read_timeout(1, 0);
  2485. cli.set_write_timeout(1, 0);
  2486. (void)cli.Get("/");
  2487. }
  2488. });
  2489. }
  2490. std::this_thread::sleep_for(std::chrono::seconds(8));
  2491. stop.store(true, std::memory_order_relaxed);
  2492. for (auto &th : threads) {
  2493. th.join();
  2494. }
  2495. std::this_thread::sleep_for(std::chrono::seconds(3));
  2496. }
  2497. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2498. TEST(ConnectionErrorTest, InvalidHost) {
  2499. auto host = "-abcde.com";
  2500. #ifdef CPPHTTPLIB_SSL_ENABLED
  2501. auto port = 443;
  2502. SSLClient cli(host, port);
  2503. #else
  2504. auto port = 80;
  2505. Client cli(host, port);
  2506. #endif
  2507. cli.set_connection_timeout(std::chrono::seconds(2));
  2508. auto res = cli.Get("/");
  2509. ASSERT_TRUE(!res);
  2510. EXPECT_EQ(Error::Connection, res.error());
  2511. }
  2512. TEST(ConnectionErrorTest, InvalidHost2) {
  2513. auto host = "httpcan.org/";
  2514. #ifdef CPPHTTPLIB_SSL_ENABLED
  2515. SSLClient cli(host);
  2516. #else
  2517. Client cli(host);
  2518. #endif
  2519. cli.set_connection_timeout(std::chrono::seconds(2));
  2520. auto res = cli.Get("/");
  2521. ASSERT_TRUE(!res);
  2522. EXPECT_EQ(Error::Connection, res.error());
  2523. }
  2524. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2525. auto host = "httpcan.org/";
  2526. #ifdef CPPHTTPLIB_SSL_ENABLED
  2527. SSLClient cli(host);
  2528. #else
  2529. Client cli(host);
  2530. #endif
  2531. cli.set_connection_timeout(std::chrono::seconds(2));
  2532. auto res = cli.Get("/");
  2533. ASSERT_TRUE(!res);
  2534. stringstream s;
  2535. s << "error code: " << res.error();
  2536. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2537. }
  2538. TEST(ConnectionErrorTest, InvalidPort) {
  2539. auto host = "localhost";
  2540. auto port = 44380;
  2541. #ifdef CPPHTTPLIB_SSL_ENABLED
  2542. SSLClient cli(host, port);
  2543. #else
  2544. Client cli(host, port);
  2545. #endif
  2546. cli.set_connection_timeout(std::chrono::seconds(2));
  2547. auto res = cli.Get("/");
  2548. ASSERT_TRUE(!res);
  2549. EXPECT_TRUE(Error::Connection == res.error() ||
  2550. Error::ConnectionTimeout == res.error());
  2551. }
  2552. TEST(ConnectionErrorTest, Timeout_Online) {
  2553. auto host = "google.com";
  2554. #ifdef CPPHTTPLIB_SSL_ENABLED
  2555. auto port = 44380;
  2556. SSLClient cli(host, port);
  2557. #else
  2558. auto port = 8080;
  2559. Client cli(host, port);
  2560. #endif
  2561. cli.set_connection_timeout(std::chrono::seconds(2));
  2562. // only probe one address type so that the error reason
  2563. // correlates to the timed-out IPv4, not the unsupported
  2564. // IPv6 connection attempt
  2565. cli.set_address_family(AF_INET);
  2566. auto res = cli.Get("/");
  2567. ASSERT_TRUE(!res);
  2568. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2569. }
  2570. TEST(CancelTest, NoCancel_Online) {
  2571. auto host = "httpbingo.org";
  2572. auto path = std::string{"/range/32"};
  2573. #ifdef CPPHTTPLIB_SSL_ENABLED
  2574. auto port = 443;
  2575. SSLClient cli(host, port);
  2576. #else
  2577. auto port = 80;
  2578. Client cli(host, port);
  2579. #endif
  2580. cli.set_connection_timeout(std::chrono::seconds(5));
  2581. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2583. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2584. EXPECT_EQ(StatusCode::OK_200, res->status);
  2585. }
  2586. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2587. // Use /bytes with a large payload so that the DownloadProgress callback
  2588. // (which only fires for Content-Length responses) is invoked before the
  2589. // entire body is received, giving cancellation a chance to fire.
  2590. auto host = "httpbingo.org";
  2591. auto path = std::string{"/bytes/524288"};
  2592. #ifdef CPPHTTPLIB_SSL_ENABLED
  2593. auto port = 443;
  2594. SSLClient cli(host, port);
  2595. #else
  2596. auto port = 80;
  2597. Client cli(host, port);
  2598. #endif
  2599. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2600. cli.set_connection_timeout(std::chrono::seconds(5));
  2601. ASSERT_TRUE(!res);
  2602. EXPECT_EQ(Error::Canceled, res.error());
  2603. }
  2604. TEST(CancelTest, WithCancelLargePayload_Online) {
  2605. auto host = "httpbingo.org";
  2606. auto path = std::string{"/bytes/524288"};
  2607. #ifdef CPPHTTPLIB_SSL_ENABLED
  2608. auto port = 443;
  2609. SSLClient cli(host, port);
  2610. #else
  2611. auto port = 80;
  2612. Client cli(host, port);
  2613. #endif
  2614. cli.set_connection_timeout(std::chrono::seconds(5));
  2615. uint32_t count = 0;
  2616. auto res =
  2617. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2618. ASSERT_TRUE(!res);
  2619. EXPECT_EQ(Error::Canceled, res.error());
  2620. }
  2621. TEST(CancelTest, NoCancelPost) {
  2622. Server svr;
  2623. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2624. res.set_content("Hello World!", "text/plain");
  2625. });
  2626. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2627. auto se = detail::scope_exit([&] {
  2628. svr.stop();
  2629. thread.join();
  2630. ASSERT_FALSE(svr.is_running());
  2631. });
  2632. svr.wait_until_ready();
  2633. Client cli(HOST, PORT);
  2634. cli.set_connection_timeout(std::chrono::seconds(5));
  2635. auto res =
  2636. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2637. "application/json", [](uint64_t, uint64_t) { return true; });
  2638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2639. EXPECT_EQ("Hello World!", res->body);
  2640. EXPECT_EQ(StatusCode::OK_200, res->status);
  2641. }
  2642. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2643. Server svr;
  2644. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2645. res.set_content("Hello World!", "text/plain");
  2646. });
  2647. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2648. auto se = detail::scope_exit([&] {
  2649. svr.stop();
  2650. thread.join();
  2651. ASSERT_FALSE(svr.is_running());
  2652. });
  2653. svr.wait_until_ready();
  2654. Client cli(HOST, PORT);
  2655. cli.set_connection_timeout(std::chrono::seconds(5));
  2656. auto res =
  2657. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2658. "application/json", [](uint64_t, uint64_t) { return false; });
  2659. ASSERT_TRUE(!res);
  2660. EXPECT_EQ(Error::Canceled, res.error());
  2661. }
  2662. TEST(CancelTest, WithCancelLargePayloadPost) {
  2663. Server svr;
  2664. svr.set_payload_max_length(200 * 1024 * 1024);
  2665. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2666. res.set_content(LARGE_DATA, "text/plain");
  2667. });
  2668. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2669. auto se = detail::scope_exit([&] {
  2670. svr.stop();
  2671. thread.join();
  2672. ASSERT_FALSE(svr.is_running());
  2673. });
  2674. svr.wait_until_ready();
  2675. Client cli(HOST, PORT);
  2676. cli.set_payload_max_length(200 * 1024 * 1024);
  2677. cli.set_connection_timeout(std::chrono::seconds(5));
  2678. auto res =
  2679. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2680. "application/json", [](uint64_t, uint64_t) { return false; });
  2681. ASSERT_TRUE(!res);
  2682. EXPECT_EQ(Error::Canceled, res.error());
  2683. }
  2684. TEST(CancelTest, NoCancelPut) {
  2685. Server svr;
  2686. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2687. res.set_content("Hello World!", "text/plain");
  2688. });
  2689. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2690. auto se = detail::scope_exit([&] {
  2691. svr.stop();
  2692. thread.join();
  2693. ASSERT_FALSE(svr.is_running());
  2694. });
  2695. svr.wait_until_ready();
  2696. Client cli(HOST, PORT);
  2697. cli.set_connection_timeout(std::chrono::seconds(5));
  2698. auto res =
  2699. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2700. "application/json", [](uint64_t, uint64_t) { return true; });
  2701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2702. EXPECT_EQ("Hello World!", res->body);
  2703. EXPECT_EQ(StatusCode::OK_200, res->status);
  2704. }
  2705. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2706. Server svr;
  2707. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2708. res.set_content("Hello World!", "text/plain");
  2709. });
  2710. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2711. auto se = detail::scope_exit([&] {
  2712. svr.stop();
  2713. thread.join();
  2714. ASSERT_FALSE(svr.is_running());
  2715. });
  2716. svr.wait_until_ready();
  2717. Client cli(HOST, PORT);
  2718. cli.set_connection_timeout(std::chrono::seconds(5));
  2719. auto res =
  2720. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2721. "application/json", [](uint64_t, uint64_t) { return false; });
  2722. ASSERT_TRUE(!res);
  2723. EXPECT_EQ(Error::Canceled, res.error());
  2724. }
  2725. TEST(CancelTest, WithCancelLargePayloadPut) {
  2726. Server svr;
  2727. svr.set_payload_max_length(200 * 1024 * 1024);
  2728. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2729. res.set_content(LARGE_DATA, "text/plain");
  2730. });
  2731. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2732. auto se = detail::scope_exit([&] {
  2733. svr.stop();
  2734. thread.join();
  2735. ASSERT_FALSE(svr.is_running());
  2736. });
  2737. svr.wait_until_ready();
  2738. Client cli(HOST, PORT);
  2739. cli.set_payload_max_length(200 * 1024 * 1024);
  2740. cli.set_connection_timeout(std::chrono::seconds(5));
  2741. auto res =
  2742. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2743. "application/json", [](uint64_t, uint64_t) { return false; });
  2744. ASSERT_TRUE(!res);
  2745. EXPECT_EQ(Error::Canceled, res.error());
  2746. }
  2747. TEST(CancelTest, NoCancelPatch) {
  2748. Server svr;
  2749. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2750. res.set_content("Hello World!", "text/plain");
  2751. });
  2752. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2753. auto se = detail::scope_exit([&] {
  2754. svr.stop();
  2755. thread.join();
  2756. ASSERT_FALSE(svr.is_running());
  2757. });
  2758. svr.wait_until_ready();
  2759. Client cli(HOST, PORT);
  2760. cli.set_connection_timeout(std::chrono::seconds(5));
  2761. auto res =
  2762. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2763. "application/json", [](uint64_t, uint64_t) { return true; });
  2764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2765. EXPECT_EQ("Hello World!", res->body);
  2766. EXPECT_EQ(StatusCode::OK_200, res->status);
  2767. }
  2768. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2769. Server svr;
  2770. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2771. res.set_content("Hello World!", "text/plain");
  2772. });
  2773. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2774. auto se = detail::scope_exit([&] {
  2775. svr.stop();
  2776. thread.join();
  2777. ASSERT_FALSE(svr.is_running());
  2778. });
  2779. svr.wait_until_ready();
  2780. Client cli(HOST, PORT);
  2781. cli.set_connection_timeout(std::chrono::seconds(5));
  2782. auto res =
  2783. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2784. "application/json", [](uint64_t, uint64_t) { return false; });
  2785. ASSERT_TRUE(!res);
  2786. EXPECT_EQ(Error::Canceled, res.error());
  2787. }
  2788. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2789. Server svr;
  2790. svr.set_payload_max_length(200 * 1024 * 1024);
  2791. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2792. res.set_content(LARGE_DATA, "text/plain");
  2793. });
  2794. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2795. auto se = detail::scope_exit([&] {
  2796. svr.stop();
  2797. thread.join();
  2798. ASSERT_FALSE(svr.is_running());
  2799. });
  2800. svr.wait_until_ready();
  2801. Client cli(HOST, PORT);
  2802. cli.set_payload_max_length(200 * 1024 * 1024);
  2803. cli.set_connection_timeout(std::chrono::seconds(5));
  2804. auto res =
  2805. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2806. "application/json", [](uint64_t, uint64_t) { return false; });
  2807. ASSERT_TRUE(!res);
  2808. EXPECT_EQ(Error::Canceled, res.error());
  2809. }
  2810. TEST(CancelTest, NoCancelDelete) {
  2811. Server svr;
  2812. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2813. res.set_content("Hello World!", "text/plain");
  2814. });
  2815. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2816. auto se = detail::scope_exit([&] {
  2817. svr.stop();
  2818. thread.join();
  2819. ASSERT_FALSE(svr.is_running());
  2820. });
  2821. svr.wait_until_ready();
  2822. Client cli(HOST, PORT);
  2823. cli.set_connection_timeout(std::chrono::seconds(5));
  2824. auto res =
  2825. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2826. "application/json", [](uint64_t, uint64_t) { return true; });
  2827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2828. EXPECT_EQ("Hello World!", res->body);
  2829. EXPECT_EQ(StatusCode::OK_200, res->status);
  2830. }
  2831. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2832. Server svr;
  2833. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2834. res.set_content("Hello World!", "text/plain");
  2835. });
  2836. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2837. auto se = detail::scope_exit([&] {
  2838. svr.stop();
  2839. thread.join();
  2840. ASSERT_FALSE(svr.is_running());
  2841. });
  2842. svr.wait_until_ready();
  2843. Client cli(HOST, PORT);
  2844. cli.set_connection_timeout(std::chrono::seconds(5));
  2845. auto res =
  2846. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2847. "application/json", [](uint64_t, uint64_t) { return false; });
  2848. ASSERT_TRUE(!res);
  2849. EXPECT_EQ(Error::Canceled, res.error());
  2850. }
  2851. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2852. Server svr;
  2853. svr.set_payload_max_length(200 * 1024 * 1024);
  2854. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2855. res.set_content(LARGE_DATA, "text/plain");
  2856. });
  2857. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2858. auto se = detail::scope_exit([&] {
  2859. svr.stop();
  2860. thread.join();
  2861. ASSERT_FALSE(svr.is_running());
  2862. });
  2863. svr.wait_until_ready();
  2864. Client cli(HOST, PORT);
  2865. cli.set_payload_max_length(200 * 1024 * 1024);
  2866. cli.set_connection_timeout(std::chrono::seconds(5));
  2867. auto res =
  2868. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2869. "application/json", [](uint64_t, uint64_t) { return false; });
  2870. ASSERT_TRUE(!res);
  2871. EXPECT_EQ(Error::Canceled, res.error());
  2872. }
  2873. static std::string remove_whitespace(const std::string &input) {
  2874. std::string output;
  2875. output.reserve(input.size());
  2876. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2877. [](unsigned char c) { return !std::isspace(c); });
  2878. return output;
  2879. }
  2880. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2881. auto host = "httpbingo.org";
  2882. auto path = std::string{"/basic-auth/hello/world"};
  2883. #ifdef CPPHTTPLIB_SSL_ENABLED
  2884. auto port = 443;
  2885. SSLClient cli(host, port);
  2886. #else
  2887. auto port = 80;
  2888. Client cli(host, port);
  2889. #endif
  2890. {
  2891. auto res = cli.Get(path);
  2892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2893. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2894. }
  2895. {
  2896. auto res = cli.Get(
  2897. path, Headers{make_basic_authentication_header("hello", "world")});
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. auto body = remove_whitespace(res->body);
  2900. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2901. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2902. EXPECT_EQ(StatusCode::OK_200, res->status);
  2903. }
  2904. {
  2905. cli.set_basic_auth("hello", "world");
  2906. auto res = cli.Get(path);
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. auto body = remove_whitespace(res->body);
  2909. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2910. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2911. EXPECT_EQ(StatusCode::OK_200, res->status);
  2912. }
  2913. {
  2914. cli.set_basic_auth("hello", "bad");
  2915. auto res = cli.Get(path);
  2916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2917. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2918. }
  2919. {
  2920. cli.set_basic_auth("bad", "world");
  2921. auto res = cli.Get(path);
  2922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2923. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2924. }
  2925. }
  2926. #ifdef CPPHTTPLIB_SSL_ENABLED
  2927. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2928. auto host = "httpbingo.org";
  2929. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2930. auto paths = std::vector<std::string>{
  2931. "/digest-auth/auth/hello/world/MD5",
  2932. "/digest-auth/auth/hello/world/SHA-256",
  2933. };
  2934. auto port = 443;
  2935. SSLClient cli(host, port);
  2936. {
  2937. auto res = cli.Get(unauth_path);
  2938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2939. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2940. }
  2941. {
  2942. cli.set_digest_auth("hello", "world");
  2943. for (const auto &path : paths) {
  2944. auto res = cli.Get(path.c_str());
  2945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2946. auto body = remove_whitespace(res->body);
  2947. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2948. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2949. EXPECT_EQ(StatusCode::OK_200, res->status);
  2950. }
  2951. cli.set_digest_auth("hello", "bad");
  2952. for (const auto &path : paths) {
  2953. auto res = cli.Get(path.c_str());
  2954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2955. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2956. }
  2957. }
  2958. }
  2959. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2960. // comma-separated list of challenges, and each challenge may itself carry a
  2961. // comma-separated auth-param list, so a server can legally offer Basic
  2962. // before Digest, either as two field lines or packed into one. Runs one 401
  2963. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2964. // value() joins them in receipt order) and checks that the retry carries a
  2965. // well-formed Digest Authorization header naming expected_realm.
  2966. static void
  2967. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2968. const std::string &expected_realm) {
  2969. std::atomic<int> hits{0};
  2970. Server svr;
  2971. svr.Get("/x", [&](const Request &req, Response &res) {
  2972. if (++hits == 1) {
  2973. res.status = StatusCode::Unauthorized_401;
  2974. for (const auto &challenge : challenges) {
  2975. res.set_header("WWW-Authenticate", challenge);
  2976. }
  2977. } else {
  2978. auto authorization = req.get_header_value("Authorization");
  2979. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2980. EXPECT_NE(std::string::npos,
  2981. authorization.find("realm=\"" + expected_realm + "\""));
  2982. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2983. res.set_content("ok", "text/plain");
  2984. }
  2985. });
  2986. auto port = svr.bind_to_any_port(HOST);
  2987. std::thread t([&]() { svr.listen_after_bind(); });
  2988. auto se = detail::scope_exit([&] {
  2989. svr.stop();
  2990. t.join();
  2991. });
  2992. svr.wait_until_ready();
  2993. Client cli(HOST, port);
  2994. cli.set_digest_auth("hello", "world");
  2995. auto res = cli.Get("/x");
  2996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2997. EXPECT_EQ(2, hits.load());
  2998. }
  2999. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3000. static const char *kDigestChallenge =
  3001. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3002. "algorithm=MD5";
  3003. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3004. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3005. "testrealm");
  3006. }
  3007. // Same challenge list with the schemes in the opposite order, to make sure
  3008. // the fix above didn't just special-case "Basic first".
  3009. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3010. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3011. "testrealm");
  3012. }
  3013. // A comma inside a quoted auth-param value must not be mistaken for the
  3014. // separator between two challenges (or two auth-params).
  3015. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3016. run_digest_challenge_list_test(
  3017. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3018. "algorithm=MD5"},
  3019. "test,realm");
  3020. }
  3021. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3022. // the params and leaves out the fragment.
  3023. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3024. Server svr;
  3025. std::string uri, target;
  3026. svr.Get("/a b", [&](const Request &req, Response &res) {
  3027. auto auth = req.get_header_value("Authorization");
  3028. if (auth.empty()) {
  3029. res.status = StatusCode::Unauthorized_401;
  3030. res.set_header("WWW-Authenticate",
  3031. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3032. return;
  3033. }
  3034. auto b = auth.find("uri=\"") + 5;
  3035. uri = auth.substr(b, auth.find('"', b) - b);
  3036. target = req.target;
  3037. });
  3038. auto port = svr.bind_to_any_port(HOST);
  3039. std::thread t([&]() { svr.listen_after_bind(); });
  3040. auto se = detail::scope_exit([&] {
  3041. svr.stop();
  3042. t.join();
  3043. });
  3044. svr.wait_until_ready();
  3045. Client cli(HOST, port);
  3046. cli.set_digest_auth("hello", "world");
  3047. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3049. EXPECT_EQ("/a%20b?x=1", target);
  3050. EXPECT_EQ(target, uri);
  3051. }
  3052. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3053. // make_digest_authentication_header() dereferences both unconditionally, so
  3054. // a server sending a challenge missing either one must not be treated as
  3055. // usable -- doing so used to crash the client with std::out_of_range.
  3056. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3057. Server svr;
  3058. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3059. res.status = StatusCode::Unauthorized_401;
  3060. res.set_header("WWW-Authenticate", challenge);
  3061. });
  3062. auto port = svr.bind_to_any_port(HOST);
  3063. std::thread t([&]() { svr.listen_after_bind(); });
  3064. auto se = detail::scope_exit([&] {
  3065. svr.stop();
  3066. t.join();
  3067. });
  3068. svr.wait_until_ready();
  3069. Client cli(HOST, port);
  3070. cli.set_digest_auth("hello", "world");
  3071. auto res = cli.Get("/x");
  3072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3073. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3074. }
  3075. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3076. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3077. }
  3078. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3079. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3080. }
  3081. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3082. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3083. }
  3084. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3085. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3086. // when storing the values, so the header builder has to re-escape them (and
  3087. // keep algorithm a bare token); otherwise the value breaks out of its
  3088. // quoted-string and injects extra auth-params into the client's Authorization.
  3089. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3090. std::atomic<int> hits{0};
  3091. std::string authorization;
  3092. Server svr;
  3093. svr.Get("/x", [&](const Request &req, Response &res) {
  3094. if (++hits == 1) {
  3095. res.status = StatusCode::Unauthorized_401;
  3096. // On the wire the quotes embedded in the values are backslash-escaped.
  3097. res.set_header("WWW-Authenticate",
  3098. "Digest realm=\"testrealm\", "
  3099. "nonce=\"n\\\"; injected=\\\"x\", "
  3100. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3101. } else {
  3102. authorization = req.get_header_value("Authorization");
  3103. res.set_content("ok", "text/plain");
  3104. }
  3105. });
  3106. auto port = svr.bind_to_any_port(HOST);
  3107. std::thread t([&]() { svr.listen_after_bind(); });
  3108. auto se = detail::scope_exit([&] {
  3109. svr.stop();
  3110. t.join();
  3111. });
  3112. svr.wait_until_ready();
  3113. Client cli(HOST, port);
  3114. cli.set_digest_auth("hello", "world");
  3115. auto res = cli.Get("/x");
  3116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3117. EXPECT_EQ(2, hits.load());
  3118. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3119. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3120. // inside its quoted-string rather than starting an "injected" auth-param.
  3121. EXPECT_NE(std::string::npos,
  3122. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3123. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3124. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3125. }
  3126. #endif
  3127. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3128. auto host = "google.com";
  3129. auto another_host = "example.com";
  3130. auto wrong_ip = "0.0.0.0";
  3131. #ifdef CPPHTTPLIB_SSL_ENABLED
  3132. SSLClient cli(host);
  3133. #else
  3134. Client cli(host);
  3135. #endif
  3136. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3137. auto res = cli.Get("/");
  3138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3139. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3140. }
  3141. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3142. auto host = "google.com";
  3143. auto wrong_ip = "0.0.0.0";
  3144. #ifdef CPPHTTPLIB_SSL_ENABLED
  3145. SSLClient cli(host);
  3146. #else
  3147. Client cli(host);
  3148. #endif
  3149. cli.set_hostname_addr_map({{host, wrong_ip}});
  3150. auto res = cli.Get("/");
  3151. ASSERT_TRUE(!res);
  3152. EXPECT_EQ(Error::Connection, res.error());
  3153. }
  3154. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3155. // A mapped value that is not an IP literal must be resolved. "localhost"
  3156. // resolves from the hosts file, so this test needs no external DNS.
  3157. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3158. auto host = "target.invalid";
  3159. Server svr;
  3160. std::string received_host;
  3161. svr.Get("/hi", [&](const Request &req, Response &res) {
  3162. received_host = req.get_header_value("Host");
  3163. res.set_content("Hello World!", "text/plain");
  3164. });
  3165. auto port = svr.bind_to_any_port(HOST);
  3166. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3167. auto se = detail::scope_exit([&] {
  3168. svr.stop();
  3169. thread.join();
  3170. ASSERT_FALSE(svr.is_running());
  3171. });
  3172. svr.wait_until_ready();
  3173. Client cli(host, port);
  3174. cli.set_hostname_addr_map({{host, HOST}});
  3175. auto res = cli.Get("/hi");
  3176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3177. EXPECT_EQ(StatusCode::OK_200, res->status);
  3178. // The mapping only redirects the connection; the identity stays host_.
  3179. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3180. }
  3181. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3182. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3183. auto host = "target.invalid";
  3184. Server svr;
  3185. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3186. res.set_content("Hello World!", "text/plain");
  3187. });
  3188. auto port = svr.bind_to_any_port("127.0.0.1");
  3189. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3190. auto se = detail::scope_exit([&] {
  3191. svr.stop();
  3192. thread.join();
  3193. ASSERT_FALSE(svr.is_running());
  3194. });
  3195. svr.wait_until_ready();
  3196. Client cli(host, port);
  3197. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3198. auto res = cli.Get("/hi");
  3199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3200. EXPECT_EQ(StatusCode::OK_200, res->status);
  3201. }
  3202. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3203. // An empty mapped value must leave host_ as the connection target. Without
  3204. // that guard the empty value would become the host argument, getaddrinfo
  3205. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3206. // loopback - silently connecting somewhere the caller never asked for.
  3207. // The server listens on loopback, so such a fallback would succeed and is
  3208. // therefore observable as a failure of this test.
  3209. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3210. Server svr;
  3211. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3212. res.set_content("Hello World!", "text/plain");
  3213. });
  3214. auto port = svr.bind_to_any_port(HOST);
  3215. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3216. auto se = detail::scope_exit([&] {
  3217. svr.stop();
  3218. thread.join();
  3219. ASSERT_FALSE(svr.is_running());
  3220. });
  3221. svr.wait_until_ready();
  3222. Client cli(blackhole, port);
  3223. cli.set_hostname_addr_map({{blackhole, ""}});
  3224. cli.set_connection_timeout(1);
  3225. auto res = cli.Get("/hi");
  3226. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3227. }
  3228. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3229. auto host = "httpbingo.org";
  3230. auto path = std::string{"/absolute-redirect/3"};
  3231. #ifdef CPPHTTPLIB_SSL_ENABLED
  3232. SSLClient cli(host);
  3233. #else
  3234. Client cli(host);
  3235. #endif
  3236. cli.set_follow_location(true);
  3237. auto res = cli.Get(path);
  3238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3239. EXPECT_EQ(StatusCode::OK_200, res->status);
  3240. }
  3241. TEST(RedirectTest, Redirect_Online) {
  3242. auto host = "httpbingo.org";
  3243. auto path = std::string{"/redirect/3"};
  3244. #ifdef CPPHTTPLIB_SSL_ENABLED
  3245. SSLClient cli(host);
  3246. #else
  3247. Client cli(host);
  3248. #endif
  3249. cli.set_follow_location(true);
  3250. auto res = cli.Get(path);
  3251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3252. EXPECT_EQ(StatusCode::OK_200, res->status);
  3253. }
  3254. TEST(RelativeRedirectTest, Redirect_Online) {
  3255. auto host = "httpbingo.org";
  3256. auto path = std::string{"/relative-redirect/3"};
  3257. #ifdef CPPHTTPLIB_SSL_ENABLED
  3258. SSLClient cli(host);
  3259. #else
  3260. Client cli(host);
  3261. #endif
  3262. cli.set_follow_location(true);
  3263. auto res = cli.Get(path);
  3264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3265. EXPECT_EQ(StatusCode::OK_200, res->status);
  3266. }
  3267. TEST(TooManyRedirectTest, Redirect_Online) {
  3268. auto host = "httpbingo.org";
  3269. auto path = std::string{"/redirect/21"};
  3270. #ifdef CPPHTTPLIB_SSL_ENABLED
  3271. SSLClient cli(host);
  3272. #else
  3273. Client cli(host);
  3274. #endif
  3275. cli.set_follow_location(true);
  3276. auto res = cli.Get(path);
  3277. ASSERT_TRUE(!res);
  3278. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3279. }
  3280. #ifdef CPPHTTPLIB_SSL_ENABLED
  3281. TEST(YahooRedirectTest, Redirect_Online) {
  3282. Client cli("yahoo.com");
  3283. auto res = cli.Get("/");
  3284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3285. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3286. cli.set_follow_location(true);
  3287. res = cli.Get("/");
  3288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3289. EXPECT_EQ(StatusCode::OK_200, res->status);
  3290. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3291. }
  3292. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3293. #define REDIR_HOST "httpbingo.org"
  3294. #define REDIR_PATH "/redirect-to"
  3295. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3296. SSLClient cli(REDIR_HOST);
  3297. cli.set_follow_location(true);
  3298. auto res =
  3299. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3301. EXPECT_EQ(StatusCode::OK_200, res->status);
  3302. }
  3303. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3304. SSLClient cli(REDIR_HOST);
  3305. cli.set_follow_location(true);
  3306. Params params;
  3307. params.emplace("url", "http://example.com");
  3308. params.emplace("status_code", "302");
  3309. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3311. EXPECT_EQ(StatusCode::OK_200, res->status);
  3312. }
  3313. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3314. SSLClient cli(REDIR_HOST);
  3315. cli.set_follow_location(true);
  3316. Params params;
  3317. params.emplace("url", "http://example.com");
  3318. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3320. EXPECT_EQ(StatusCode::OK_200, res->status);
  3321. }
  3322. TEST(UrlWithSpace, Redirect_Online) {
  3323. SSLClient cli("edge.forgecdn.net");
  3324. cli.set_follow_location(true);
  3325. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3327. EXPECT_EQ(StatusCode::OK_200, res->status);
  3328. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3329. }
  3330. #endif
  3331. #if !defined(_WIN32) && !defined(_WIN64)
  3332. TEST(ReceiveSignals, Signal) {
  3333. auto setupSignalHandlers = []() {
  3334. struct sigaction act;
  3335. sigemptyset(&act.sa_mask);
  3336. act.sa_flags = SA_SIGINFO;
  3337. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3338. switch (sig) {
  3339. case SIGINT:
  3340. default: break;
  3341. }
  3342. };
  3343. ::sigaction(SIGINT, &act, nullptr);
  3344. };
  3345. Server svr;
  3346. int port = 0;
  3347. auto thread = std::thread([&]() {
  3348. setupSignalHandlers();
  3349. port = svr.bind_to_any_port(HOST);
  3350. svr.listen_after_bind();
  3351. });
  3352. auto se = detail::scope_exit([&] {
  3353. svr.stop();
  3354. thread.join();
  3355. ASSERT_FALSE(svr.is_running());
  3356. });
  3357. svr.wait_until_ready();
  3358. ASSERT_TRUE(svr.is_running());
  3359. pthread_kill(thread.native_handle(), SIGINT);
  3360. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3361. ASSERT_TRUE(svr.is_running());
  3362. }
  3363. #endif
  3364. TEST(RedirectToDifferentPort, Redirect) {
  3365. Server svr1;
  3366. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3367. res.set_content("Hello World!", "text/plain");
  3368. });
  3369. int svr1_port = 0;
  3370. auto thread1 = std::thread([&]() {
  3371. svr1_port = svr1.bind_to_any_port(HOST);
  3372. svr1.listen_after_bind();
  3373. });
  3374. Server svr2;
  3375. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3376. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3377. });
  3378. int svr2_port = 0;
  3379. auto thread2 = std::thread([&]() {
  3380. svr2_port = svr2.bind_to_any_port(HOST);
  3381. svr2.listen_after_bind();
  3382. });
  3383. auto se = detail::scope_exit([&] {
  3384. svr2.stop();
  3385. thread2.join();
  3386. svr1.stop();
  3387. thread1.join();
  3388. ASSERT_FALSE(svr2.is_running());
  3389. ASSERT_FALSE(svr1.is_running());
  3390. });
  3391. svr1.wait_until_ready();
  3392. svr2.wait_until_ready();
  3393. Client cli("localhost", svr2_port);
  3394. cli.set_follow_location(true);
  3395. auto res = cli.Get("/2");
  3396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3397. EXPECT_EQ(StatusCode::OK_200, res->status);
  3398. EXPECT_EQ("Hello World!", res->body);
  3399. }
  3400. // GET /redir on one server redirects to /target on another port, so the
  3401. // client follows it with a new client.
  3402. static Result
  3403. GetThroughRedirectToDifferentPort(Server::Handler target,
  3404. const std::function<void(Client &)> &setup,
  3405. const Headers &headers = Headers()) {
  3406. Server target_svr;
  3407. target_svr.Get("/target", target);
  3408. int target_port = 0;
  3409. auto target_thread = std::thread([&]() {
  3410. target_port = target_svr.bind_to_any_port(HOST);
  3411. target_svr.listen_after_bind();
  3412. });
  3413. Server origin_svr;
  3414. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3415. res.set_redirect(
  3416. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3417. });
  3418. int origin_port = 0;
  3419. auto origin_thread = std::thread([&]() {
  3420. origin_port = origin_svr.bind_to_any_port(HOST);
  3421. origin_svr.listen_after_bind();
  3422. });
  3423. auto se = detail::scope_exit([&] {
  3424. origin_svr.stop();
  3425. origin_thread.join();
  3426. target_svr.stop();
  3427. target_thread.join();
  3428. });
  3429. target_svr.wait_until_ready();
  3430. origin_svr.wait_until_ready();
  3431. Client cli("localhost", origin_port);
  3432. cli.set_follow_location(true);
  3433. setup(cli);
  3434. return cli.Get("/redir", headers);
  3435. }
  3436. static void
  3437. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3438. std::string captured_authorization;
  3439. auto result = GetThroughRedirectToDifferentPort(
  3440. [&](const Request &req, Response &res) {
  3441. captured_authorization = req.get_header_value("Authorization");
  3442. res.set_content("OK", "text/plain");
  3443. },
  3444. set_auth);
  3445. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3446. EXPECT_EQ(StatusCode::OK_200, result->status);
  3447. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3448. EXPECT_TRUE(captured_authorization.empty());
  3449. }
  3450. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3451. TestDoNotForwardCredentialsOnRedirect(
  3452. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3453. }
  3454. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3455. TestDoNotForwardCredentialsOnRedirect(
  3456. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3457. }
  3458. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3459. std::string captured_cookie;
  3460. auto result = GetThroughRedirectToDifferentPort(
  3461. [&](const Request &req, Response &res) {
  3462. captured_cookie = req.get_header_value("Cookie");
  3463. res.set_content("OK", "text/plain");
  3464. },
  3465. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3466. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3467. EXPECT_EQ(StatusCode::OK_200, result->status);
  3468. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3469. EXPECT_TRUE(captured_cookie.empty());
  3470. }
  3471. TEST(RedirectToSamePort, ForwardCookie) {
  3472. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3473. // header so that ordinary session flows keep working.
  3474. Server svr;
  3475. std::string captured_cookie;
  3476. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3477. res.set_redirect("/target", 302);
  3478. });
  3479. svr.Get("/target", [&](const Request &req, Response &res) {
  3480. captured_cookie = req.get_header_value("Cookie");
  3481. res.set_content("OK", "text/plain");
  3482. });
  3483. auto port = svr.bind_to_any_port(HOST);
  3484. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3485. auto se = detail::scope_exit([&] {
  3486. svr.stop();
  3487. thread.join();
  3488. ASSERT_FALSE(svr.is_running());
  3489. });
  3490. svr.wait_until_ready();
  3491. Client cli(HOST, port);
  3492. cli.set_follow_location(true);
  3493. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3494. auto res = cli.Get("/redir", headers);
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::OK_200, res->status);
  3497. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3498. }
  3499. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3500. std::string authorization;
  3501. std::string trace_id;
  3502. auto result = GetThroughRedirectToDifferentPort(
  3503. [&](const Request &req, Response &res) {
  3504. authorization = req.get_header_value("Authorization");
  3505. trace_id = req.get_header_value("X-Trace-Id");
  3506. res.set_content("OK", "text/plain");
  3507. },
  3508. [](Client &cli) {
  3509. cli.set_default_headers(
  3510. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3511. });
  3512. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3513. EXPECT_EQ(StatusCode::OK_200, result->status);
  3514. // Like a header given with the request, a default one goes along unless it
  3515. // carries credentials (RFC 9110 15.4).
  3516. EXPECT_TRUE(authorization.empty());
  3517. EXPECT_EQ("42", trace_id);
  3518. }
  3519. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3520. auto result = GetThroughRedirectToDifferentPort(
  3521. [](const Request &, Response &res) {
  3522. res.set_content(std::string(2048, 'x'), "text/plain");
  3523. },
  3524. [](Client &cli) { cli.set_payload_max_length(1024); });
  3525. EXPECT_FALSE(result);
  3526. }
  3527. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3528. auto result = GetThroughRedirectToDifferentPort(
  3529. [](const Request &req, Response &res) {
  3530. // Answer after a second, or once the client gives up.
  3531. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3532. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3533. }
  3534. res.set_content("late", "text/plain");
  3535. },
  3536. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3537. ASSERT_FALSE(result);
  3538. EXPECT_EQ(Error::Read, result.error());
  3539. }
  3540. #ifdef CPPHTTPLIB_SSL_ENABLED
  3541. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3542. auto result = GetThroughRedirectToDifferentPort(
  3543. [](const Request &, Response &res) {
  3544. res.status = StatusCode::Unauthorized_401;
  3545. res.set_header("WWW-Authenticate",
  3546. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3547. },
  3548. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3549. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3550. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3551. }
  3552. #endif
  3553. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3554. Server svr;
  3555. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3556. // Port number that overflows int — should not crash
  3557. res.set_redirect("http://localhost:99999999999999999999/target");
  3558. });
  3559. auto port = svr.bind_to_any_port(HOST);
  3560. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3561. auto se = detail::scope_exit([&] {
  3562. svr.stop();
  3563. thread.join();
  3564. ASSERT_FALSE(svr.is_running());
  3565. });
  3566. svr.wait_until_ready();
  3567. Client cli(HOST, port);
  3568. cli.set_follow_location(true);
  3569. auto res = cli.Get("/redir");
  3570. // Should fail gracefully, not crash (no valid response due to bad port)
  3571. EXPECT_FALSE(res);
  3572. }
  3573. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3574. Server svr;
  3575. auto port = svr.bind_to_any_port(HOST);
  3576. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3577. // The server's own port followed by junk must not be followed
  3578. res.set_redirect("http://" + std::string(HOST) + ":" +
  3579. std::to_string(port) + "junk/target");
  3580. });
  3581. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3582. res.set_content("target", "text/plain");
  3583. });
  3584. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3585. auto se = detail::scope_exit([&] {
  3586. svr.stop();
  3587. thread.join();
  3588. ASSERT_FALSE(svr.is_running());
  3589. });
  3590. svr.wait_until_ready();
  3591. Client cli(HOST, port);
  3592. cli.set_follow_location(true);
  3593. auto res = cli.Get("/redir");
  3594. EXPECT_FALSE(res);
  3595. }
  3596. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  3597. Server svr;
  3598. std::atomic<bool> followed{false};
  3599. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  3600. res.status = StatusCode::NotModified_304;
  3601. res.set_header("Location", "/target");
  3602. });
  3603. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  3604. res.status = StatusCode::UseProxy_305;
  3605. res.set_header("Location", "/target");
  3606. });
  3607. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3608. followed = true;
  3609. res.set_content("target", "text/plain");
  3610. });
  3611. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3612. auto se = detail::scope_exit([&] {
  3613. svr.stop();
  3614. th.join();
  3615. ASSERT_FALSE(svr.is_running());
  3616. });
  3617. svr.wait_until_ready();
  3618. Client cli("localhost", PORT);
  3619. cli.set_follow_location(true);
  3620. auto res = cli.Get("/304");
  3621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3622. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  3623. res = cli.Get("/305");
  3624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3625. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  3626. EXPECT_FALSE(followed);
  3627. }
  3628. TEST(RedirectFromPageWithContent, Redirect) {
  3629. Server svr;
  3630. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3631. res.set_content("___", "text/plain");
  3632. res.set_redirect("/2");
  3633. });
  3634. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3635. res.set_content("Hello World!", "text/plain");
  3636. });
  3637. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3638. auto se = detail::scope_exit([&] {
  3639. svr.stop();
  3640. th.join();
  3641. ASSERT_FALSE(svr.is_running());
  3642. });
  3643. svr.wait_until_ready();
  3644. {
  3645. Client cli("localhost", PORT);
  3646. cli.set_follow_location(true);
  3647. std::string body;
  3648. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3649. body.append(data, data_length);
  3650. return true;
  3651. });
  3652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3653. EXPECT_EQ(StatusCode::OK_200, res->status);
  3654. EXPECT_EQ("Hello World!", body);
  3655. }
  3656. {
  3657. Client cli("localhost", PORT);
  3658. std::string body;
  3659. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3660. body.append(data, data_length);
  3661. return true;
  3662. });
  3663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3664. EXPECT_EQ(StatusCode::Found_302, res->status);
  3665. EXPECT_EQ("___", body);
  3666. }
  3667. }
  3668. // A server can close the connection after a request with "Connection: close"
  3669. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  3670. // redirected request must go out on a new connection.
  3671. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  3672. #ifndef _WIN32
  3673. signal(SIGPIPE, SIG_IGN);
  3674. #endif
  3675. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  3676. default_socket_options(srv);
  3677. sockaddr_in addr{};
  3678. addr.sin_family = AF_INET;
  3679. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  3680. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3681. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  3682. ASSERT_EQ(0, ::listen(srv, 2));
  3683. auto send_text = [](socket_t sock, const std::string &text) {
  3684. ::send(sock,
  3685. #ifdef _WIN32
  3686. static_cast<const char *>(text.c_str()),
  3687. static_cast<int>(text.size()),
  3688. #else
  3689. text.c_str(), text.size(),
  3690. #endif
  3691. 0);
  3692. };
  3693. auto reused = false;
  3694. auto server_thread = std::thread([&] {
  3695. char buf[4096];
  3696. auto first = ::accept(srv, nullptr, nullptr);
  3697. if (first == INVALID_SOCKET) { return; }
  3698. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3699. ::recv(first, buf, sizeof(buf), 0);
  3700. send_text(
  3701. first,
  3702. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  3703. auto next = first;
  3704. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  3705. reused = true;
  3706. } else {
  3707. detail::close_socket(first);
  3708. next = ::accept(srv, nullptr, nullptr);
  3709. if (next == INVALID_SOCKET) { return; }
  3710. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3711. ::recv(next, buf, sizeof(buf), 0);
  3712. }
  3713. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3714. "Connection: close\r\n\r\nok");
  3715. detail::close_socket(next);
  3716. });
  3717. Client cli("127.0.0.1", PORT + 2);
  3718. cli.set_follow_location(true);
  3719. cli.set_read_timeout(5, 0);
  3720. auto res = cli.Get("/1");
  3721. server_thread.join();
  3722. detail::close_socket(srv);
  3723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3724. EXPECT_EQ(StatusCode::OK_200, res->status);
  3725. EXPECT_EQ("ok", res->body);
  3726. EXPECT_FALSE(reused);
  3727. }
  3728. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3729. Server svr;
  3730. auto port_str = std::to_string(PORT);
  3731. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3732. auto expected_host = "[::1]:" + port_str;
  3733. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3734. res.set_content("___", "text/plain");
  3735. // res.set_redirect("/2");
  3736. res.set_redirect(redirect_url);
  3737. });
  3738. svr.Get("/2", [&](const Request &req, Response &res) {
  3739. auto host_header = req.headers.find("Host");
  3740. ASSERT_TRUE(host_header != req.headers.end());
  3741. EXPECT_EQ(expected_host, host_header->second);
  3742. res.set_content("Hello World!", "text/plain");
  3743. });
  3744. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3745. auto se = detail::scope_exit([&] {
  3746. svr.stop();
  3747. th.join();
  3748. ASSERT_FALSE(svr.is_running());
  3749. });
  3750. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3751. // actually starts anything, so the condition !svr.is_running() will
  3752. // always remain true, and the loop never stops.
  3753. // This basically counts how many milliseconds have passed since the
  3754. // call to svr.listen(), and if after 5 seconds nothing started yet
  3755. // aborts the test.
  3756. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3757. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3758. ASSERT_LT(milliseconds, 5000U);
  3759. }
  3760. {
  3761. Client cli("::1", PORT);
  3762. cli.set_follow_location(true);
  3763. std::string body;
  3764. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3765. body.append(data, data_length);
  3766. return true;
  3767. });
  3768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3769. EXPECT_EQ(StatusCode::OK_200, res->status);
  3770. EXPECT_EQ("Hello World!", body);
  3771. }
  3772. {
  3773. Client cli("::1", PORT);
  3774. std::string body;
  3775. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3776. body.append(data, data_length);
  3777. return true;
  3778. });
  3779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3780. EXPECT_EQ(StatusCode::Found_302, res->status);
  3781. EXPECT_EQ("___", body);
  3782. }
  3783. }
  3784. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3785. Server svr;
  3786. svr.Get("/foo", [](const Request &req, Response &res) {
  3787. auto a = req.params.find("a");
  3788. if (a != req.params.end()) {
  3789. res.set_content((*a).second, "text/plain");
  3790. res.status = StatusCode::OK_200;
  3791. } else {
  3792. res.status = StatusCode::BadRequest_400;
  3793. }
  3794. });
  3795. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3796. auto se = detail::scope_exit([&] {
  3797. svr.stop();
  3798. thread.join();
  3799. ASSERT_FALSE(svr.is_running());
  3800. });
  3801. svr.wait_until_ready();
  3802. {
  3803. Client cli(HOST, PORT);
  3804. cli.set_path_encode(false);
  3805. auto res = cli.Get("/foo?a=explicitly+encoded");
  3806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3807. EXPECT_EQ(StatusCode::OK_200, res->status);
  3808. // This expects it back with a space, as the `+` won't have been
  3809. // url-encoded, and server-side the params get decoded turning `+`
  3810. // into spaces.
  3811. EXPECT_EQ("explicitly encoded", res->body);
  3812. }
  3813. }
  3814. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3815. // When path encoding is disabled the client must transmit the supplied
  3816. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3817. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3818. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3819. // than a space (0x20). Assert on the raw wire target to catch this.
  3820. Server svr;
  3821. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3822. svr.Get("/foo", [&](const Request &req, Response &res) {
  3823. EXPECT_EQ(expected_target, req.target);
  3824. res.status = StatusCode::OK_200;
  3825. });
  3826. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3827. auto se = detail::scope_exit([&] {
  3828. svr.stop();
  3829. thread.join();
  3830. ASSERT_FALSE(svr.is_running());
  3831. });
  3832. svr.wait_until_ready();
  3833. {
  3834. Client cli(HOST, PORT);
  3835. cli.set_path_encode(false);
  3836. auto res = cli.Get(expected_target.c_str());
  3837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3838. EXPECT_EQ(StatusCode::OK_200, res->status);
  3839. }
  3840. }
  3841. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3842. // `open_stream()` used to skip the path encoding that the buffered send
  3843. // path applies, so the same `path` produced different bytes in the request
  3844. // line depending on which API was used. Assert the two agree.
  3845. Server svr;
  3846. std::string target;
  3847. svr.Get(".*", [&](const Request &req, Response &res) {
  3848. target = req.target;
  3849. res.status = StatusCode::OK_200;
  3850. });
  3851. auto port = svr.bind_to_any_port(HOST);
  3852. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3853. auto se = detail::scope_exit([&] {
  3854. svr.stop();
  3855. thread.join();
  3856. ASSERT_FALSE(svr.is_running());
  3857. });
  3858. svr.wait_until_ready();
  3859. struct {
  3860. const char *path;
  3861. const char *expected;
  3862. } cases[] = {
  3863. {"/a b?x=1", "/a%20b?x=1"},
  3864. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3865. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3866. };
  3867. for (const auto &c : cases) {
  3868. Client cli(HOST, port);
  3869. target.clear();
  3870. auto res = cli.Get(c.path);
  3871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3872. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3873. auto buffered_target = target;
  3874. target.clear();
  3875. auto handle = cli.open_stream("GET", c.path);
  3876. EXPECT_TRUE(handle.is_valid())
  3877. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3878. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3879. }
  3880. }
  3881. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3882. // The `set_path_encode(false)` contract — transmit the supplied target
  3883. // verbatim — must hold for the streaming API too.
  3884. Server svr;
  3885. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3886. std::string target;
  3887. svr.Get("/foo", [&](const Request &req, Response &res) {
  3888. target = req.target;
  3889. res.status = StatusCode::OK_200;
  3890. });
  3891. auto port = svr.bind_to_any_port(HOST);
  3892. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3893. auto se = detail::scope_exit([&] {
  3894. svr.stop();
  3895. thread.join();
  3896. ASSERT_FALSE(svr.is_running());
  3897. });
  3898. svr.wait_until_ready();
  3899. {
  3900. Client cli(HOST, port);
  3901. cli.set_path_encode(false);
  3902. auto handle = cli.open_stream("GET", expected_target);
  3903. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3904. EXPECT_EQ(expected_target, target);
  3905. }
  3906. }
  3907. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3908. // With path encoding enabled a CR/LF in the target is percent-encoded
  3909. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3910. // write_request_line still backstops `set_path_encode(false)`, which is
  3911. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3912. Server svr;
  3913. // Captured before routing: the decoded path contains a newline, which a
  3914. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3915. std::string target;
  3916. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3917. target = req.target;
  3918. res.status = StatusCode::OK_200;
  3919. return Server::HandlerResponse::Handled;
  3920. });
  3921. auto port = svr.bind_to_any_port(HOST);
  3922. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3923. auto se = detail::scope_exit([&] {
  3924. svr.stop();
  3925. thread.join();
  3926. ASSERT_FALSE(svr.is_running());
  3927. });
  3928. svr.wait_until_ready();
  3929. {
  3930. Client cli(HOST, port);
  3931. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3932. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3933. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3934. }
  3935. }
  3936. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3937. // Every control character is percent-encoded, not just CR/LF, so the target
  3938. // passes the request-target check in write_request_line.
  3939. Server svr;
  3940. std::string target;
  3941. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3942. target = req.target;
  3943. res.status = StatusCode::OK_200;
  3944. return Server::HandlerResponse::Handled;
  3945. });
  3946. auto port = svr.bind_to_any_port(HOST);
  3947. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3948. auto se = detail::scope_exit([&] {
  3949. svr.stop();
  3950. thread.join();
  3951. ASSERT_FALSE(svr.is_running());
  3952. });
  3953. svr.wait_until_ready();
  3954. {
  3955. Client cli(HOST, port);
  3956. auto res = cli.Get("/a\tb\x1b\x7f");
  3957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3958. EXPECT_EQ("/a%09b%1B%7F", target);
  3959. }
  3960. }
  3961. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3962. // Nothing may reach the wire: a raw CR/LF target would split the request
  3963. // line and inject headers.
  3964. Server svr;
  3965. // Pre-routing so that "not called" means nothing reached the server at all,
  3966. // rather than merely failing to match a handler pattern.
  3967. auto handler_called = false;
  3968. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3969. handler_called = true;
  3970. res.status = StatusCode::OK_200;
  3971. return Server::HandlerResponse::Handled;
  3972. });
  3973. auto port = svr.bind_to_any_port(HOST);
  3974. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3975. auto se = detail::scope_exit([&] {
  3976. svr.stop();
  3977. thread.join();
  3978. ASSERT_FALSE(svr.is_running());
  3979. });
  3980. svr.wait_until_ready();
  3981. {
  3982. Client cli(HOST, port);
  3983. cli.set_path_encode(false);
  3984. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3985. EXPECT_FALSE(handle.is_valid());
  3986. EXPECT_EQ(Error::Write, handle.error);
  3987. EXPECT_FALSE(handler_called);
  3988. }
  3989. }
  3990. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3991. // Which of the two branches runs is decided by whether the query component
  3992. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3993. // an empty query and must still fall back to building one from
  3994. // `req.params`, while a non-empty query must win over `req.params`.
  3995. Server svr;
  3996. std::string target;
  3997. svr.Get("/foo", [&](const Request &req, Response &res) {
  3998. target = req.target;
  3999. res.status = StatusCode::OK_200;
  4000. });
  4001. auto port = svr.bind_to_any_port(HOST);
  4002. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4003. auto se = detail::scope_exit([&] {
  4004. svr.stop();
  4005. thread.join();
  4006. ASSERT_FALSE(svr.is_running());
  4007. });
  4008. svr.wait_until_ready();
  4009. {
  4010. // Trailing `?` -> empty query component -> `req.params` is used.
  4011. Client cli(HOST, port);
  4012. Request req;
  4013. req.method = "GET";
  4014. req.path = "/foo?";
  4015. req.params.emplace("a", "1");
  4016. target.clear();
  4017. auto res = cli.send(req);
  4018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4019. EXPECT_EQ("/foo?a=1", target);
  4020. }
  4021. {
  4022. // Non-empty query in `req.path` -> `req.params` is not appended.
  4023. Client cli(HOST, port);
  4024. Request req;
  4025. req.method = "GET";
  4026. req.path = "/foo?b=2";
  4027. req.params.emplace("a", "1");
  4028. target.clear();
  4029. auto res = cli.send(req);
  4030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4031. EXPECT_EQ("/foo?b=2", target);
  4032. }
  4033. }
  4034. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4035. Server svr;
  4036. svr.Get("/", [](const Request &req, Response &) {
  4037. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4038. });
  4039. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4040. auto se = detail::scope_exit([&] {
  4041. svr.stop();
  4042. thread.join();
  4043. ASSERT_FALSE(svr.is_running());
  4044. });
  4045. svr.wait_until_ready();
  4046. {
  4047. Client cli(HOST, PORT);
  4048. cli.set_path_encode(false);
  4049. auto res = cli.Get("/?something=%0A");
  4050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4051. EXPECT_EQ(StatusCode::OK_200, res->status);
  4052. }
  4053. }
  4054. TEST(BindServerTest, BindDualStack) {
  4055. Server svr;
  4056. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4057. res.set_content("Hello World!", "text/plain");
  4058. });
  4059. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4060. auto se = detail::scope_exit([&] {
  4061. svr.stop();
  4062. thread.join();
  4063. ASSERT_FALSE(svr.is_running());
  4064. });
  4065. svr.wait_until_ready();
  4066. {
  4067. Client cli("127.0.0.1", PORT);
  4068. auto res = cli.Get("/1");
  4069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4070. EXPECT_EQ(StatusCode::OK_200, res->status);
  4071. EXPECT_EQ("Hello World!", res->body);
  4072. }
  4073. {
  4074. Client cli("::1", PORT);
  4075. auto res = cli.Get("/1");
  4076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4077. EXPECT_EQ(StatusCode::OK_200, res->status);
  4078. EXPECT_EQ("Hello World!", res->body);
  4079. }
  4080. }
  4081. TEST(BindServerTest, BindAndListenSeparately) {
  4082. Server svr;
  4083. int port = svr.bind_to_any_port("0.0.0.0");
  4084. ASSERT_TRUE(svr.is_valid());
  4085. ASSERT_TRUE(port > 0);
  4086. svr.stop();
  4087. }
  4088. // Reports whether anything is still listening on a loopback port. A plain
  4089. // connect() is used instead of a Client request because a socket left bound by
  4090. // mistake accepts the connection into its backlog and never answers, which
  4091. // would hang the test instead of failing it.
  4092. static bool is_loopback_port_accepting(int port) {
  4093. sockaddr_in addr{};
  4094. addr.sin_family = AF_INET;
  4095. addr.sin_port = htons(static_cast<uint16_t>(port));
  4096. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4097. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4098. EXPECT_NE(sock, INVALID_SOCKET);
  4099. if (sock == INVALID_SOCKET) { return false; }
  4100. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4101. static_cast<socklen_t>(sizeof(addr)));
  4102. detail::close_socket(sock);
  4103. return ret == 0;
  4104. }
  4105. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4106. Server svr;
  4107. auto port = svr.bind_to_any_port("127.0.0.1");
  4108. ASSERT_TRUE(port > 0);
  4109. svr.stop();
  4110. // bind_to_any_port() already called listen(2), so until stop() closed the
  4111. // descriptor the port kept accepting connections into the backlog. ASSERT
  4112. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4113. // below blocks forever in the accept loop.
  4114. ASSERT_FALSE(is_loopback_port_accepting(port));
  4115. // Nothing is left to accept on, so listen_after_bind() must report failure
  4116. // instead of returning success without ever serving.
  4117. EXPECT_FALSE(svr.listen_after_bind());
  4118. // The failed listen marks the server decommissioned, so a waiter returns
  4119. // instead of spinning forever.
  4120. svr.wait_until_ready();
  4121. }
  4122. #ifdef CPPHTTPLIB_SSL_ENABLED
  4123. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4124. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4125. CLIENT_CA_CERT_DIR);
  4126. int port = svr.bind_to_any_port("0.0.0.0");
  4127. ASSERT_TRUE(svr.is_valid());
  4128. ASSERT_TRUE(port > 0);
  4129. svr.stop();
  4130. }
  4131. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4132. // or a rejected CustomRoute() registration would not stop the server binding.
  4133. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4134. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4135. CLIENT_CA_CERT_DIR);
  4136. ASSERT_TRUE(svr.is_valid());
  4137. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4138. EXPECT_FALSE(svr.is_valid());
  4139. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4140. }
  4141. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4142. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4143. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4144. int port = svr.bind_to_any_port("0.0.0.0");
  4145. ASSERT_TRUE(svr.is_valid());
  4146. ASSERT_TRUE(port > 0);
  4147. svr.stop();
  4148. }
  4149. TEST(BindServerTest, UpdateCertsPem) {
  4150. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4151. int port = svr.bind_to_any_port("0.0.0.0");
  4152. ASSERT_TRUE(svr.is_valid());
  4153. ASSERT_TRUE(port > 0);
  4154. // Read PEM files
  4155. std::string cert_pem, key_pem, ca_pem;
  4156. read_file(SERVER_CERT_FILE, cert_pem);
  4157. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4158. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4159. // Update server certificates using PEM API
  4160. ASSERT_TRUE(
  4161. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4162. ASSERT_TRUE(svr.is_valid());
  4163. svr.stop();
  4164. }
  4165. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4166. // Start server with client CA (enables client auth)
  4167. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4168. ASSERT_TRUE(svr.is_valid());
  4169. bool handler_called = false;
  4170. svr.Get("/test", [&](const Request &req, Response &res) {
  4171. handler_called = true;
  4172. // Verify client certificate is present
  4173. auto cert = req.peer_cert();
  4174. EXPECT_TRUE(static_cast<bool>(cert));
  4175. res.set_content("ok", "text/plain");
  4176. });
  4177. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4178. auto se = detail::scope_exit([&] {
  4179. svr.stop();
  4180. t.join();
  4181. ASSERT_FALSE(svr.is_running());
  4182. });
  4183. svr.wait_until_ready();
  4184. // Read PEM files
  4185. std::string cert_pem, key_pem, ca_pem;
  4186. read_file(SERVER_CERT_FILE, cert_pem);
  4187. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4188. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4189. // Update server certificates and client CA using PEM API while server running
  4190. ASSERT_TRUE(
  4191. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4192. // Connect with client certificate
  4193. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4194. cli.enable_server_certificate_verification(false);
  4195. cli.set_connection_timeout(30);
  4196. auto res = cli.Get("/test");
  4197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4198. ASSERT_EQ(StatusCode::OK_200, res->status);
  4199. ASSERT_TRUE(handler_called);
  4200. EXPECT_EQ("ok", res->body);
  4201. }
  4202. // Puts a CA that did not sign the client's certificate in the old one's place.
  4203. static bool replace_client_ca(SSLServer &svr) {
  4204. std::string cert_pem, key_pem, ca_pem;
  4205. read_file(SERVER_CERT_FILE, cert_pem);
  4206. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4207. read_file(SERVER_CERT2_FILE, ca_pem);
  4208. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4209. ca_pem.c_str());
  4210. }
  4211. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4212. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4213. ASSERT_TRUE(svr.is_valid());
  4214. svr.Get("/test", [](const Request &, Response &res) {
  4215. res.set_content("ok", "text/plain");
  4216. });
  4217. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4218. auto se = detail::scope_exit([&] {
  4219. svr.stop();
  4220. t.join();
  4221. ASSERT_FALSE(svr.is_running());
  4222. });
  4223. svr.wait_until_ready();
  4224. auto get = [] {
  4225. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4226. cli.enable_server_certificate_verification(false);
  4227. return cli.Get("/test");
  4228. };
  4229. ASSERT_TRUE(get());
  4230. ASSERT_TRUE(replace_client_ca(svr));
  4231. EXPECT_FALSE(get());
  4232. }
  4233. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4234. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4235. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4236. ASSERT_TRUE(svr.is_valid());
  4237. tls::set_verify_callback(svr.tls_context(),
  4238. [](const tls::VerifyContext &) -> bool {
  4239. throw std::runtime_error("verify");
  4240. });
  4241. svr.Get("/test", [](const Request &, Response &res) {
  4242. res.set_content("ok", "text/plain");
  4243. });
  4244. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4245. auto se = detail::scope_exit([&] {
  4246. svr.stop();
  4247. t.join();
  4248. ASSERT_FALSE(svr.is_running());
  4249. });
  4250. svr.wait_until_ready();
  4251. auto get = [] {
  4252. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4253. cli.enable_server_certificate_verification(false);
  4254. return cli.Get("/test");
  4255. };
  4256. EXPECT_FALSE(get());
  4257. // The handshake is over, so an update does not wait for it.
  4258. std::string cert_pem, key_pem;
  4259. read_file(SERVER_CERT_FILE, cert_pem);
  4260. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4261. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4262. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4263. return v.preverify_ok;
  4264. });
  4265. auto res = get();
  4266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4267. EXPECT_EQ("ok", res->body);
  4268. }
  4269. #endif
  4270. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4271. // Sends each request over a new connection with a client certificate,
  4272. // resuming the session of the one before when there is one.
  4273. class ResumingClient {
  4274. public:
  4275. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4276. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4277. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4278. SSL_FILETYPE_PEM);
  4279. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4280. // callback, not through SSL_get1_session().
  4281. SSL_CTX_set_app_data(ctx_, this);
  4282. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4283. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4284. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4285. auto self = static_cast<ResumingClient *>(
  4286. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4287. SSL_SESSION_free(self->session_);
  4288. self->session_ = session;
  4289. return 1; // Keeps the reference
  4290. });
  4291. }
  4292. ~ResumingClient() {
  4293. SSL_SESSION_free(session_);
  4294. SSL_CTX_free(ctx_);
  4295. }
  4296. // Tells whether the request was answered.
  4297. bool get() {
  4298. auto error = Error::Success;
  4299. auto sock = detail::create_client_socket(
  4300. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4301. /*connection_timeout_sec=*/5, 0,
  4302. /*read_timeout_sec=*/5, 0,
  4303. /*write_timeout_sec=*/5, 0, std::string(), error);
  4304. if (sock == INVALID_SOCKET) { return false; }
  4305. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4306. auto ssl = SSL_new(ctx_);
  4307. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4308. SSL_set_fd(ssl, static_cast<int>(sock));
  4309. if (session_) { SSL_set_session(ssl, session_); }
  4310. if (SSL_connect(ssl) != 1) { return false; }
  4311. reused_ = SSL_session_reused(ssl) == 1;
  4312. // Reading the response also takes in a TLS 1.3 session ticket.
  4313. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4314. "Connection: close\r\n\r\n";
  4315. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4316. std::string res;
  4317. char buf[256];
  4318. int n;
  4319. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4320. res.append(buf, static_cast<size_t>(n));
  4321. }
  4322. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4323. SSL_shutdown(ssl);
  4324. return res.find("200 OK") != std::string::npos;
  4325. }
  4326. // Whether the last connection resumed a session
  4327. bool reused() const { return reused_; }
  4328. private:
  4329. SSL_CTX *ctx_;
  4330. SSL_SESSION *session_ = nullptr;
  4331. bool reused_ = false;
  4332. };
  4333. // A client that resumes its session gets through, but not once the client CA
  4334. // has changed, as a resumed session does not show the certificate again.
  4335. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4336. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4337. ASSERT_TRUE(svr.is_valid());
  4338. svr.Get("/test", [](const Request &, Response &res) {
  4339. res.set_content("ok", "text/plain");
  4340. });
  4341. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4342. auto se = detail::scope_exit([&] {
  4343. svr.stop();
  4344. t.join();
  4345. ASSERT_FALSE(svr.is_running());
  4346. });
  4347. svr.wait_until_ready();
  4348. ResumingClient cli;
  4349. ASSERT_TRUE(cli.get());
  4350. ASSERT_TRUE(cli.get());
  4351. EXPECT_TRUE(cli.reused());
  4352. ASSERT_TRUE(replace_client_ca(svr));
  4353. EXPECT_FALSE(cli.get());
  4354. }
  4355. // A resumed session does not show the certificate again, so the server does
  4356. // not resume one with a verify callback to run on it.
  4357. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4358. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4359. ASSERT_TRUE(svr.is_valid());
  4360. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4361. return v.preverify_ok;
  4362. });
  4363. svr.Get("/test", [](const Request &, Response &res) {
  4364. res.set_content("ok", "text/plain");
  4365. });
  4366. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4367. auto se = detail::scope_exit([&] {
  4368. svr.stop();
  4369. t.join();
  4370. ASSERT_FALSE(svr.is_running());
  4371. });
  4372. svr.wait_until_ready();
  4373. ResumingClient cli;
  4374. ASSERT_TRUE(cli.get());
  4375. ASSERT_TRUE(cli.get());
  4376. EXPECT_FALSE(cli.reused());
  4377. }
  4378. #endif
  4379. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4380. // wolfSSL shares its session cache between contexts, so a resumed session
  4381. // could carry a client certificate checked against another server's CA, or
  4382. // against a client CA since replaced.
  4383. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4384. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4385. ASSERT_TRUE(svr.is_valid());
  4386. // Trusts a CA that did not sign the client's certificate.
  4387. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4388. ASSERT_TRUE(other.is_valid());
  4389. for (auto s : {&svr, &other}) {
  4390. s->Get("/test", [](const Request &, Response &res) {
  4391. res.set_content("ok", "text/plain");
  4392. });
  4393. }
  4394. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4395. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4396. auto se = detail::scope_exit([&] {
  4397. other.stop();
  4398. svr.stop();
  4399. t2.join();
  4400. t.join();
  4401. });
  4402. svr.wait_until_ready();
  4403. other.wait_until_ready();
  4404. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4405. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4406. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4407. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4408. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4409. ASSERT_EQ(WOLFSSL_SUCCESS,
  4410. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4411. WOLFSSL_FILETYPE_PEM));
  4412. WOLFSSL_SESSION *session = nullptr;
  4413. auto session_se = detail::scope_exit([&] {
  4414. if (session) { wolfSSL_SESSION_free(session); }
  4415. });
  4416. // A request over a new connection, resuming `session` when there is one and
  4417. // keeping the connection's own in its place. Tells whether it was answered.
  4418. auto get = [&](int port) {
  4419. auto error = Error::Success;
  4420. auto sock = detail::create_client_socket(
  4421. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4422. /*connection_timeout_sec=*/5, 0,
  4423. /*read_timeout_sec=*/5, 0,
  4424. /*write_timeout_sec=*/5, 0, std::string(), error);
  4425. if (sock == INVALID_SOCKET) { return false; }
  4426. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4427. auto ssl = wolfSSL_new(ctx);
  4428. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4429. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4430. if (session) { wolfSSL_set_session(ssl, session); }
  4431. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4432. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4433. "Connection: close\r\n\r\n";
  4434. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4435. std::string res;
  4436. char buf[256];
  4437. int n;
  4438. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4439. res.append(buf, static_cast<size_t>(n));
  4440. }
  4441. wolfSSL_shutdown(ssl);
  4442. if (session) { wolfSSL_SESSION_free(session); }
  4443. session = wolfSSL_get1_session(ssl);
  4444. return res.find("200 OK") != std::string::npos;
  4445. };
  4446. ASSERT_TRUE(get(PORT));
  4447. EXPECT_FALSE(get(PORT + 1));
  4448. ASSERT_TRUE(get(PORT));
  4449. ASSERT_TRUE(replace_client_ca(svr));
  4450. EXPECT_FALSE(get(PORT));
  4451. }
  4452. #endif
  4453. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4454. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4455. ASSERT_TRUE(svr.is_valid());
  4456. svr.Get("/test", [](const Request &, Response &res) {
  4457. res.set_content("ok", "text/plain");
  4458. });
  4459. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4460. auto se = detail::scope_exit([&] {
  4461. svr.stop();
  4462. t.join();
  4463. ASSERT_FALSE(svr.is_running());
  4464. });
  4465. svr.wait_until_ready();
  4466. // A connection that sends no ClientHello keeps its handshake in progress,
  4467. // once the server has had a moment to start it.
  4468. auto error = Error::Success;
  4469. auto sock = detail::create_client_socket(
  4470. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4471. /*connection_timeout_sec=*/5, 0,
  4472. /*read_timeout_sec=*/5, 0,
  4473. /*write_timeout_sec=*/5, 0, std::string(), error);
  4474. ASSERT_NE(INVALID_SOCKET, sock);
  4475. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4476. std::string cert_pem, key_pem;
  4477. read_file(SERVER_CERT_FILE, cert_pem);
  4478. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4479. auto update = std::async(std::launch::async, [&]() {
  4480. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4481. });
  4482. EXPECT_EQ(std::future_status::timeout,
  4483. update.wait_for(std::chrono::milliseconds(200)));
  4484. detail::close_socket(sock);
  4485. EXPECT_TRUE(update.get());
  4486. SSLClient cli(HOST, PORT);
  4487. cli.enable_server_certificate_verification(false);
  4488. auto res = cli.Get("/test");
  4489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4490. EXPECT_EQ(StatusCode::OK_200, res->status);
  4491. }
  4492. #endif
  4493. TEST(ErrorHandlerTest, ContentLength) {
  4494. Server svr;
  4495. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4496. res.status = StatusCode::OK_200;
  4497. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4498. "text/html"); // <= Content-Length still 13
  4499. });
  4500. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4501. res.set_content("Hello World!\n", "text/plain");
  4502. res.status = 524;
  4503. });
  4504. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4505. auto se = detail::scope_exit([&] {
  4506. svr.stop();
  4507. thread.join();
  4508. ASSERT_FALSE(svr.is_running());
  4509. });
  4510. svr.wait_until_ready();
  4511. {
  4512. Client cli(HOST, PORT);
  4513. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4514. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4515. EXPECT_EQ(StatusCode::OK_200, res->status);
  4516. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4517. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4518. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4519. }
  4520. }
  4521. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4522. TEST(ExceptionTest, WithoutExceptionHandler) {
  4523. Server svr;
  4524. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4525. throw std::runtime_error("exception...");
  4526. });
  4527. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4528. throw std::runtime_error("exception\r\n...");
  4529. });
  4530. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4531. auto se = detail::scope_exit([&] {
  4532. svr.stop();
  4533. listen_thread.join();
  4534. ASSERT_FALSE(svr.is_running());
  4535. });
  4536. svr.wait_until_ready();
  4537. Client cli("localhost", PORT);
  4538. {
  4539. auto res = cli.Get("/exception");
  4540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4541. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4542. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4543. }
  4544. {
  4545. auto res = cli.Get("/unknown");
  4546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4547. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4548. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4549. }
  4550. }
  4551. TEST(ExceptionTest, WithExceptionHandler) {
  4552. Server svr;
  4553. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4554. std::exception_ptr ep) {
  4555. EXPECT_FALSE(ep == nullptr);
  4556. try {
  4557. std::rethrow_exception(ep);
  4558. } catch (std::exception &e) {
  4559. EXPECT_EQ("abc", std::string(e.what()));
  4560. } catch (...) {}
  4561. res.status = StatusCode::InternalServerError_500;
  4562. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4563. "text/html"); // <= Content-Length still 13 at this point
  4564. });
  4565. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4566. res.set_content("Hello World!\n", "text/plain");
  4567. throw std::runtime_error("abc");
  4568. });
  4569. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4570. auto se = detail::scope_exit([&] {
  4571. svr.stop();
  4572. thread.join();
  4573. ASSERT_FALSE(svr.is_running());
  4574. });
  4575. svr.wait_until_ready();
  4576. for (size_t i = 0; i < 10; i++) {
  4577. Client cli(HOST, PORT);
  4578. for (size_t j = 0; j < 100; j++) {
  4579. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4581. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4582. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4583. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4584. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4585. }
  4586. cli.set_keep_alive(true);
  4587. for (size_t j = 0; j < 100; j++) {
  4588. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4590. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4591. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4592. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4593. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4594. }
  4595. }
  4596. }
  4597. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4598. Server svr;
  4599. svr.set_exception_handler(
  4600. [](const Request &, Response &res, std::exception_ptr) {
  4601. res.set_content("oops", "text/plain");
  4602. });
  4603. svr.Get("/throw", [](const Request &, Response &) {
  4604. throw std::runtime_error("throw");
  4605. });
  4606. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4607. res.status = StatusCode::Created_201;
  4608. throw std::runtime_error("created-then-throw");
  4609. });
  4610. auto port = svr.bind_to_any_port(HOST);
  4611. ASSERT_GT(port, 0);
  4612. thread t = thread([&] { svr.listen_after_bind(); });
  4613. auto se = detail::scope_exit([&] {
  4614. svr.stop();
  4615. t.join();
  4616. ASSERT_FALSE(svr.is_running());
  4617. });
  4618. svr.wait_until_ready();
  4619. Client cli(HOST, port);
  4620. for (auto path : {"/throw", "/created-then-throw"}) {
  4621. auto res = cli.Get(path);
  4622. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4623. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4624. }
  4625. }
  4626. TEST(ExceptionTest, AndErrorHandler) {
  4627. Server svr;
  4628. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4629. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4630. });
  4631. svr.set_exception_handler(
  4632. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4633. EXPECT_FALSE(ep == nullptr);
  4634. try {
  4635. std::rethrow_exception(ep);
  4636. } catch (std::exception &e) {
  4637. res.set_content(e.what(), "text/html");
  4638. } catch (...) {}
  4639. res.status = StatusCode::InternalServerError_500;
  4640. });
  4641. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4642. throw std::runtime_error("EXCEPTION");
  4643. });
  4644. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4645. res.set_content("ERROR", "text/html");
  4646. res.status = StatusCode::InternalServerError_500;
  4647. });
  4648. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4649. auto se = detail::scope_exit([&] {
  4650. svr.stop();
  4651. thread.join();
  4652. ASSERT_FALSE(svr.is_running());
  4653. });
  4654. svr.wait_until_ready();
  4655. Client cli(HOST, PORT);
  4656. {
  4657. auto res = cli.Get("/exception");
  4658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4659. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4660. EXPECT_EQ("EXCEPTION", res->body);
  4661. }
  4662. {
  4663. auto res = cli.Get("/error");
  4664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4665. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4666. EXPECT_EQ("ERROR", res->body);
  4667. }
  4668. {
  4669. auto res = cli.Get("/invalid");
  4670. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4671. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4672. EXPECT_EQ("NOT_FOUND", res->body);
  4673. }
  4674. }
  4675. #endif
  4676. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4677. // An exception from a user callback outside process_request()'s try/catch
  4678. // used to unwind into the task queue - which does not catch - and terminate
  4679. // the process. Each test below runs the server on a single worker thread: a
  4680. // guard that catches the exception but still loses the thread would otherwise
  4681. // be hidden by a spare worker serving the follow-up request. Note that a
  4682. // regression here aborts the whole test binary rather than failing one test.
  4683. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4684. Server svr;
  4685. svr.new_task_queue = [] { return new ThreadPool(1); };
  4686. std::atomic<int> reported{0};
  4687. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4688. if (err == Error::UserCallbackException) { reported++; }
  4689. });
  4690. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4691. res.set_content_provider(
  4692. 1024, "text/plain",
  4693. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4694. sink.write("hello", 5);
  4695. throw std::runtime_error("from the content provider");
  4696. });
  4697. });
  4698. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4699. res.set_content("ok", "text/plain");
  4700. });
  4701. auto port = svr.bind_to_any_port(HOST);
  4702. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4703. auto se = detail::scope_exit([&] {
  4704. svr.stop();
  4705. listen_thread.join();
  4706. ASSERT_FALSE(svr.is_running());
  4707. });
  4708. svr.wait_until_ready();
  4709. {
  4710. Client cli(HOST, port);
  4711. cli.set_read_timeout(5, 0);
  4712. EXPECT_FALSE(cli.Get("/throw"));
  4713. }
  4714. EXPECT_TRUE(svr.is_running());
  4715. EXPECT_EQ(1, reported.load());
  4716. // A request on a fresh connection is still served.
  4717. {
  4718. Client cli(HOST, port);
  4719. auto res = cli.Get("/ok");
  4720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4721. EXPECT_EQ(StatusCode::OK_200, res->status);
  4722. EXPECT_EQ("ok", res->body);
  4723. }
  4724. }
  4725. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4726. Server svr;
  4727. svr.new_task_queue = [] { return new ThreadPool(1); };
  4728. std::atomic<bool> should_throw{true};
  4729. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4730. res.set_content("hi", "text/plain");
  4731. });
  4732. svr.set_post_routing_handler(
  4733. [&](const Request & /*req*/, Response & /*res*/) {
  4734. if (should_throw) {
  4735. throw std::runtime_error("from the post-routing handler");
  4736. }
  4737. });
  4738. auto port = svr.bind_to_any_port(HOST);
  4739. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4740. auto se = detail::scope_exit([&] {
  4741. svr.stop();
  4742. listen_thread.join();
  4743. ASSERT_FALSE(svr.is_running());
  4744. });
  4745. svr.wait_until_ready();
  4746. {
  4747. Client cli(HOST, port);
  4748. cli.set_read_timeout(5, 0);
  4749. EXPECT_FALSE(cli.Get("/hi"));
  4750. }
  4751. EXPECT_TRUE(svr.is_running());
  4752. should_throw = false;
  4753. {
  4754. Client cli(HOST, port);
  4755. auto res = cli.Get("/hi");
  4756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4757. EXPECT_EQ(StatusCode::OK_200, res->status);
  4758. EXPECT_EQ("hi", res->body);
  4759. }
  4760. }
  4761. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4762. // The guard reports the caught exception through the error logger, which is
  4763. // a user callback too. A logger that throws has to be contained as well, or
  4764. // the process would terminate from inside the catch.
  4765. Server svr;
  4766. svr.new_task_queue = [] { return new ThreadPool(1); };
  4767. std::atomic<int> reported{0};
  4768. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4769. if (err == Error::UserCallbackException) {
  4770. reported++;
  4771. throw std::runtime_error("from the error logger");
  4772. }
  4773. });
  4774. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4775. res.set_content_provider(
  4776. 1024, "text/plain",
  4777. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4778. sink.write("hello", 5);
  4779. throw std::runtime_error("from the content provider");
  4780. });
  4781. });
  4782. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4783. res.set_content("ok", "text/plain");
  4784. });
  4785. auto port = svr.bind_to_any_port(HOST);
  4786. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4787. auto se = detail::scope_exit([&] {
  4788. svr.stop();
  4789. listen_thread.join();
  4790. ASSERT_FALSE(svr.is_running());
  4791. });
  4792. svr.wait_until_ready();
  4793. {
  4794. Client cli(HOST, port);
  4795. cli.set_read_timeout(5, 0);
  4796. EXPECT_FALSE(cli.Get("/throw"));
  4797. }
  4798. EXPECT_TRUE(svr.is_running());
  4799. EXPECT_EQ(1, reported.load());
  4800. {
  4801. Client cli(HOST, port);
  4802. auto res = cli.Get("/ok");
  4803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4804. EXPECT_EQ(StatusCode::OK_200, res->status);
  4805. EXPECT_EQ("ok", res->body);
  4806. }
  4807. }
  4808. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4809. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4810. // so the exception unwinds through the ws::WebSocket object on its way to
  4811. // the guard. None of the HTTP cases above cross that.
  4812. Server svr;
  4813. svr.new_task_queue = [] { return new ThreadPool(1); };
  4814. std::atomic<int> reported{0};
  4815. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4816. if (err == Error::UserCallbackException) { reported++; }
  4817. });
  4818. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4819. throw std::runtime_error("from the WebSocket handler");
  4820. });
  4821. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4822. res.set_content("ok", "text/plain");
  4823. });
  4824. auto port = svr.bind_to_any_port(HOST);
  4825. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4826. auto se = detail::scope_exit([&] {
  4827. svr.stop();
  4828. listen_thread.join();
  4829. ASSERT_FALSE(svr.is_running());
  4830. });
  4831. svr.wait_until_ready();
  4832. {
  4833. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4834. "/ws");
  4835. auto res = client.connect();
  4836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4837. // The server dropped the connection instead of dying.
  4838. std::string msg;
  4839. EXPECT_FALSE(client.read(msg));
  4840. client.close();
  4841. }
  4842. EXPECT_TRUE(svr.is_running());
  4843. EXPECT_EQ(1, reported.load());
  4844. {
  4845. Client cli(HOST, port);
  4846. auto res = cli.Get("/ok");
  4847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4848. EXPECT_EQ(StatusCode::OK_200, res->status);
  4849. EXPECT_EQ("ok", res->body);
  4850. }
  4851. }
  4852. #ifdef CPPHTTPLIB_SSL_ENABLED
  4853. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4854. // SSLServer::process_and_close_socket() is a separate overload with its own
  4855. // guard, so it is exercised on its own.
  4856. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4857. ASSERT_TRUE(svr.is_valid());
  4858. svr.new_task_queue = [] { return new ThreadPool(1); };
  4859. std::atomic<int> reported{0};
  4860. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4861. if (err == Error::UserCallbackException) { reported++; }
  4862. });
  4863. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4864. res.set_content_provider(
  4865. 1024, "text/plain",
  4866. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4867. sink.write("hello", 5);
  4868. throw std::runtime_error("from the content provider");
  4869. });
  4870. });
  4871. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4872. res.set_content("ok", "text/plain");
  4873. });
  4874. auto port = svr.bind_to_any_port(HOST);
  4875. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4876. auto se = detail::scope_exit([&] {
  4877. svr.stop();
  4878. listen_thread.join();
  4879. ASSERT_FALSE(svr.is_running());
  4880. });
  4881. svr.wait_until_ready();
  4882. {
  4883. SSLClient cli(HOST, port);
  4884. cli.enable_server_certificate_verification(false);
  4885. cli.set_read_timeout(5, 0);
  4886. EXPECT_FALSE(cli.Get("/throw"));
  4887. }
  4888. EXPECT_TRUE(svr.is_running());
  4889. EXPECT_EQ(1, reported.load());
  4890. {
  4891. SSLClient cli(HOST, port);
  4892. cli.enable_server_certificate_verification(false);
  4893. auto res = cli.Get("/ok");
  4894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4895. EXPECT_EQ(StatusCode::OK_200, res->status);
  4896. EXPECT_EQ("ok", res->body);
  4897. }
  4898. }
  4899. #endif
  4900. #endif
  4901. TEST(NoContentTest, ContentLength) {
  4902. Server svr;
  4903. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4904. res.status = StatusCode::NoContent_204;
  4905. });
  4906. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4907. auto se = detail::scope_exit([&] {
  4908. svr.stop();
  4909. thread.join();
  4910. ASSERT_FALSE(svr.is_running());
  4911. });
  4912. svr.wait_until_ready();
  4913. {
  4914. Client cli(HOST, PORT);
  4915. auto res = cli.Get("/hi");
  4916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4917. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4918. // RFC 9110 8.6: none in a 204 response
  4919. EXPECT_FALSE(res->has_header("Content-Length"));
  4920. }
  4921. }
  4922. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4923. Server svr;
  4924. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4925. res.set_header("Content-Length", "5");
  4926. res.set_content("hello world", "text/plain");
  4927. });
  4928. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4929. // A body that reads as the last chunk, were it taken as chunked
  4930. res.set_header("Transfer-Encoding", "chunked");
  4931. res.set_content("0\r\n\r\n", "text/plain");
  4932. });
  4933. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4934. res.set_header("Content-Length", "2");
  4935. res.set_content_provider(5, "text/plain",
  4936. [](size_t offset, size_t length, DataSink &sink) {
  4937. sink.write(&"hello"[offset], length);
  4938. return true;
  4939. });
  4940. });
  4941. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4942. res.set_header("Content-Length", "1234");
  4943. });
  4944. thread t = thread([&] { svr.listen(HOST, PORT); });
  4945. auto se = detail::scope_exit([&] {
  4946. svr.stop();
  4947. t.join();
  4948. ASSERT_FALSE(svr.is_running());
  4949. });
  4950. svr.wait_until_ready();
  4951. Client cli(HOST, PORT);
  4952. cli.set_read_timeout(1, 0);
  4953. auto expect_body = [&](const Result &res, const std::string &body) {
  4954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4955. EXPECT_EQ(body, res->body);
  4956. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4957. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4958. };
  4959. Headers identity{{"Accept-Encoding", ""}};
  4960. expect_body(cli.Get("/body", identity), "hello world");
  4961. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4962. expect_body(cli.Get("/body",
  4963. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4964. "he");
  4965. expect_body(cli.Get("/provider", identity), "hello");
  4966. expect_body(cli.Get("/empty", identity), "");
  4967. // A HEAD response may give the length of the body a GET would get.
  4968. auto res = cli.Head("/empty");
  4969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4970. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4971. }
  4972. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4973. Server svr;
  4974. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4975. res.set_content("short", "text/plain");
  4976. });
  4977. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4978. res.body += " with a footer";
  4979. res.set_header("Transfer-Encoding", "chunked");
  4980. });
  4981. thread t = thread([&] { svr.listen(HOST, PORT); });
  4982. auto se = detail::scope_exit([&] {
  4983. svr.stop();
  4984. t.join();
  4985. ASSERT_FALSE(svr.is_running());
  4986. });
  4987. svr.wait_until_ready();
  4988. Client cli(HOST, PORT);
  4989. cli.set_read_timeout(1, 0);
  4990. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4992. EXPECT_EQ("short with a footer", res->body);
  4993. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4994. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4995. }
  4996. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4997. Server svr;
  4998. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4999. res.set_header("Content-Length", "3");
  5000. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5001. sink.write("abc", 3);
  5002. sink.done();
  5003. return true;
  5004. });
  5005. });
  5006. thread t = thread([&] { svr.listen(HOST, PORT); });
  5007. auto se = detail::scope_exit([&] {
  5008. svr.stop();
  5009. t.join();
  5010. ASSERT_FALSE(svr.is_running());
  5011. });
  5012. svr.wait_until_ready();
  5013. Client cli(HOST, PORT);
  5014. cli.set_keep_alive(true);
  5015. auto res = cli.Get("/");
  5016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5017. EXPECT_EQ("abc", res->body);
  5018. EXPECT_FALSE(res->has_header("Content-Length"));
  5019. EXPECT_EQ("close", res->get_header_value("Connection"));
  5020. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5021. // No body to delimit
  5022. auto head = cli.Head("/");
  5023. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5024. EXPECT_FALSE(head->has_header("Connection"));
  5025. }
  5026. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5027. #ifdef CPPHTTPLIB_SSL_ENABLED
  5028. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5029. ASSERT_TRUE(svr.is_valid());
  5030. #else
  5031. Server svr;
  5032. #endif
  5033. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5034. if (req.path == "/routing_handler") {
  5035. res.set_header("PRE_ROUTING", "on");
  5036. res.set_content("Routing Handler", "text/plain");
  5037. return httplib::Server::HandlerResponse::Handled;
  5038. }
  5039. return httplib::Server::HandlerResponse::Unhandled;
  5040. });
  5041. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5042. res.set_content("Error", "text/html");
  5043. });
  5044. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5045. if (req.path == "/routing_handler") {
  5046. res.set_header("POST_ROUTING", "on");
  5047. }
  5048. });
  5049. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5050. res.set_content("Hello World!\n", "text/plain");
  5051. });
  5052. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5053. auto se = detail::scope_exit([&] {
  5054. svr.stop();
  5055. thread.join();
  5056. ASSERT_FALSE(svr.is_running());
  5057. });
  5058. svr.wait_until_ready();
  5059. {
  5060. #ifdef CPPHTTPLIB_SSL_ENABLED
  5061. SSLClient cli(HOST, PORT);
  5062. cli.enable_server_certificate_verification(false);
  5063. #else
  5064. Client cli(HOST, PORT);
  5065. #endif
  5066. auto res = cli.Get("/routing_handler");
  5067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5068. EXPECT_EQ(StatusCode::OK_200, res->status);
  5069. EXPECT_EQ("Routing Handler", res->body);
  5070. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5071. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5072. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5073. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5074. }
  5075. {
  5076. #ifdef CPPHTTPLIB_SSL_ENABLED
  5077. SSLClient cli(HOST, PORT);
  5078. cli.enable_server_certificate_verification(false);
  5079. #else
  5080. Client cli(HOST, PORT);
  5081. #endif
  5082. auto res = cli.Get("/hi");
  5083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5084. EXPECT_EQ(StatusCode::OK_200, res->status);
  5085. EXPECT_EQ("Hello World!\n", res->body);
  5086. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5087. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5088. }
  5089. {
  5090. #ifdef CPPHTTPLIB_SSL_ENABLED
  5091. SSLClient cli(HOST, PORT);
  5092. cli.enable_server_certificate_verification(false);
  5093. #else
  5094. Client cli(HOST, PORT);
  5095. #endif
  5096. auto res = cli.Get("/aaa");
  5097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5098. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5099. EXPECT_EQ("Error", res->body);
  5100. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5101. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5102. }
  5103. }
  5104. TEST(RequestHandlerTest, PreRequestHandler) {
  5105. auto route_path = "/user/:user";
  5106. Server svr;
  5107. svr.Get("/hi", [](const Request &, Response &res) {
  5108. res.set_content("hi", "text/plain");
  5109. });
  5110. svr.Get(route_path, [](const Request &req, Response &res) {
  5111. res.set_content(req.path_params.at("user"), "text/plain");
  5112. });
  5113. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5114. if (req.matched_route == route_path) {
  5115. auto user = req.path_params.at("user");
  5116. if (user != "john") {
  5117. res.status = StatusCode::Forbidden_403;
  5118. res.set_content("error", "text/html");
  5119. return Server::HandlerResponse::Handled;
  5120. }
  5121. }
  5122. return Server::HandlerResponse::Unhandled;
  5123. });
  5124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5125. auto se = detail::scope_exit([&] {
  5126. svr.stop();
  5127. thread.join();
  5128. ASSERT_FALSE(svr.is_running());
  5129. });
  5130. svr.wait_until_ready();
  5131. Client cli(HOST, PORT);
  5132. {
  5133. auto res = cli.Get("/hi");
  5134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5135. EXPECT_EQ(StatusCode::OK_200, res->status);
  5136. EXPECT_EQ("hi", res->body);
  5137. }
  5138. {
  5139. auto res = cli.Get("/user/john");
  5140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5141. EXPECT_EQ(StatusCode::OK_200, res->status);
  5142. EXPECT_EQ("john", res->body);
  5143. }
  5144. {
  5145. auto res = cli.Get("/user/invalid-user");
  5146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5147. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5148. EXPECT_EQ("error", res->body);
  5149. }
  5150. }
  5151. // The pre-request handler must run before the request body is read, so a
  5152. // rejected request never forces the server to buffer a (potentially large)
  5153. // body. Here the posted body is larger than the payload limit: if the body
  5154. // were read first the server would answer 413, but because the pre-request
  5155. // handler runs first it answers 403 and the body is never read.
  5156. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5157. Server svr;
  5158. svr.set_payload_max_length(8);
  5159. auto handler_ran = false;
  5160. svr.Post("/reject", [&](const Request &req, Response &res) {
  5161. handler_ran = true;
  5162. res.set_content(req.body, "text/plain");
  5163. });
  5164. svr.Post("/accept", [](const Request &req, Response &res) {
  5165. res.set_content(req.body, "text/plain");
  5166. });
  5167. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5168. if (req.matched_route == "/reject") {
  5169. res.status = StatusCode::Forbidden_403;
  5170. res.set_content("denied", "text/plain");
  5171. return Server::HandlerResponse::Handled;
  5172. }
  5173. return Server::HandlerResponse::Unhandled;
  5174. });
  5175. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5176. auto se = detail::scope_exit([&] {
  5177. svr.stop();
  5178. thread.join();
  5179. ASSERT_FALSE(svr.is_running());
  5180. });
  5181. svr.wait_until_ready();
  5182. Client cli(HOST, PORT);
  5183. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5184. // rejects with 403 before the body is read, so 413 is never reached.
  5185. {
  5186. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5188. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5189. EXPECT_EQ("denied", res->body);
  5190. EXPECT_FALSE(handler_ran);
  5191. }
  5192. // An approved route still reads the body and enforces the payload limit.
  5193. {
  5194. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5196. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5197. }
  5198. }
  5199. TEST(UserDataTest, BasicOperations) {
  5200. httplib::UserData ud;
  5201. // Initially empty
  5202. EXPECT_FALSE(ud.has("key"));
  5203. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5204. // set and get
  5205. ud.set("key", 42);
  5206. EXPECT_TRUE(ud.has("key"));
  5207. auto *p = ud.get<int>("key");
  5208. ASSERT_NE(nullptr, p);
  5209. EXPECT_EQ(42, *p);
  5210. // Type mismatch → nullptr
  5211. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5212. // Overwrite with different type
  5213. ud.set("key", std::string("hello"));
  5214. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5215. auto *s = ud.get<std::string>("key");
  5216. ASSERT_NE(nullptr, s);
  5217. EXPECT_EQ("hello", *s);
  5218. // erase
  5219. ud.erase("key");
  5220. EXPECT_FALSE(ud.has("key"));
  5221. // clear
  5222. ud.set("a", 1);
  5223. ud.set("b", 2);
  5224. ud.clear();
  5225. EXPECT_FALSE(ud.has("a"));
  5226. EXPECT_FALSE(ud.has("b"));
  5227. }
  5228. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5229. struct AuthCtx {
  5230. std::string user_id;
  5231. };
  5232. Server svr;
  5233. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5234. res.user_data.set("auth", AuthCtx{"alice"});
  5235. return Server::HandlerResponse::Unhandled;
  5236. });
  5237. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5238. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5239. ASSERT_NE(nullptr, ctx);
  5240. res.set_content("Hello " + ctx->user_id, "text/plain");
  5241. });
  5242. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5243. auto se = detail::scope_exit([&] {
  5244. svr.stop();
  5245. thread.join();
  5246. ASSERT_FALSE(svr.is_running());
  5247. });
  5248. svr.wait_until_ready();
  5249. Client cli(HOST, PORT);
  5250. auto res = cli.Get("/me");
  5251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5252. EXPECT_EQ(StatusCode::OK_200, res->status);
  5253. EXPECT_EQ("Hello alice", res->body);
  5254. }
  5255. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5256. struct RoleCtx {
  5257. std::string role;
  5258. };
  5259. Server svr;
  5260. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5261. res.user_data.set("role", RoleCtx{"admin"});
  5262. return Server::HandlerResponse::Unhandled;
  5263. });
  5264. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5265. auto *ctx = res.user_data.get<RoleCtx>("role");
  5266. ASSERT_NE(nullptr, ctx);
  5267. res.set_content(ctx->role, "text/plain");
  5268. });
  5269. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5270. auto se = detail::scope_exit([&] {
  5271. svr.stop();
  5272. thread.join();
  5273. ASSERT_FALSE(svr.is_running());
  5274. });
  5275. svr.wait_until_ready();
  5276. Client cli(HOST, PORT);
  5277. auto res = cli.Get("/role");
  5278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5279. EXPECT_EQ(StatusCode::OK_200, res->status);
  5280. EXPECT_EQ("admin", res->body);
  5281. }
  5282. TEST(InvalidFormatTest, StatusCode) {
  5283. Server svr;
  5284. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5285. res.set_content("Hello World!\n", "text/plain");
  5286. res.status = 9999; // Status should be a three-digit code...
  5287. });
  5288. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5289. auto se = detail::scope_exit([&] {
  5290. svr.stop();
  5291. thread.join();
  5292. ASSERT_FALSE(svr.is_running());
  5293. });
  5294. svr.wait_until_ready();
  5295. {
  5296. Client cli(HOST, PORT);
  5297. auto res = cli.Get("/hi");
  5298. ASSERT_FALSE(res);
  5299. }
  5300. }
  5301. TEST(URLFragmentTest, WithFragment) {
  5302. Server svr;
  5303. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5304. EXPECT_TRUE(req.target == "/hi");
  5305. });
  5306. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5307. auto se = detail::scope_exit([&] {
  5308. svr.stop();
  5309. thread.join();
  5310. ASSERT_FALSE(svr.is_running());
  5311. });
  5312. svr.wait_until_ready();
  5313. {
  5314. Client cli(HOST, PORT);
  5315. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5316. EXPECT_TRUE(res);
  5317. EXPECT_EQ(StatusCode::OK_200, res->status);
  5318. res = cli.Get("/hi%23key1=val1=key2=val2");
  5319. EXPECT_TRUE(res);
  5320. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5321. }
  5322. }
  5323. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5324. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5325. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5326. Server svr;
  5327. std::vector<std::string> targets;
  5328. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5329. targets.push_back(req.target);
  5330. });
  5331. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5332. auto se = detail::scope_exit([&] {
  5333. svr.stop();
  5334. thread.join();
  5335. ASSERT_FALSE(svr.is_running());
  5336. });
  5337. svr.wait_until_ready();
  5338. Client cli(HOST, PORT);
  5339. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5340. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5341. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5342. // A '?' after the '#' belongs to the fragment, not to the query.
  5343. Request req;
  5344. req.method = "GET";
  5345. req.path = "/hi#f?x=1";
  5346. req.params.emplace("a", "1");
  5347. Response res;
  5348. auto error = Error::Success;
  5349. EXPECT_TRUE(cli.send(req, res, error));
  5350. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5351. "/hi?a=1"}),
  5352. targets);
  5353. }
  5354. TEST(HeaderWriter, SetHeaderWriter) {
  5355. Server svr;
  5356. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5357. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5358. return detail::write_headers(strm, hdrs);
  5359. });
  5360. svr.Get("/hi", [](const Request &req, Response &res) {
  5361. auto it = req.headers.find("CustomClientHeader");
  5362. EXPECT_TRUE(it != req.headers.end());
  5363. EXPECT_EQ(it->second, "CustomClientValue");
  5364. res.set_content("Hello World!\n", "text/plain");
  5365. });
  5366. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5367. auto se = detail::scope_exit([&] {
  5368. svr.stop();
  5369. thread.join();
  5370. ASSERT_FALSE(svr.is_running());
  5371. });
  5372. svr.wait_until_ready();
  5373. {
  5374. Client cli(HOST, PORT);
  5375. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5376. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5377. return detail::write_headers(strm, hdrs);
  5378. });
  5379. auto res = cli.Get("/hi");
  5380. EXPECT_TRUE(res);
  5381. EXPECT_EQ(StatusCode::OK_200, res->status);
  5382. auto it = res->headers.find("CustomServerHeader");
  5383. EXPECT_TRUE(it != res->headers.end());
  5384. EXPECT_EQ(it->second, "CustomServerValue");
  5385. }
  5386. }
  5387. class ServerTest : public ::testing::Test {
  5388. protected:
  5389. ServerTest()
  5390. : cli_(HOST, PORT)
  5391. #ifdef CPPHTTPLIB_SSL_ENABLED
  5392. ,
  5393. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5394. #endif
  5395. {
  5396. #ifdef CPPHTTPLIB_SSL_ENABLED
  5397. cli_.enable_server_certificate_verification(false);
  5398. #endif
  5399. // Allow LARGE_DATA (100MB) responses
  5400. cli_.set_payload_max_length(200 * 1024 * 1024);
  5401. }
  5402. virtual void SetUp() {
  5403. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5404. svr_.set_payload_max_length(200 * 1024 * 1024);
  5405. svr_.set_mount_point("/", "./www");
  5406. svr_.set_mount_point("/mount", "./www2");
  5407. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5408. svr_.Get("/hi",
  5409. [&](const Request & /*req*/, Response &res) {
  5410. res.set_content("Hello World!", "text/plain");
  5411. })
  5412. .Get("/file_content",
  5413. [&](const Request & /*req*/, Response &res) {
  5414. res.set_file_content("./www/dir/test.html");
  5415. })
  5416. .Get("/file_content_with_content_type",
  5417. [&](const Request & /*req*/, Response &res) {
  5418. res.set_file_content("./www/file", "text/plain");
  5419. })
  5420. .Get("/invalid_file_content",
  5421. [&](const Request & /*req*/, Response &res) {
  5422. res.set_file_content("./www/dir/invalid_file_path");
  5423. })
  5424. .Get("/http_response_splitting",
  5425. [&](const Request & /*req*/, Response &res) {
  5426. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5427. EXPECT_EQ(0U, res.headers.size());
  5428. EXPECT_FALSE(res.has_header("a"));
  5429. res.set_header("a", "1\nSet-Cookie: a=1");
  5430. EXPECT_EQ(0U, res.headers.size());
  5431. EXPECT_FALSE(res.has_header("a"));
  5432. res.set_header("a", "1\rSet-Cookie: a=1");
  5433. EXPECT_EQ(0U, res.headers.size());
  5434. EXPECT_FALSE(res.has_header("a"));
  5435. res.set_header("a\r\nb", "0");
  5436. EXPECT_EQ(0U, res.headers.size());
  5437. EXPECT_FALSE(res.has_header("a"));
  5438. res.set_header("a\rb", "0");
  5439. EXPECT_EQ(0U, res.headers.size());
  5440. EXPECT_FALSE(res.has_header("a"));
  5441. res.set_header("a\nb", "0");
  5442. EXPECT_EQ(0U, res.headers.size());
  5443. EXPECT_FALSE(res.has_header("a"));
  5444. res.set_redirect("1\r\nSet-Cookie: a=1");
  5445. EXPECT_EQ(0U, res.headers.size());
  5446. EXPECT_FALSE(res.has_header("Location"));
  5447. })
  5448. .Get("/slow",
  5449. [&](const Request & /*req*/, Response &res) {
  5450. std::this_thread::sleep_for(std::chrono::seconds(4));
  5451. res.set_content("slow", "text/plain");
  5452. })
  5453. #if 0
  5454. .Post("/slowpost",
  5455. [&](const Request & /*req*/, Response &res) {
  5456. std::this_thread::sleep_for(std::chrono::seconds(2));
  5457. res.set_content("slow", "text/plain");
  5458. })
  5459. #endif
  5460. .Get("/remote_addr",
  5461. [&](const Request &req, Response &res) {
  5462. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5463. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5464. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5465. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5466. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5467. #endif
  5468. res.set_content(req.remote_addr, "text/plain");
  5469. })
  5470. .Get("/local_addr",
  5471. [&](const Request &req, Response &res) {
  5472. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5473. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5474. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5475. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5476. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5477. #endif
  5478. auto local_addr = req.local_addr;
  5479. auto local_port = std::to_string(req.local_port);
  5480. res.set_content(local_addr.append(":").append(local_port),
  5481. "text/plain");
  5482. })
  5483. .Get("/endwith%",
  5484. [&](const Request & /*req*/, Response &res) {
  5485. res.set_content("Hello World!", "text/plain");
  5486. })
  5487. .Get("/a\\+\\+b",
  5488. [&](const Request &req, Response &res) {
  5489. ASSERT_TRUE(req.has_param("a +b"));
  5490. auto val = req.get_param_value("a +b");
  5491. res.set_content(val, "text/plain");
  5492. })
  5493. .Get("/", [&](const Request & /*req*/,
  5494. Response &res) { res.set_redirect("/hi"); })
  5495. .Post("/1",
  5496. [](const Request & /*req*/, Response &res) {
  5497. res.set_redirect("/2", StatusCode::SeeOther_303);
  5498. })
  5499. .Get("/2",
  5500. [](const Request & /*req*/, Response &res) {
  5501. res.set_content("redirected.", "text/plain");
  5502. res.status = StatusCode::OK_200;
  5503. })
  5504. .Post("/person",
  5505. [&](const Request &req, Response &res) {
  5506. if (req.has_param("name") && req.has_param("note")) {
  5507. persons_[req.get_param_value("name")] =
  5508. req.get_param_value("note");
  5509. } else {
  5510. res.status = StatusCode::BadRequest_400;
  5511. }
  5512. })
  5513. .Put("/person",
  5514. [&](const Request &req, Response &res) {
  5515. if (req.has_param("name") && req.has_param("note")) {
  5516. persons_[req.get_param_value("name")] =
  5517. req.get_param_value("note");
  5518. } else {
  5519. res.status = StatusCode::BadRequest_400;
  5520. }
  5521. })
  5522. .Get("/person/(.*)",
  5523. [&](const Request &req, Response &res) {
  5524. string name = req.matches[1];
  5525. if (persons_.find(name) != persons_.end()) {
  5526. auto note = persons_[name];
  5527. res.set_content(note, "text/plain");
  5528. } else {
  5529. res.status = StatusCode::NotFound_404;
  5530. }
  5531. })
  5532. .Delete("/person",
  5533. [&](const Request &req, Response &res) {
  5534. if (req.has_param("name")) {
  5535. string name = req.get_param_value("name");
  5536. if (persons_.find(name) != persons_.end()) {
  5537. persons_.erase(name);
  5538. res.set_content("DELETED", "text/plain");
  5539. } else {
  5540. res.status = StatusCode::NotFound_404;
  5541. }
  5542. } else {
  5543. res.status = StatusCode::BadRequest_400;
  5544. }
  5545. })
  5546. .Post("/x-www-form-urlencoded-json",
  5547. [&](const Request &req, Response &res) {
  5548. auto json = req.get_param_value("json");
  5549. ASSERT_EQ(JSON_DATA, json);
  5550. res.set_content(json, "appliation/json");
  5551. res.status = StatusCode::OK_200;
  5552. })
  5553. .Get("/streamed-chunked",
  5554. [&](const Request & /*req*/, Response &res) {
  5555. res.set_chunked_content_provider(
  5556. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5557. sink.os << "123";
  5558. sink.os << "456";
  5559. sink.os << "789";
  5560. sink.done();
  5561. return true;
  5562. });
  5563. })
  5564. .Get("/streamed-chunked-with-prohibited-trailer",
  5565. [&](const Request & /*req*/, Response &res) {
  5566. auto i = new int(0);
  5567. // Declare both a prohibited trailer (Content-Length) and an
  5568. // allowed one
  5569. res.set_header("Trailer", "Content-Length, X-Allowed");
  5570. res.set_chunked_content_provider(
  5571. "text/plain",
  5572. [i](size_t /*offset*/, DataSink &sink) {
  5573. switch (*i) {
  5574. case 0: sink.os << "123"; break;
  5575. case 1: sink.os << "456"; break;
  5576. case 2: sink.os << "789"; break;
  5577. case 3: {
  5578. sink.done_with_trailer(
  5579. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5580. } break;
  5581. }
  5582. (*i)++;
  5583. return true;
  5584. },
  5585. [i](bool success) {
  5586. EXPECT_TRUE(success);
  5587. delete i;
  5588. });
  5589. })
  5590. .Get("/streamed-chunked2",
  5591. [&](const Request & /*req*/, Response &res) {
  5592. auto i = new int(0);
  5593. res.set_chunked_content_provider(
  5594. "text/plain",
  5595. [i](size_t /*offset*/, DataSink &sink) {
  5596. switch (*i) {
  5597. case 0: sink.os << "123"; break;
  5598. case 1: sink.os << "456"; break;
  5599. case 2: sink.os << "789"; break;
  5600. case 3: sink.done(); break;
  5601. }
  5602. (*i)++;
  5603. return true;
  5604. },
  5605. [i](bool success) {
  5606. EXPECT_TRUE(success);
  5607. delete i;
  5608. });
  5609. })
  5610. .Get("/streamed-chunked-with-trailer",
  5611. [&](const Request & /*req*/, Response &res) {
  5612. auto i = new int(0);
  5613. res.set_header("Trailer", "Dummy1, Dummy2");
  5614. res.set_chunked_content_provider(
  5615. "text/plain",
  5616. [i](size_t /*offset*/, DataSink &sink) {
  5617. switch (*i) {
  5618. case 0: sink.os << "123"; break;
  5619. case 1: sink.os << "456"; break;
  5620. case 2: sink.os << "789"; break;
  5621. case 3: {
  5622. sink.done_with_trailer(
  5623. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5624. } break;
  5625. }
  5626. (*i)++;
  5627. return true;
  5628. },
  5629. [i](bool success) {
  5630. EXPECT_TRUE(success);
  5631. delete i;
  5632. });
  5633. })
  5634. .Get("/streamed",
  5635. [&](const Request & /*req*/, Response &res) {
  5636. res.set_content_provider(
  5637. 6, "text/plain",
  5638. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5639. sink.os << (offset < 3 ? "a" : "b");
  5640. return true;
  5641. });
  5642. })
  5643. .Get("/streamed-without-length",
  5644. [&](const Request & /*req*/, Response &res) {
  5645. auto data = new std::string("abcdefg");
  5646. res.set_content_provider(
  5647. "text/plain",
  5648. [data](size_t offset, DataSink &sink) {
  5649. if (offset < data->size()) {
  5650. sink.os << data->substr(offset);
  5651. }
  5652. sink.done();
  5653. return true;
  5654. },
  5655. [data](bool success) {
  5656. EXPECT_TRUE(success);
  5657. delete data;
  5658. });
  5659. })
  5660. .Get("/streamed-with-range",
  5661. [&](const Request &req, Response &res) {
  5662. auto data = new std::string("abcdefg");
  5663. // An explicit status keeps the server from picking the 206 it
  5664. // would otherwise choose for a ranged request, so the response
  5665. // is not a partial representation.
  5666. auto status = req.get_param_value("status");
  5667. if (status == "200") {
  5668. res.status = StatusCode::OK_200;
  5669. } else if (status == "403") {
  5670. res.status = StatusCode::Forbidden_403;
  5671. }
  5672. res.set_content_provider(
  5673. data->size(), "text/plain",
  5674. [data](size_t offset, size_t length, DataSink &sink) {
  5675. size_t DATA_CHUNK_SIZE = 4;
  5676. const auto &d = *data;
  5677. auto out_len =
  5678. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5679. auto ret =
  5680. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5681. EXPECT_TRUE(ret);
  5682. return true;
  5683. },
  5684. [data, &req](bool success) {
  5685. EXPECT_EQ(success, !req.has_param("error"));
  5686. delete data;
  5687. });
  5688. })
  5689. .Get("/streamed-cancel",
  5690. [&](const Request & /*req*/, Response &res) {
  5691. res.set_content_provider(
  5692. size_t(-1), "text/plain",
  5693. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5694. sink.os << "data_chunk";
  5695. return true;
  5696. });
  5697. })
  5698. .Get("/regex-with-delimiter",
  5699. [&](const Request &req, Response & /*res*/) {
  5700. ASSERT_TRUE(req.has_param("key"));
  5701. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5702. })
  5703. .Get("/with-range",
  5704. [&](const Request & /*req*/, Response &res) {
  5705. res.set_content("abcdefg", "text/plain");
  5706. })
  5707. .Get("/test-start-time",
  5708. [&](const Request &req, Response & /*res*/) {
  5709. EXPECT_NE(req.start_time_,
  5710. std::chrono::steady_clock::time_point::min());
  5711. })
  5712. .Get("/with-range-customized-response",
  5713. [&](const Request & /*req*/, Response &res) {
  5714. res.status = StatusCode::BadRequest_400;
  5715. res.set_content(JSON_DATA, "application/json");
  5716. })
  5717. .Post("/chunked",
  5718. [&](const Request &req, Response & /*res*/) {
  5719. EXPECT_EQ(req.body, "dechunked post body");
  5720. })
  5721. .Post("/large-chunked",
  5722. [&](const Request &req, Response & /*res*/) {
  5723. std::string expected(6 * 30 * 1024u, 'a');
  5724. EXPECT_EQ(req.body, expected);
  5725. })
  5726. .Post("/multipart",
  5727. [&](const Request &req, Response & /*res*/) {
  5728. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5729. req.form.get_field_count("text2") +
  5730. req.form.get_field_count("file3") +
  5731. req.form.get_field_count("file4"));
  5732. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5733. req.form.get_file_count("file2"));
  5734. ASSERT_TRUE(!req.form.has_file("???"));
  5735. ASSERT_TRUE(!req.form.has_field("???"));
  5736. ASSERT_TRUE(req.body.empty());
  5737. {
  5738. const auto &text = req.form.get_field("text1");
  5739. EXPECT_EQ("text default", text);
  5740. }
  5741. {
  5742. const auto &text = req.form.get_field("text2");
  5743. EXPECT_EQ("aωb", text);
  5744. }
  5745. {
  5746. const auto &file = req.form.get_file("file1");
  5747. EXPECT_EQ("hello.txt", file.filename);
  5748. EXPECT_EQ("text/plain", file.content_type);
  5749. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5750. }
  5751. {
  5752. const auto &file = req.form.get_file("file2");
  5753. EXPECT_EQ("world.json", file.filename);
  5754. EXPECT_EQ("application/json", file.content_type);
  5755. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5756. }
  5757. {
  5758. const auto &text = req.form.get_field("file3");
  5759. EXPECT_EQ(0u, text.size());
  5760. }
  5761. {
  5762. const auto &text = req.form.get_field("file4");
  5763. EXPECT_EQ(0u, text.size());
  5764. }
  5765. })
  5766. .Post("/multipart/multi_file_values",
  5767. [&](const Request &req, Response & /*res*/) {
  5768. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5769. req.form.get_field_count("multi_text1"));
  5770. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5771. ASSERT_TRUE(!req.form.has_file("???"));
  5772. ASSERT_TRUE(!req.form.has_field("???"));
  5773. ASSERT_TRUE(req.body.empty());
  5774. {
  5775. const auto &text = req.form.get_field("text");
  5776. EXPECT_EQ("default text", text);
  5777. }
  5778. {
  5779. const auto &text1_values = req.form.get_fields("multi_text1");
  5780. EXPECT_EQ(2u, text1_values.size());
  5781. EXPECT_EQ("aaaaa", text1_values[0]);
  5782. EXPECT_EQ("bbbbb", text1_values[1]);
  5783. }
  5784. {
  5785. const auto &file1_values = req.form.get_files("multi_file1");
  5786. EXPECT_EQ(2u, file1_values.size());
  5787. auto file1 = file1_values[0];
  5788. EXPECT_EQ(file1.filename, "hello.txt");
  5789. EXPECT_EQ(file1.content_type, "text/plain");
  5790. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5791. auto file2 = file1_values[1];
  5792. EXPECT_EQ(file2.filename, "world.json");
  5793. EXPECT_EQ(file2.content_type, "application/json");
  5794. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5795. }
  5796. })
  5797. .Post("/empty",
  5798. [&](const Request &req, Response &res) {
  5799. EXPECT_EQ(req.body, "");
  5800. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5801. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5802. res.set_content("empty", "text/plain");
  5803. })
  5804. .Post("/empty-no-content-type",
  5805. [&](const Request &req, Response &res) {
  5806. EXPECT_EQ(req.body, "");
  5807. EXPECT_FALSE(req.has_header("Content-Type"));
  5808. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5809. res.set_content("empty-no-content-type", "text/plain");
  5810. })
  5811. .Post("/path-only",
  5812. [&](const Request &req, Response &res) {
  5813. EXPECT_EQ(req.body, "");
  5814. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5815. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5816. res.set_content("path-only", "text/plain");
  5817. })
  5818. .Post("/path-headers-only",
  5819. [&](const Request &req, Response &res) {
  5820. EXPECT_EQ(req.body, "");
  5821. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5822. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5823. EXPECT_EQ("world", req.get_header_value("hello"));
  5824. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5825. res.set_content("path-headers-only", "text/plain");
  5826. })
  5827. .Post("/post-large",
  5828. [&](const Request &req, Response &res) {
  5829. EXPECT_EQ(req.body, LARGE_DATA);
  5830. res.set_content(req.body, "text/plain");
  5831. })
  5832. .Post("/post-loopback",
  5833. [&](const Request &, Response &res,
  5834. ContentReader const &content_reader) {
  5835. std::string body;
  5836. content_reader([&](const char *data, size_t data_length) {
  5837. body.append(data, data_length);
  5838. return true;
  5839. });
  5840. res.set_content(body, "text/plain");
  5841. })
  5842. .Put("/put-loopback",
  5843. [&](const Request &, Response &res,
  5844. ContentReader const &content_reader) {
  5845. std::string body;
  5846. content_reader([&](const char *data, size_t data_length) {
  5847. body.append(data, data_length);
  5848. return true;
  5849. });
  5850. res.set_content(body, "text/plain");
  5851. })
  5852. .Patch("/patch-loopback",
  5853. [&](const Request &, Response &res,
  5854. ContentReader const &content_reader) {
  5855. std::string body;
  5856. content_reader([&](const char *data, size_t data_length) {
  5857. body.append(data, data_length);
  5858. return true;
  5859. });
  5860. res.set_content(body, "text/plain");
  5861. })
  5862. .Put("/empty-no-content-type",
  5863. [&](const Request &req, Response &res) {
  5864. EXPECT_EQ(req.body, "");
  5865. EXPECT_FALSE(req.has_header("Content-Type"));
  5866. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5867. res.set_content("empty-no-content-type", "text/plain");
  5868. })
  5869. .Put("/put",
  5870. [&](const Request &req, Response &res) {
  5871. EXPECT_EQ(req.body, "PUT");
  5872. res.set_content(req.body, "text/plain");
  5873. })
  5874. .Put("/put-large",
  5875. [&](const Request &req, Response &res) {
  5876. EXPECT_EQ(req.body, LARGE_DATA);
  5877. res.set_content(req.body, "text/plain");
  5878. })
  5879. .Patch("/patch",
  5880. [&](const Request &req, Response &res) {
  5881. EXPECT_EQ(req.body, "PATCH");
  5882. res.set_content(req.body, "text/plain");
  5883. })
  5884. .Delete("/delete",
  5885. [&](const Request & /*req*/, Response &res) {
  5886. res.set_content("DELETE", "text/plain");
  5887. })
  5888. .Delete("/delete-body",
  5889. [&](const Request &req, Response &res) {
  5890. EXPECT_EQ(req.body, "content");
  5891. res.set_content(req.body, "text/plain");
  5892. })
  5893. .Options(R"(\*)",
  5894. [&](const Request & /*req*/, Response &res) {
  5895. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5896. })
  5897. .CustomRoute("PROPFIND", "/dav/:id",
  5898. [&](const Request &req, Response &res) {
  5899. res.set_header("x-body-size",
  5900. std::to_string(req.body.size()));
  5901. res.set_header("x-matched-route", req.matched_route);
  5902. res.set_header("x-dav-id", req.path_params.at("id"));
  5903. res.status = StatusCode::MultiStatus_207;
  5904. res.set_content(req.body, "application/xml");
  5905. })
  5906. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5907. [&](const Request &req, Response &res) {
  5908. res.set_header("x-dav-match", req.matches[1]);
  5909. res.status = StatusCode::MultiStatus_207;
  5910. })
  5911. .CustomRoute("MKCOL", "/dav-mkcol",
  5912. [&](const Request &req, Response &res) {
  5913. EXPECT_TRUE(req.body.empty());
  5914. res.status = StatusCode::Created_201;
  5915. })
  5916. .CustomRoute(
  5917. "REPORT", "/dav-report",
  5918. [&](const Request & /*req*/, Response &res,
  5919. const ContentReader &content_reader) {
  5920. std::string body;
  5921. content_reader([&](const char *data, size_t data_length) {
  5922. body.append(data, data_length);
  5923. return true;
  5924. });
  5925. res.set_header("x-body-size", std::to_string(body.size()));
  5926. res.status = StatusCode::MultiStatus_207;
  5927. res.set_content(body, "application/xml");
  5928. })
  5929. .Get("/request-target",
  5930. [&](const Request &req, Response & /*res*/) {
  5931. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5932. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5933. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5934. })
  5935. .Get("/long-query-value",
  5936. [&](const Request &req, Response & /*res*/) {
  5937. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5938. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5939. })
  5940. .Get("/too-long-query-value",
  5941. [&](const Request &req, Response & /*res*/) {
  5942. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5943. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5944. })
  5945. .Get("/array-param",
  5946. [&](const Request &req, Response & /*res*/) {
  5947. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5948. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5949. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5950. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5951. })
  5952. .Get("/array-param-values",
  5953. [&](const Request &req, Response & /*res*/) {
  5954. auto values = req.get_param_values("array");
  5955. EXPECT_EQ(3u, values.size());
  5956. EXPECT_EQ("value1", values[0]);
  5957. EXPECT_EQ("value2", values[1]);
  5958. EXPECT_EQ("value3", values[2]);
  5959. auto empty = req.get_param_values("nonexistent");
  5960. EXPECT_TRUE(empty.empty());
  5961. })
  5962. .Post("/validate-no-multiple-headers",
  5963. [&](const Request &req, Response & /*res*/) {
  5964. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5965. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5966. })
  5967. .Post("/content_receiver",
  5968. [&](const Request &req, Response &res,
  5969. const ContentReader &content_reader) {
  5970. if (req.is_multipart_form_data()) {
  5971. std::vector<FormData> items;
  5972. content_reader(
  5973. [&](const FormData &file) {
  5974. items.push_back(file);
  5975. return true;
  5976. },
  5977. [&](const char *data, size_t data_length) {
  5978. items.back().content.append(data, data_length);
  5979. return true;
  5980. });
  5981. EXPECT_EQ(5u, items.size());
  5982. {
  5983. const auto &file = get_file_value(items, "text1");
  5984. EXPECT_TRUE(file.filename.empty());
  5985. EXPECT_EQ("text default", file.content);
  5986. }
  5987. {
  5988. const auto &file = get_file_value(items, "text2");
  5989. EXPECT_TRUE(file.filename.empty());
  5990. EXPECT_EQ("aωb", file.content);
  5991. }
  5992. {
  5993. const auto &file = get_file_value(items, "file1");
  5994. EXPECT_EQ("hello.txt", file.filename);
  5995. EXPECT_EQ("text/plain", file.content_type);
  5996. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5997. }
  5998. {
  5999. const auto &file = get_file_value(items, "file2");
  6000. EXPECT_EQ("world.json", file.filename);
  6001. EXPECT_EQ("application/json", file.content_type);
  6002. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6003. }
  6004. {
  6005. const auto &file = get_file_value(items, "file3");
  6006. EXPECT_TRUE(file.filename.empty());
  6007. EXPECT_EQ("application/octet-stream", file.content_type);
  6008. EXPECT_EQ(0u, file.content.size());
  6009. }
  6010. } else {
  6011. std::string body;
  6012. content_reader([&](const char *data, size_t data_length) {
  6013. EXPECT_EQ(7U, data_length);
  6014. body.append(data, data_length);
  6015. return true;
  6016. });
  6017. EXPECT_EQ(body, "content");
  6018. res.set_content(body, "text/plain");
  6019. }
  6020. })
  6021. .Put("/content_receiver",
  6022. [&](const Request & /*req*/, Response &res,
  6023. const ContentReader &content_reader) {
  6024. std::string body;
  6025. content_reader([&](const char *data, size_t data_length) {
  6026. body.append(data, data_length);
  6027. return true;
  6028. });
  6029. EXPECT_EQ(body, "content");
  6030. res.set_content(body, "text/plain");
  6031. })
  6032. .Patch("/content_receiver",
  6033. [&](const Request & /*req*/, Response &res,
  6034. const ContentReader &content_reader) {
  6035. std::string body;
  6036. content_reader([&](const char *data, size_t data_length) {
  6037. body.append(data, data_length);
  6038. return true;
  6039. });
  6040. EXPECT_EQ(body, "content");
  6041. res.set_content(body, "text/plain");
  6042. })
  6043. .Post("/query-string-and-body",
  6044. [&](const Request &req, Response & /*res*/) {
  6045. ASSERT_TRUE(req.has_param("key"));
  6046. EXPECT_EQ(req.get_param_value("key"), "value");
  6047. EXPECT_EQ(req.body, "content");
  6048. })
  6049. .Get("/last-request",
  6050. [&](const Request &req, Response & /*res*/) {
  6051. EXPECT_EQ("close", req.get_header_value("Connection"));
  6052. })
  6053. .Get(R"(/redirect/(\d+))",
  6054. [&](const Request &req, Response &res) {
  6055. auto num = std::stoi(req.matches[1]) + 1;
  6056. std::string url = "/redirect/" + std::to_string(num);
  6057. res.set_redirect(url);
  6058. })
  6059. .Post("/binary",
  6060. [&](const Request &req, Response &res) {
  6061. EXPECT_EQ(4U, req.body.size());
  6062. EXPECT_EQ("application/octet-stream",
  6063. req.get_header_value("Content-Type"));
  6064. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6065. res.set_content(req.body, "application/octet-stream");
  6066. })
  6067. .Put("/binary",
  6068. [&](const Request &req, Response &res) {
  6069. EXPECT_EQ(4U, req.body.size());
  6070. EXPECT_EQ("application/octet-stream",
  6071. req.get_header_value("Content-Type"));
  6072. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6073. res.set_content(req.body, "application/octet-stream");
  6074. })
  6075. .Patch("/binary",
  6076. [&](const Request &req, Response &res) {
  6077. EXPECT_EQ(4U, req.body.size());
  6078. EXPECT_EQ("application/octet-stream",
  6079. req.get_header_value("Content-Type"));
  6080. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6081. res.set_content(req.body, "application/octet-stream");
  6082. })
  6083. .Delete("/binary",
  6084. [&](const Request &req, Response &res) {
  6085. EXPECT_EQ(4U, req.body.size());
  6086. EXPECT_EQ("application/octet-stream",
  6087. req.get_header_value("Content-Type"));
  6088. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6089. res.set_content(req.body, "application/octet-stream");
  6090. })
  6091. .Get("/issue1772",
  6092. [&](const Request & /*req*/, Response &res) {
  6093. res.status = 401;
  6094. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6095. })
  6096. .Delete("/issue609",
  6097. [](const httplib::Request &, httplib::Response &res,
  6098. const httplib::ContentReader &) {
  6099. res.set_content("ok", "text/plain");
  6100. })
  6101. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6102. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6103. .Get("/compress",
  6104. [&](const Request & /*req*/, Response &res) {
  6105. res.set_content(
  6106. "12345678901234567890123456789012345678901234567890123456789"
  6107. "01234567890123456789012345678901234567890",
  6108. "text/plain");
  6109. })
  6110. .Get("/compress-with-charset",
  6111. [&](const Request & /*req*/, Response &res) {
  6112. res.set_content(
  6113. "12345678901234567890123456789012345678901234567890123456789"
  6114. "01234567890123456789012345678901234567890",
  6115. "application/json; charset=utf-8");
  6116. })
  6117. .Get("/nocompress",
  6118. [&](const Request & /*req*/, Response &res) {
  6119. res.set_content(
  6120. "12345678901234567890123456789012345678901234567890123456789"
  6121. "01234567890123456789012345678901234567890",
  6122. "application/octet-stream");
  6123. })
  6124. .Post("/compress-multipart",
  6125. [&](const Request &req, Response & /*res*/) {
  6126. EXPECT_EQ(2u, req.form.fields.size());
  6127. ASSERT_TRUE(!req.form.has_field("???"));
  6128. {
  6129. const auto &text = req.form.get_field("key1");
  6130. EXPECT_EQ("test", text);
  6131. }
  6132. {
  6133. const auto &text = req.form.get_field("key2");
  6134. EXPECT_EQ("--abcdefg123", text);
  6135. }
  6136. })
  6137. #endif
  6138. ;
  6139. persons_["john"] = "programmer";
  6140. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6141. svr_.wait_until_ready();
  6142. }
  6143. virtual void TearDown() {
  6144. svr_.stop();
  6145. if (!request_threads_.empty()) {
  6146. std::this_thread::sleep_for(std::chrono::seconds(1));
  6147. for (auto &t : request_threads_) {
  6148. t.join();
  6149. }
  6150. }
  6151. t_.join();
  6152. }
  6153. map<string, string> persons_;
  6154. #ifdef CPPHTTPLIB_SSL_ENABLED
  6155. SSLClient cli_;
  6156. SSLServer svr_;
  6157. #else
  6158. Client cli_;
  6159. Server svr_;
  6160. #endif
  6161. thread t_;
  6162. std::vector<thread> request_threads_;
  6163. };
  6164. TEST_F(ServerTest, GetMethod200) {
  6165. auto res = cli_.Get("/hi");
  6166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6167. EXPECT_EQ("HTTP/1.1", res->version);
  6168. EXPECT_EQ(StatusCode::OK_200, res->status);
  6169. EXPECT_EQ("OK", res->reason);
  6170. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6171. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6172. EXPECT_EQ("Hello World!", res->body);
  6173. }
  6174. TEST_F(ServerTest, GetEmptyFile) {
  6175. auto res = cli_.Get("/empty_file");
  6176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6177. EXPECT_EQ(StatusCode::OK_200, res->status);
  6178. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6179. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6180. EXPECT_EQ("", res->body);
  6181. }
  6182. TEST_F(ServerTest, GetFileContent) {
  6183. auto res = cli_.Get("/file_content");
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. EXPECT_EQ(StatusCode::OK_200, res->status);
  6186. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6187. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6188. EXPECT_EQ("test.html", res->body);
  6189. }
  6190. TEST_F(ServerTest, GetFileContentWithRange) {
  6191. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6192. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6193. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6194. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6195. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6196. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6197. EXPECT_EQ("est", res->body);
  6198. }
  6199. TEST_F(ServerTest, GetFileContentWithContentType) {
  6200. auto res = cli_.Get("/file_content_with_content_type");
  6201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6202. EXPECT_EQ(StatusCode::OK_200, res->status);
  6203. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6204. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6205. EXPECT_EQ("file\n", res->body);
  6206. }
  6207. TEST_F(ServerTest, GetInvalidFileContent) {
  6208. auto res = cli_.Get("/invalid_file_content");
  6209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6210. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6211. }
  6212. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6213. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6215. EXPECT_EQ("HTTP/1.1", res->version);
  6216. EXPECT_EQ(StatusCode::OK_200, res->status);
  6217. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6218. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6219. EXPECT_EQ("Hello World!", res->body);
  6220. }
  6221. TEST_F(ServerTest, GetMethod302) {
  6222. auto res = cli_.Get("/");
  6223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6224. EXPECT_EQ(StatusCode::Found_302, res->status);
  6225. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6226. }
  6227. TEST_F(ServerTest, GetMethod302Redirect) {
  6228. cli_.set_follow_location(true);
  6229. auto res = cli_.Get("/");
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. EXPECT_EQ(StatusCode::OK_200, res->status);
  6232. EXPECT_EQ("Hello World!", res->body);
  6233. EXPECT_EQ("/hi", res->location);
  6234. }
  6235. TEST_F(ServerTest, GetMethod404) {
  6236. auto res = cli_.Get("/invalid");
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6239. }
  6240. TEST_F(ServerTest, HeadMethod200) {
  6241. auto res = cli_.Head("/hi");
  6242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6243. EXPECT_EQ(StatusCode::OK_200, res->status);
  6244. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6245. EXPECT_TRUE(res->body.empty());
  6246. }
  6247. TEST_F(ServerTest, HeadMethod200Static) {
  6248. auto res = cli_.Head("/mount/dir/index.html");
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. EXPECT_EQ(StatusCode::OK_200, res->status);
  6251. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6252. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6253. EXPECT_TRUE(res->body.empty());
  6254. }
  6255. TEST_F(ServerTest, HeadMethod404) {
  6256. auto res = cli_.Head("/invalid");
  6257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6258. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6259. EXPECT_TRUE(res->body.empty());
  6260. }
  6261. TEST_F(ServerTest, GetMethodPersonJohn) {
  6262. auto res = cli_.Get("/person/john");
  6263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6264. EXPECT_EQ(StatusCode::OK_200, res->status);
  6265. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6266. EXPECT_EQ("programmer", res->body);
  6267. }
  6268. TEST_F(ServerTest, PostMethod1) {
  6269. auto res = cli_.Get("/person/john1");
  6270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6271. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6272. res = cli_.Post("/person", "name=john1&note=coder",
  6273. "application/x-www-form-urlencoded");
  6274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6275. ASSERT_EQ(StatusCode::OK_200, res->status);
  6276. res = cli_.Get("/person/john1");
  6277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6278. ASSERT_EQ(StatusCode::OK_200, res->status);
  6279. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6280. ASSERT_EQ("coder", res->body);
  6281. }
  6282. TEST_F(ServerTest, PostMethod2) {
  6283. auto res = cli_.Get("/person/john2");
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6286. Params params;
  6287. params.emplace("name", "john2");
  6288. params.emplace("note", "coder");
  6289. res = cli_.Post("/person", params);
  6290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6291. ASSERT_EQ(StatusCode::OK_200, res->status);
  6292. res = cli_.Get("/person/john2");
  6293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6294. ASSERT_EQ(StatusCode::OK_200, res->status);
  6295. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6296. ASSERT_EQ("coder", res->body);
  6297. }
  6298. TEST_F(ServerTest, PutMethod3) {
  6299. auto res = cli_.Get("/person/john3");
  6300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6301. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6302. Params params;
  6303. params.emplace("name", "john3");
  6304. params.emplace("note", "coder");
  6305. res = cli_.Put("/person", params);
  6306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6307. ASSERT_EQ(StatusCode::OK_200, res->status);
  6308. res = cli_.Get("/person/john3");
  6309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6310. ASSERT_EQ(StatusCode::OK_200, res->status);
  6311. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6312. ASSERT_EQ("coder", res->body);
  6313. }
  6314. TEST_F(ServerTest, DeleteMethod1) {
  6315. auto res = cli_.Get("/person/john4");
  6316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6317. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6318. Params params;
  6319. params.emplace("name", "john4");
  6320. params.emplace("note", "coder");
  6321. res = cli_.Post("/person", params);
  6322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6323. ASSERT_EQ(StatusCode::OK_200, res->status);
  6324. res = cli_.Get("/person/john4");
  6325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6326. ASSERT_EQ(StatusCode::OK_200, res->status);
  6327. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6328. ASSERT_EQ("coder", res->body);
  6329. Params delete_params;
  6330. delete_params.emplace("name", "john4");
  6331. res = cli_.Delete("/person", delete_params);
  6332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6333. ASSERT_EQ(StatusCode::OK_200, res->status);
  6334. ASSERT_EQ("DELETED", res->body);
  6335. res = cli_.Get("/person/john4");
  6336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6337. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6338. }
  6339. TEST_F(ServerTest, DeleteMethod2) {
  6340. auto res = cli_.Get("/person/john5");
  6341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6342. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6343. Params params;
  6344. params.emplace("name", "john5");
  6345. params.emplace("note", "developer");
  6346. res = cli_.Post("/person", params);
  6347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6348. ASSERT_EQ(StatusCode::OK_200, res->status);
  6349. res = cli_.Get("/person/john5");
  6350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6351. ASSERT_EQ(StatusCode::OK_200, res->status);
  6352. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6353. ASSERT_EQ("developer", res->body);
  6354. Params delete_params;
  6355. delete_params.emplace("name", "john5");
  6356. Headers headers;
  6357. headers.emplace("Custom-Header", "test-value");
  6358. res = cli_.Delete("/person", headers, delete_params);
  6359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6360. ASSERT_EQ(StatusCode::OK_200, res->status);
  6361. ASSERT_EQ("DELETED", res->body);
  6362. res = cli_.Get("/person/john5");
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6365. }
  6366. TEST_F(ServerTest, DeleteMethod3) {
  6367. auto res = cli_.Get("/person/john6");
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6370. Params params;
  6371. params.emplace("name", "john6");
  6372. params.emplace("note", "tester");
  6373. res = cli_.Post("/person", params);
  6374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6375. ASSERT_EQ(StatusCode::OK_200, res->status);
  6376. res = cli_.Get("/person/john6");
  6377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6378. ASSERT_EQ(StatusCode::OK_200, res->status);
  6379. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6380. ASSERT_EQ("tester", res->body);
  6381. Params delete_params;
  6382. delete_params.emplace("name", "john6");
  6383. Headers headers;
  6384. headers.emplace("Custom-Header", "test-value");
  6385. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6387. ASSERT_EQ(StatusCode::OK_200, res->status);
  6388. ASSERT_EQ("DELETED", res->body);
  6389. res = cli_.Get("/person/john6");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6392. }
  6393. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6394. Params params;
  6395. params.emplace("json", JSON_DATA);
  6396. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6398. ASSERT_EQ(StatusCode::OK_200, res->status);
  6399. ASSERT_EQ(JSON_DATA, res->body);
  6400. }
  6401. TEST_F(ServerTest, PostEmptyContent) {
  6402. auto res = cli_.Post("/empty", "", "text/plain");
  6403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6404. ASSERT_EQ(StatusCode::OK_200, res->status);
  6405. ASSERT_EQ("empty", res->body);
  6406. }
  6407. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6408. auto res = cli_.Post("/empty-no-content-type");
  6409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6410. ASSERT_EQ(StatusCode::OK_200, res->status);
  6411. ASSERT_EQ("empty-no-content-type", res->body);
  6412. }
  6413. TEST_F(ServerTest, PostPathOnly) {
  6414. auto res = cli_.Post("/path-only");
  6415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6416. ASSERT_EQ(StatusCode::OK_200, res->status);
  6417. ASSERT_EQ("path-only", res->body);
  6418. }
  6419. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6420. auto res = cli_.Post("/path-headers-only",
  6421. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. ASSERT_EQ(StatusCode::OK_200, res->status);
  6424. ASSERT_EQ("path-headers-only", res->body);
  6425. }
  6426. TEST_F(ServerTest, PostLarge) {
  6427. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. ASSERT_EQ(StatusCode::OK_200, res->status);
  6430. EXPECT_EQ(LARGE_DATA, res->body);
  6431. }
  6432. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6433. auto res = cli_.Put("/empty-no-content-type");
  6434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6435. ASSERT_EQ(StatusCode::OK_200, res->status);
  6436. ASSERT_EQ("empty-no-content-type", res->body);
  6437. }
  6438. TEST_F(ServerTest, GetMethodDir) {
  6439. auto res = cli_.Get("/dir/");
  6440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6441. EXPECT_EQ(StatusCode::OK_200, res->status);
  6442. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6443. auto body = R"(<html>
  6444. <head>
  6445. </head>
  6446. <body>
  6447. <a href="/dir/test.html">Test</a>
  6448. <a href="/hi">hi</a>
  6449. </body>
  6450. </html>
  6451. )";
  6452. EXPECT_EQ(body, res->body);
  6453. }
  6454. TEST_F(ServerTest, GetMethodDirTest) {
  6455. auto res = cli_.Get("/dir/test.html");
  6456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6457. EXPECT_EQ(StatusCode::OK_200, res->status);
  6458. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6459. EXPECT_EQ("test.html", res->body);
  6460. }
  6461. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6462. auto res = cli_.Get("/dir/../dir/test.html");
  6463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6464. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6465. }
  6466. TEST_F(ServerTest, GetMethodInvalidPath) {
  6467. auto res = cli_.Get("/dir/../test.html");
  6468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6470. }
  6471. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6472. auto res = cli_.Get("/../www/dir/test.html");
  6473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6474. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6475. }
  6476. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6477. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6479. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6480. }
  6481. TEST_F(ServerTest, GetMethodDirMountTest) {
  6482. auto res = cli_.Get("/mount/dir/test.html");
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. EXPECT_EQ(StatusCode::OK_200, res->status);
  6485. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6486. EXPECT_EQ("test.html", res->body);
  6487. }
  6488. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6489. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6490. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6491. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6492. }
  6493. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6494. auto res = cli_.Get("/mount/dir/../test.html");
  6495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6496. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6497. }
  6498. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6499. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6501. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6502. }
  6503. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6504. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6506. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6507. }
  6508. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6509. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6511. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6512. }
  6513. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6514. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6517. }
  6518. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6519. auto res = cli_.Get("/mount/dir");
  6520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6521. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6522. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6523. }
  6524. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6525. auto res = cli_.Get("//dir");
  6526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6527. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6528. EXPECT_FALSE(res->has_header("Location"));
  6529. }
  6530. TEST_F(ServerTest, PostMethod303) {
  6531. auto res = cli_.Post("/1", "body", "text/plain");
  6532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6533. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6534. EXPECT_EQ("/2", res->get_header_value("Location"));
  6535. }
  6536. TEST_F(ServerTest, PostMethod303Redirect) {
  6537. cli_.set_follow_location(true);
  6538. auto res = cli_.Post("/1", "body", "text/plain");
  6539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6540. EXPECT_EQ(StatusCode::OK_200, res->status);
  6541. EXPECT_EQ("redirected.", res->body);
  6542. EXPECT_EQ("/2", res->location);
  6543. }
  6544. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6545. auto res = cli_.Get("/dir/test.abcde");
  6546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6547. EXPECT_EQ(StatusCode::OK_200, res->status);
  6548. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6549. EXPECT_EQ("abcde", res->body);
  6550. }
  6551. TEST_F(ServerTest, StaticFileRange) {
  6552. auto res =
  6553. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6555. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6556. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6557. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6558. EXPECT_EQ(true, res->has_header("Content-Range"));
  6559. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6560. EXPECT_EQ(std::string("cd"), res->body);
  6561. }
  6562. TEST_F(ServerTest, StaticFileRanges) {
  6563. auto res = cli_.Get("/dir/test.abcde",
  6564. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6566. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6567. EXPECT_TRUE(
  6568. res->get_header_value("Content-Type")
  6569. .find(
  6570. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6571. 0);
  6572. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6573. }
  6574. TEST_F(ServerTest, StaticFileRangeHead) {
  6575. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6577. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6578. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6579. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6580. EXPECT_EQ(true, res->has_header("Content-Range"));
  6581. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6582. }
  6583. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6584. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6586. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6587. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6588. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6589. EXPECT_EQ(true, res->has_header("Content-Range"));
  6590. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6591. res->get_header_value("Content-Range"));
  6592. EXPECT_EQ("LAST\n", res->body);
  6593. }
  6594. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6595. auto res =
  6596. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6598. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6599. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6600. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6601. EXPECT_EQ(true, res->has_header("Content-Range"));
  6602. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6603. }
  6604. TEST_F(ServerTest, StaticFileBigFile) {
  6605. auto res = cli_.Get("/dir/1MB.txt");
  6606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6607. EXPECT_EQ(StatusCode::OK_200, res->status);
  6608. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6609. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6610. }
  6611. TEST_F(ServerTest, InvalidBaseDirMount) {
  6612. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6613. }
  6614. TEST_F(ServerTest, Binary) {
  6615. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6616. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6617. "application/octet-stream");
  6618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6619. ASSERT_EQ(StatusCode::OK_200, res->status);
  6620. ASSERT_EQ(4U, res->body.size());
  6621. res = cli_.Put("/binary", binary.data(), binary.size(),
  6622. "application/octet-stream");
  6623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6624. ASSERT_EQ(StatusCode::OK_200, res->status);
  6625. ASSERT_EQ(4U, res->body.size());
  6626. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6627. "application/octet-stream");
  6628. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6629. ASSERT_EQ(StatusCode::OK_200, res->status);
  6630. ASSERT_EQ(4U, res->body.size());
  6631. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6632. "application/octet-stream");
  6633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6634. ASSERT_EQ(StatusCode::OK_200, res->status);
  6635. ASSERT_EQ(4U, res->body.size());
  6636. }
  6637. TEST_F(ServerTest, BinaryString) {
  6638. auto binary = std::string("\x00\x01\x02\x03", 4);
  6639. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6641. ASSERT_EQ(StatusCode::OK_200, res->status);
  6642. ASSERT_EQ(4U, res->body.size());
  6643. res = cli_.Put("/binary", binary, "application/octet-stream");
  6644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6645. ASSERT_EQ(StatusCode::OK_200, res->status);
  6646. ASSERT_EQ(4U, res->body.size());
  6647. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6649. ASSERT_EQ(StatusCode::OK_200, res->status);
  6650. ASSERT_EQ(4U, res->body.size());
  6651. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6653. ASSERT_EQ(StatusCode::OK_200, res->status);
  6654. ASSERT_EQ(4U, res->body.size());
  6655. }
  6656. TEST_F(ServerTest, EmptyRequest) {
  6657. auto res = cli_.Get("");
  6658. ASSERT_TRUE(!res);
  6659. EXPECT_EQ(Error::Connection, res.error());
  6660. }
  6661. TEST_F(ServerTest, LongRequest) {
  6662. std::string request;
  6663. for (size_t i = 0; i < 545; i++) {
  6664. request += "/TooLongRequest";
  6665. }
  6666. request += "OK";
  6667. auto res = cli_.Get(request.c_str());
  6668. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6669. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6670. }
  6671. TEST_F(ServerTest, TooLongRequest) {
  6672. std::string request;
  6673. for (size_t i = 0; i < 546; i++) {
  6674. request += "/TooLongRequest";
  6675. }
  6676. request += "_NG";
  6677. auto start = std::chrono::high_resolution_clock::now();
  6678. cli_.set_keep_alive(true);
  6679. auto res = cli_.Get(request.c_str());
  6680. auto end = std::chrono::high_resolution_clock::now();
  6681. auto elapsed =
  6682. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6683. .count();
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6686. EXPECT_LE(elapsed, 1000);
  6687. EXPECT_EQ("close", res->get_header_value("Connection"));
  6688. EXPECT_FALSE(cli_.is_socket_open());
  6689. }
  6690. TEST_F(ServerTest, AlmostTooLongRequest) {
  6691. // test for #2046 - URI length check shouldn't include other content on req
  6692. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6693. // leading /, space, HTTP/1.1)
  6694. std::string request =
  6695. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6696. auto res = cli_.Get(request.c_str());
  6697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6698. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6699. }
  6700. TEST_F(ServerTest, LongHeader) {
  6701. Request req;
  6702. req.method = "GET";
  6703. req.path = "/hi";
  6704. std::string host_and_port;
  6705. host_and_port += HOST;
  6706. host_and_port += ":";
  6707. host_and_port += std::to_string(PORT);
  6708. req.headers.emplace("Host", host_and_port.c_str());
  6709. req.headers.emplace("Accept", "*/*");
  6710. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6711. req.headers.emplace(
  6712. "Header-Name",
  6713. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6714. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6715. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6716. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6717. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6718. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6719. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6720. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6721. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6722. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6723. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6724. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6725. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6726. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6727. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6728. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6729. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6730. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6731. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6732. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6733. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6734. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6741. "@@@@@@@@@@@@@@@@");
  6742. auto res = std::make_shared<Response>();
  6743. auto error = Error::Success;
  6744. auto ret = cli_.send(req, *res, error);
  6745. ASSERT_TRUE(ret);
  6746. EXPECT_EQ(StatusCode::OK_200, res->status);
  6747. }
  6748. TEST_F(ServerTest, LongQueryValue) {
  6749. auto start = std::chrono::high_resolution_clock::now();
  6750. cli_.set_keep_alive(true);
  6751. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6752. auto end = std::chrono::high_resolution_clock::now();
  6753. auto elapsed =
  6754. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6755. .count();
  6756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6757. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6758. EXPECT_LE(elapsed, 1000);
  6759. EXPECT_EQ("close", res->get_header_value("Connection"));
  6760. EXPECT_FALSE(cli_.is_socket_open());
  6761. }
  6762. TEST_F(ServerTest, TooLongQueryValue) {
  6763. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6764. ASSERT_FALSE(res);
  6765. EXPECT_EQ(Error::Read, res.error());
  6766. }
  6767. TEST_F(ServerTest, TooLongHeader) {
  6768. Request req;
  6769. req.method = "GET";
  6770. req.path = "/hi";
  6771. std::string host_and_port;
  6772. host_and_port += HOST;
  6773. host_and_port += ":";
  6774. host_and_port += std::to_string(PORT);
  6775. req.headers.emplace("Host", host_and_port.c_str());
  6776. req.headers.emplace("Accept", "*/*");
  6777. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6778. req.headers.emplace(
  6779. "Header-Name",
  6780. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6781. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6782. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6783. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6784. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6785. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6786. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6787. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6788. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6789. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6790. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6791. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6792. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6793. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6794. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6795. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6796. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6797. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6798. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6799. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6800. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6801. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6802. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6803. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6804. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6805. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6806. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6807. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6808. "@@@@@@@@@@@@@@@@@");
  6809. auto res = std::make_shared<Response>();
  6810. auto error = Error::Success;
  6811. auto ret = cli_.send(req, *res, error);
  6812. ASSERT_TRUE(ret);
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. }
  6815. TEST_F(ServerTest, HeaderCountAtLimit) {
  6816. // Test with headers just under the 100 limit
  6817. httplib::Headers headers;
  6818. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6819. // This should keep us just under the 100 header limit
  6820. for (int i = 0; i < 95; i++) {
  6821. std::string name = "X-Test-Header-" + std::to_string(i);
  6822. std::string value = "value" + std::to_string(i);
  6823. headers.emplace(name, value);
  6824. }
  6825. // This should work fine as we're under the limit
  6826. auto res = cli_.Get("/hi", headers);
  6827. EXPECT_TRUE(res);
  6828. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6829. }
  6830. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6831. // Test with many headers to exceed the 100 limit
  6832. httplib::Headers headers;
  6833. // Add 150 headers to definitely exceed the 100 limit
  6834. for (int i = 0; i < 150; i++) {
  6835. std::string name = "X-Test-Header-" + std::to_string(i);
  6836. std::string value = "value" + std::to_string(i);
  6837. headers.emplace(name, value);
  6838. }
  6839. // This should fail due to exceeding header count limit
  6840. cli_.set_keep_alive(true);
  6841. auto res = cli_.Get("/hi", headers);
  6842. // The server should respond with 400 Bad Request
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6845. EXPECT_EQ("close", res->get_header_value("Connection"));
  6846. EXPECT_FALSE(cli_.is_socket_open());
  6847. }
  6848. TEST_F(ServerTest, PercentEncoding) {
  6849. auto res = cli_.Get("/e%6edwith%");
  6850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6851. EXPECT_EQ(StatusCode::OK_200, res->status);
  6852. }
  6853. TEST_F(ServerTest, PercentEncodingUnicode) {
  6854. auto res = cli_.Get("/e%u006edwith%");
  6855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6856. EXPECT_EQ(StatusCode::OK_200, res->status);
  6857. }
  6858. TEST_F(ServerTest, InvalidPercentEncoding) {
  6859. auto res = cli_.Get("/%endwith%");
  6860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6861. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6862. }
  6863. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6864. auto res = cli_.Get("/%uendwith%");
  6865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6866. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6867. }
  6868. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6869. auto res = cli_.Get("/hello?aaa=bbb%");
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6872. }
  6873. TEST_F(ServerTest, PlusSignEncoding) {
  6874. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6876. EXPECT_EQ(StatusCode::OK_200, res->status);
  6877. EXPECT_EQ("a +b", res->body);
  6878. }
  6879. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6880. // This test simulates a potential DoS attack using many headers
  6881. // to verify our security fix prevents memory exhaustion
  6882. httplib::Headers attack_headers;
  6883. // Attempt to add many headers like an attacker would (200 headers to far
  6884. // exceed limit)
  6885. for (int i = 0; i < 200; i++) {
  6886. std::string name = "X-Attack-Header-" + std::to_string(i);
  6887. std::string value = "attack_payload_" + std::to_string(i);
  6888. attack_headers.emplace(name, value);
  6889. }
  6890. // Try to POST with excessive headers
  6891. cli_.set_keep_alive(true);
  6892. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6893. // Should either fail or return 400 Bad Request due to security limit
  6894. if (res) {
  6895. // If we get a response, it should be 400 Bad Request
  6896. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6897. EXPECT_EQ("close", res->get_header_value("Connection"));
  6898. }
  6899. EXPECT_FALSE(cli_.is_socket_open());
  6900. }
  6901. TEST_F(ServerTest, MultipartFormData) {
  6902. UploadFormDataItems items = {
  6903. {"text1", "text default", "", ""},
  6904. {"text2", "aωb", "", ""},
  6905. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6906. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6907. {"file3", "", "", "application/octet-stream"},
  6908. {"file4", "", "", " application/json tmp-string "}};
  6909. auto res = cli_.Post("/multipart", items);
  6910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6911. EXPECT_EQ(StatusCode::OK_200, res->status);
  6912. }
  6913. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6914. UploadFormDataItems items = {
  6915. {"text", "default text", "", ""},
  6916. {"multi_text1", "aaaaa", "", ""},
  6917. {"multi_text1", "bbbbb", "", ""},
  6918. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6919. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6920. "application/json"},
  6921. };
  6922. auto res = cli_.Post("/multipart/multi_file_values", items);
  6923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6924. EXPECT_EQ(StatusCode::OK_200, res->status);
  6925. }
  6926. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6927. auto res = cli_.Get("/hi");
  6928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6929. EXPECT_EQ(StatusCode::OK_200, res->status);
  6930. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6931. EXPECT_EQ("Hello World!", res->body);
  6932. }
  6933. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6934. Request req;
  6935. req.method = "POST";
  6936. req.path = "/chunked";
  6937. std::string host_and_port;
  6938. host_and_port += HOST;
  6939. host_and_port += ":";
  6940. host_and_port += std::to_string(PORT);
  6941. req.headers.emplace("Host", host_and_port.c_str());
  6942. req.headers.emplace("Accept", "*/*");
  6943. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6944. req.headers.emplace("Content-Type", "text/plain");
  6945. req.headers.emplace("Content-Length", "0");
  6946. req.headers.emplace(
  6947. "Transfer-Encoding",
  6948. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6949. // Client does not chunk, so make a chunked body manually.
  6950. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6951. auto res = std::make_shared<Response>();
  6952. auto error = Error::Success;
  6953. auto ret = cli_.send(req, *res, error);
  6954. ASSERT_TRUE(ret);
  6955. EXPECT_EQ(StatusCode::OK_200, res->status);
  6956. }
  6957. template <typename ClientT>
  6958. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6959. int expected_status) {
  6960. Request req;
  6961. req.method = "POST";
  6962. req.path = "/chunked";
  6963. std::string host_and_port;
  6964. host_and_port += HOST;
  6965. host_and_port += ":";
  6966. host_and_port += std::to_string(PORT);
  6967. req.headers.emplace("Host", host_and_port.c_str());
  6968. req.headers.emplace("Content-Length", "0");
  6969. req.headers.emplace("Transfer-Encoding", "chunked");
  6970. req.body = body;
  6971. auto res = std::make_shared<Response>();
  6972. auto error = Error::Success;
  6973. ASSERT_TRUE(cli.send(req, *res, error));
  6974. EXPECT_EQ(expected_status, res->status);
  6975. }
  6976. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6977. // rather than treat them as valid lengths.
  6978. template <typename ClientT>
  6979. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6980. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6981. }
  6982. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6983. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6984. }
  6985. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6986. expect_chunked_body_rejected(
  6987. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6988. }
  6989. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6990. // chunk-size line carries no CR, LF or other control character ahead of its
  6991. // terminator. Such a line must be refused rather than read as extension text.
  6992. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6993. expect_chunked_body_rejected(
  6994. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6995. }
  6996. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6997. expect_chunked_body_rejected(
  6998. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6999. }
  7000. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7001. expect_chunked_body_rejected(
  7002. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7003. }
  7004. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7005. // The literal stays split: a hex escape consumes every hex digit that
  7006. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7007. expect_chunked_body_rejected(
  7008. cli_, "4;a\x01"
  7009. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7010. }
  7011. // The bytes around chunk data are no payload, so they cannot ride on the
  7012. // payload limit
  7013. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7014. // Small enough that the whole request is sent before the server turns it
  7015. // down, yet past the limit by the last chunks
  7016. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7017. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7018. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7019. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7020. SCOPED_TRACE(size_line.substr(0, 2));
  7021. std::string body;
  7022. for (auto c : std::string("dechunked post body")) {
  7023. body += size_line + "\r\n" + c + "\r\n";
  7024. }
  7025. body += "0\r\n\r\n";
  7026. expect_chunked_body_rejected(cli_, body.c_str());
  7027. }
  7028. }
  7029. TEST_F(ServerTest, AcceptsChunkExtension) {
  7030. expect_chunked_body_status(cli_,
  7031. "4;name=value\r\ndech\r\n"
  7032. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7033. "0;last\r\n\r\n",
  7034. StatusCode::OK_200);
  7035. }
  7036. TEST_F(ServerTest, GetStreamed2) {
  7037. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7040. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7041. EXPECT_EQ(true, res->has_header("Content-Range"));
  7042. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7043. EXPECT_EQ(std::string("ab"), res->body);
  7044. }
  7045. TEST_F(ServerTest, GetStreamed) {
  7046. auto res = cli_.Get("/streamed");
  7047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7048. EXPECT_EQ(StatusCode::OK_200, res->status);
  7049. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7050. EXPECT_EQ(std::string("aaabbb"), res->body);
  7051. }
  7052. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7053. auto res = cli_.Get("/streamed-without-length",
  7054. Headers{make_range_header({{0, -1}})});
  7055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7056. EXPECT_EQ(StatusCode::OK_200, res->status);
  7057. EXPECT_EQ(false, res->has_header("Content-Length"));
  7058. EXPECT_EQ(false, res->has_header("Content-Range"));
  7059. EXPECT_EQ(std::string("abcdefg"), res->body);
  7060. }
  7061. TEST_F(ServerTest, GetStreamedWithRange1) {
  7062. auto res =
  7063. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7065. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7066. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7067. EXPECT_EQ(true, res->has_header("Content-Range"));
  7068. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7069. EXPECT_EQ(std::string("def"), res->body);
  7070. }
  7071. TEST_F(ServerTest, GetStreamedWithRange2) {
  7072. auto res =
  7073. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7075. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7076. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7077. EXPECT_EQ(true, res->has_header("Content-Range"));
  7078. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7079. EXPECT_EQ(std::string("bcdefg"), res->body);
  7080. }
  7081. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7082. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7084. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7085. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7086. EXPECT_EQ(true, res->has_header("Content-Range"));
  7087. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7088. EXPECT_EQ(std::string("efg"), res->body);
  7089. }
  7090. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7091. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7092. // the entire representation.
  7093. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7094. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7097. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7098. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7099. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7100. }
  7101. }
  7102. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7103. auto res =
  7104. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7106. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7107. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7108. EXPECT_EQ(false, res->has_header("Content-Range"));
  7109. EXPECT_EQ(0U, res->body.size());
  7110. }
  7111. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7112. // Only a 206 is served as a partial representation. Under any other status
  7113. // `apply_ranges()` reported the full content length, so the body must match
  7114. // that header, and the content provider must never be asked for an offset
  7115. // outside the representation.
  7116. auto check = [&](int status, const char *range) {
  7117. auto path =
  7118. std::string("/streamed-with-range?status=") + std::to_string(status);
  7119. auto ctx = path + " Range: " + range;
  7120. auto res = cli_.Get(path, Headers{{"Range", range}});
  7121. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7122. EXPECT_EQ(status, res->status) << ctx;
  7123. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7124. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7125. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7126. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7127. };
  7128. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7129. check(403, "bytes=3-5");
  7130. // The offset is far past the representation.
  7131. check(403, "bytes=100000-100200");
  7132. // `first_pos` is still -1 here, and the bounds asserts in
  7133. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7134. check(403, "bytes=-3");
  7135. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7136. // multipart branch would have written one that is empty.
  7137. check(403, "bytes=1-2, 4-5");
  7138. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7139. // covers the whole representation.
  7140. check(200, "bytes=3-5");
  7141. check(200, "bytes=1-2, 4-5");
  7142. }
  7143. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7144. auto res =
  7145. cli_.Get("/streamed-with-range",
  7146. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7147. "92233720368547758079223372036854775807"}});
  7148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7149. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7150. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7151. EXPECT_EQ(false, res->has_header("Content-Range"));
  7152. EXPECT_EQ(0U, res->body.size());
  7153. }
  7154. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7155. auto res = cli_.Get(
  7156. "/with-range",
  7157. Headers{{"Range",
  7158. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7159. {"Accept-Encoding", ""}});
  7160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7161. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7162. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7163. EXPECT_EQ(true, res->has_header("Content-Range"));
  7164. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7165. EXPECT_EQ(std::string("abcdefg"), res->body);
  7166. }
  7167. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7168. auto res = cli_.Get("/with-range", Headers{
  7169. {"Range", "bytes=0-"},
  7170. {"Accept-Encoding", ""},
  7171. });
  7172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7173. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7174. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7175. EXPECT_EQ(true, res->has_header("Content-Range"));
  7176. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7177. EXPECT_EQ(std::string("abcdefg"), res->body);
  7178. }
  7179. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7180. auto res = cli_.Get("/streamed-with-range",
  7181. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7183. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7184. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7185. EXPECT_EQ(false, res->has_header("Content-Range"));
  7186. EXPECT_EQ(267U, res->body.size());
  7187. // Check that both range contents are present
  7188. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7189. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7190. // Check that Content-Range headers are present for both ranges
  7191. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7192. std::string::npos);
  7193. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7194. std::string::npos);
  7195. }
  7196. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7197. Ranges ranges;
  7198. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7199. ranges.emplace_back(0, -1);
  7200. }
  7201. auto res = cli_.Get("/streamed-with-range?error",
  7202. Headers{{make_range_header(ranges)}});
  7203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7204. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7205. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7206. EXPECT_EQ(false, res->has_header("Content-Range"));
  7207. EXPECT_EQ(0U, res->body.size());
  7208. }
  7209. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7210. auto res = cli_.Get("/streamed-with-range",
  7211. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7213. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7214. EXPECT_EQ(5U, res->body.size());
  7215. // Check that overlapping ranges are coalesced into a single range
  7216. EXPECT_EQ("bcdef", res->body);
  7217. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7218. // Should be single range, not multipart
  7219. EXPECT_TRUE(res->has_header("Content-Range"));
  7220. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7221. }
  7222. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7223. auto res = cli_.Get("/streamed-with-range",
  7224. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7227. EXPECT_EQ(268U, res->body.size());
  7228. // Check that both range contents are present
  7229. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7230. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7231. // Check that Content-Range headers are present for both ranges
  7232. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7233. std::string::npos);
  7234. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7235. std::string::npos);
  7236. }
  7237. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7238. auto res = cli_.Get("/streamed-with-range",
  7239. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7241. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7242. EXPECT_EQ(269U, res->body.size());
  7243. // Check that both duplicate range contents are present
  7244. size_t first_abc = res->body.find("abc\r\n");
  7245. EXPECT_TRUE(first_abc != std::string::npos);
  7246. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7247. EXPECT_TRUE(second_abc != std::string::npos);
  7248. // Check that Content-Range headers are present for both ranges
  7249. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7250. EXPECT_TRUE(first_range != std::string::npos);
  7251. size_t second_range =
  7252. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7253. EXPECT_TRUE(second_range != std::string::npos);
  7254. }
  7255. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7256. auto res =
  7257. cli_.Get("/streamed-with-range?error",
  7258. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7260. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7261. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7262. EXPECT_EQ(false, res->has_header("Content-Range"));
  7263. EXPECT_EQ(0U, res->body.size());
  7264. }
  7265. TEST_F(ServerTest, GetStreamedEndless) {
  7266. uint64_t offset = 0;
  7267. auto res = cli_.Get("/streamed-cancel",
  7268. [&](const char * /*data*/, uint64_t data_length) {
  7269. if (offset < 100) {
  7270. offset += data_length;
  7271. return true;
  7272. }
  7273. return false;
  7274. });
  7275. ASSERT_TRUE(!res);
  7276. EXPECT_EQ(Error::Canceled, res.error());
  7277. }
  7278. TEST_F(ServerTest, ClientStop) {
  7279. std::atomic_size_t count{4};
  7280. std::vector<std::thread> threads;
  7281. for (auto i = count.load(); i != 0; --i) {
  7282. threads.emplace_back([&]() {
  7283. auto res = cli_.Get("/streamed-cancel",
  7284. [&](const char *, uint64_t) { return true; });
  7285. --count;
  7286. ASSERT_TRUE(!res);
  7287. EXPECT_TRUE(res.error() == Error::Canceled ||
  7288. res.error() == Error::Read || res.error() == Error::Write);
  7289. });
  7290. }
  7291. std::this_thread::sleep_for(std::chrono::seconds(2));
  7292. while (count != 0) {
  7293. cli_.stop();
  7294. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7295. }
  7296. for (auto &t : threads) {
  7297. t.join();
  7298. }
  7299. }
  7300. TEST_F(ServerTest, GetWithRange1) {
  7301. auto res = cli_.Get("/with-range", Headers{
  7302. make_range_header({{3, 5}}),
  7303. {"Accept-Encoding", ""},
  7304. });
  7305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7306. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7307. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7308. EXPECT_EQ(true, res->has_header("Content-Range"));
  7309. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7310. EXPECT_EQ(std::string("def"), res->body);
  7311. }
  7312. TEST_F(ServerTest, GetWithRange2) {
  7313. auto res = cli_.Get("/with-range", Headers{
  7314. make_range_header({{1, -1}}),
  7315. {"Accept-Encoding", ""},
  7316. });
  7317. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7318. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7319. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7320. EXPECT_EQ(true, res->has_header("Content-Range"));
  7321. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7322. EXPECT_EQ(std::string("bcdefg"), res->body);
  7323. }
  7324. TEST_F(ServerTest, GetWithRange3) {
  7325. auto res = cli_.Get("/with-range", Headers{
  7326. make_range_header({{0, 0}}),
  7327. {"Accept-Encoding", ""},
  7328. });
  7329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7330. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7331. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7332. EXPECT_EQ(true, res->has_header("Content-Range"));
  7333. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7334. EXPECT_EQ(std::string("a"), res->body);
  7335. }
  7336. TEST_F(ServerTest, GetWithRange4) {
  7337. auto res = cli_.Get("/with-range", Headers{
  7338. make_range_header({{-1, 2}}),
  7339. {"Accept-Encoding", ""},
  7340. });
  7341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7342. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7343. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7344. EXPECT_EQ(true, res->has_header("Content-Range"));
  7345. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7346. EXPECT_EQ(std::string("fg"), res->body);
  7347. }
  7348. TEST_F(ServerTest, GetWithRange5) {
  7349. auto res = cli_.Get("/with-range", Headers{
  7350. make_range_header({{0, 5}}),
  7351. {"Accept-Encoding", ""},
  7352. });
  7353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7354. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7355. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7356. EXPECT_EQ(true, res->has_header("Content-Range"));
  7357. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7358. EXPECT_EQ(std::string("abcdef"), res->body);
  7359. }
  7360. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7361. auto res =
  7362. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7364. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7365. }
  7366. TEST_F(ServerTest, GetWithRangeMultipart) {
  7367. auto res =
  7368. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7370. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7371. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7372. EXPECT_EQ(false, res->has_header("Content-Range"));
  7373. EXPECT_EQ(267U, res->body.size());
  7374. }
  7375. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7376. auto res = cli_.Get("/with-range",
  7377. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7379. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7380. }
  7381. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7382. auto res = cli_.Get("/with-range-customized-response",
  7383. Headers{{make_range_header({{1, 2}})}});
  7384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7385. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7386. EXPECT_EQ(true, res->has_header("Content-Length"));
  7387. EXPECT_EQ(false, res->has_header("Content-Range"));
  7388. EXPECT_EQ(JSON_DATA, res->body);
  7389. }
  7390. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7391. auto res = cli_.Get("/with-range-customized-response",
  7392. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7394. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7395. EXPECT_EQ(true, res->has_header("Content-Length"));
  7396. EXPECT_EQ(false, res->has_header("Content-Range"));
  7397. EXPECT_EQ(JSON_DATA, res->body);
  7398. }
  7399. TEST_F(ServerTest, Issue1772) {
  7400. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7402. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7403. }
  7404. TEST_F(ServerTest, Issue609) {
  7405. auto res = cli_.Delete("/issue609");
  7406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7407. EXPECT_EQ(StatusCode::OK_200, res->status);
  7408. EXPECT_EQ(std::string("ok"), res->body);
  7409. }
  7410. TEST_F(ServerTest, GetStreamedChunked) {
  7411. auto res = cli_.Get("/streamed-chunked");
  7412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7413. EXPECT_EQ(StatusCode::OK_200, res->status);
  7414. EXPECT_EQ(std::string("123456789"), res->body);
  7415. }
  7416. TEST_F(ServerTest, GetStreamedChunked2) {
  7417. auto res = cli_.Get("/streamed-chunked2");
  7418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7419. EXPECT_EQ(StatusCode::OK_200, res->status);
  7420. EXPECT_EQ(std::string("123456789"), res->body);
  7421. }
  7422. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7423. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7425. EXPECT_EQ(StatusCode::OK_200, res->status);
  7426. EXPECT_EQ(std::string("123456789"), res->body);
  7427. EXPECT_TRUE(res->has_header("Trailer"));
  7428. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7429. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7430. // Trailers are now stored separately from headers (security fix)
  7431. EXPECT_EQ(2U, res->trailers.size());
  7432. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7433. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7434. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7435. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7436. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7437. // Verify trailers are NOT in headers (security verification)
  7438. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7439. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7440. }
  7441. TEST_F(ServerTest, LargeChunkedPost) {
  7442. Request req;
  7443. req.method = "POST";
  7444. req.path = "/large-chunked";
  7445. std::string host_and_port;
  7446. host_and_port += HOST;
  7447. host_and_port += ":";
  7448. host_and_port += std::to_string(PORT);
  7449. req.headers.emplace("Host", host_and_port.c_str());
  7450. req.headers.emplace("Accept", "*/*");
  7451. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7452. req.headers.emplace("Content-Type", "text/plain");
  7453. req.headers.emplace("Content-Length", "0");
  7454. req.headers.emplace("Transfer-Encoding", "chunked");
  7455. std::string long_string(30 * 1024u, 'a');
  7456. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7457. // Attempt to make a large enough post to exceed OS buffers, to test that
  7458. // the server handles short reads if the full chunk data isn't available.
  7459. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7460. auto res = std::make_shared<Response>();
  7461. auto error = Error::Success;
  7462. auto ret = cli_.send(req, *res, error);
  7463. ASSERT_TRUE(ret);
  7464. EXPECT_EQ(StatusCode::OK_200, res->status);
  7465. }
  7466. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7467. auto res = cli_.Get("/remote_addr");
  7468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7469. EXPECT_EQ(StatusCode::OK_200, res->status);
  7470. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7471. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7472. }
  7473. TEST_F(ServerTest, GetMethodLocalAddr) {
  7474. auto res = cli_.Get("/local_addr");
  7475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7476. EXPECT_EQ(StatusCode::OK_200, res->status);
  7477. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7478. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7479. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7480. }
  7481. TEST_F(ServerTest, HTTPResponseSplitting) {
  7482. auto res = cli_.Get("/http_response_splitting");
  7483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7484. EXPECT_EQ(StatusCode::OK_200, res->status);
  7485. }
  7486. TEST_F(ServerTest, SlowRequest) {
  7487. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7488. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7489. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7490. }
  7491. #if 0
  7492. TEST_F(ServerTest, SlowPost) {
  7493. char buffer[64 * 1024];
  7494. memset(buffer, 0x42, sizeof(buffer));
  7495. auto res = cli_.Post(
  7496. "/slowpost", 64 * 1024 * 1024,
  7497. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7498. auto ret = sink.write(buffer, sizeof(buffer));
  7499. EXPECT_TRUE(ret);
  7500. return true;
  7501. },
  7502. "text/plain");
  7503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7504. EXPECT_EQ(StatusCode::OK_200, res->status);
  7505. }
  7506. TEST_F(ServerTest, SlowPostFail) {
  7507. char buffer[64 * 1024];
  7508. memset(buffer, 0x42, sizeof(buffer));
  7509. cli_.set_write_timeout(std::chrono::seconds(0));
  7510. auto res = cli_.Post(
  7511. "/slowpost", 64 * 1024 * 1024,
  7512. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7513. sink.write(buffer, sizeof(buffer));
  7514. return true;
  7515. },
  7516. "text/plain");
  7517. ASSERT_TRUE(!res);
  7518. EXPECT_EQ(Error::Write, res.error());
  7519. }
  7520. #endif
  7521. TEST_F(ServerTest, Put) {
  7522. auto res = cli_.Put("/put", "PUT", "text/plain");
  7523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7524. EXPECT_EQ(StatusCode::OK_200, res->status);
  7525. EXPECT_EQ("PUT", res->body);
  7526. }
  7527. TEST_F(ServerTest, PutWithContentProvider) {
  7528. auto res = cli_.Put(
  7529. "/put", 3,
  7530. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7531. sink.os << "PUT";
  7532. return true;
  7533. },
  7534. "text/plain");
  7535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7536. EXPECT_EQ(StatusCode::OK_200, res->status);
  7537. EXPECT_EQ("PUT", res->body);
  7538. }
  7539. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7540. auto res = cli_.Post(
  7541. "/post", 42,
  7542. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7543. return false;
  7544. },
  7545. "text/plain");
  7546. ASSERT_TRUE(!res);
  7547. EXPECT_EQ(Error::Canceled, res.error());
  7548. }
  7549. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7550. auto res = cli_.Put(
  7551. "/put",
  7552. [](size_t /*offset*/, DataSink &sink) {
  7553. sink.os << "PUT";
  7554. sink.done();
  7555. return true;
  7556. },
  7557. "text/plain");
  7558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7559. EXPECT_EQ(StatusCode::OK_200, res->status);
  7560. EXPECT_EQ("PUT", res->body);
  7561. }
  7562. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7563. auto res = cli_.Post(
  7564. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7565. "text/plain");
  7566. ASSERT_TRUE(!res);
  7567. EXPECT_EQ(Error::Canceled, res.error());
  7568. }
  7569. TEST_F(ServerTest, PostLoopBack) {
  7570. std::string body;
  7571. auto res = cli_.Post(
  7572. "/post-loopback", 9,
  7573. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7574. EXPECT_EQ(9u, length);
  7575. sink.write("123", 3);
  7576. sink.write("456", 3);
  7577. sink.write("789", 3);
  7578. return true;
  7579. },
  7580. "text/plain",
  7581. [&body](const char *data, size_t data_length) {
  7582. body.append(data, data_length);
  7583. return true;
  7584. });
  7585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7586. EXPECT_EQ(StatusCode::OK_200, res->status);
  7587. EXPECT_EQ("123456789", body);
  7588. }
  7589. TEST_F(ServerTest, PutLoopBack) {
  7590. std::string body;
  7591. auto res = cli_.Put(
  7592. "/put-loopback", 9,
  7593. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7594. EXPECT_EQ(9u, length);
  7595. sink.write("123", 3);
  7596. sink.write("456", 3);
  7597. sink.write("789", 3);
  7598. return true;
  7599. },
  7600. "text/plain",
  7601. [&body](const char *data, size_t data_length) {
  7602. body.append(data, data_length);
  7603. return true;
  7604. });
  7605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7606. EXPECT_EQ(StatusCode::OK_200, res->status);
  7607. EXPECT_EQ("123456789", body);
  7608. }
  7609. TEST_F(ServerTest, PatchLoopBack) {
  7610. std::string body;
  7611. auto res = cli_.Patch(
  7612. "/patch-loopback", 9,
  7613. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7614. EXPECT_EQ(9u, length);
  7615. sink.write("123", 3);
  7616. sink.write("456", 3);
  7617. sink.write("789", 3);
  7618. return true;
  7619. },
  7620. "text/plain",
  7621. [&body](const char *data, size_t data_length) {
  7622. body.append(data, data_length);
  7623. return true;
  7624. });
  7625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7626. EXPECT_EQ(StatusCode::OK_200, res->status);
  7627. EXPECT_EQ("123456789", body);
  7628. }
  7629. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7630. std::string body;
  7631. auto res = cli_.Post(
  7632. "/post-loopback",
  7633. [](size_t /*offset*/, DataSink &sink) {
  7634. sink.write("123", 3);
  7635. sink.write("456", 3);
  7636. sink.write("789", 3);
  7637. sink.done();
  7638. return true;
  7639. },
  7640. "text/plain",
  7641. [&body](const char *data, size_t data_length) {
  7642. body.append(data, data_length);
  7643. return true;
  7644. });
  7645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7646. EXPECT_EQ(StatusCode::OK_200, res->status);
  7647. EXPECT_EQ("123456789", body);
  7648. }
  7649. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7650. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7651. cli_.set_compress(true);
  7652. auto res = cli_.Put(
  7653. "/put", 3,
  7654. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7655. sink.os << "PUT";
  7656. return true;
  7657. },
  7658. "text/plain");
  7659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7660. EXPECT_EQ(StatusCode::OK_200, res->status);
  7661. EXPECT_EQ("PUT", res->body);
  7662. }
  7663. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7664. cli_.set_compress(true);
  7665. auto res = cli_.Post(
  7666. "/post", 42,
  7667. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7668. return false;
  7669. },
  7670. "text/plain");
  7671. ASSERT_TRUE(!res);
  7672. EXPECT_EQ(Error::Canceled, res.error());
  7673. }
  7674. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7675. cli_.set_compress(true);
  7676. auto res = cli_.Put(
  7677. "/put",
  7678. [](size_t /*offset*/, DataSink &sink) {
  7679. sink.os << "PUT";
  7680. sink.done();
  7681. return true;
  7682. },
  7683. "text/plain");
  7684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7685. EXPECT_EQ(StatusCode::OK_200, res->status);
  7686. EXPECT_EQ("PUT", res->body);
  7687. }
  7688. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7689. cli_.set_compress(true);
  7690. auto res = cli_.Post(
  7691. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7692. "text/plain");
  7693. ASSERT_TRUE(!res);
  7694. EXPECT_EQ(Error::Canceled, res.error());
  7695. }
  7696. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7697. cli_.set_compress(true);
  7698. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7700. EXPECT_EQ(StatusCode::OK_200, res->status);
  7701. EXPECT_EQ(LARGE_DATA, res->body);
  7702. }
  7703. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7704. #ifdef CPPHTTPLIB_SSL_ENABLED
  7705. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7706. Client cli(s.c_str());
  7707. cli.enable_server_certificate_verification(false);
  7708. #else
  7709. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7710. Client cli(s.c_str());
  7711. #endif
  7712. cli.set_compress(true);
  7713. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7715. EXPECT_EQ(StatusCode::OK_200, res->status);
  7716. EXPECT_EQ(LARGE_DATA, res->body);
  7717. // The compressed size should be less than a 10th of the original. May vary
  7718. // depending on the zlib library.
  7719. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7720. static_cast<uint64_t>(10 * 1024 * 1024));
  7721. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7722. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7723. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7724. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7725. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7726. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7727. #endif
  7728. }
  7729. TEST_F(ServerTest, PutContentWithDeflate) {
  7730. cli_.set_compress(false);
  7731. Headers headers;
  7732. headers.emplace("Content-Encoding", "deflate");
  7733. // PUT in deflate format:
  7734. auto res = cli_.Put("/put", headers,
  7735. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7737. EXPECT_EQ(StatusCode::OK_200, res->status);
  7738. EXPECT_EQ("PUT", res->body);
  7739. }
  7740. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7741. Headers headers;
  7742. headers.emplace("Accept-Encoding", "gzip, deflate");
  7743. auto res = cli_.Get("/streamed-chunked", headers);
  7744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7745. EXPECT_EQ(StatusCode::OK_200, res->status);
  7746. EXPECT_EQ(std::string("123456789"), res->body);
  7747. }
  7748. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7749. Headers headers;
  7750. headers.emplace("Accept-Encoding", "gzip, deflate");
  7751. auto res = cli_.Get("/streamed-chunked2", headers);
  7752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7753. EXPECT_EQ(StatusCode::OK_200, res->status);
  7754. EXPECT_EQ(std::string("123456789"), res->body);
  7755. }
  7756. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7757. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7759. EXPECT_EQ(StatusCode::OK_200, res->status);
  7760. }
  7761. TEST(GzipDecompressor, ChunkedDecompression) {
  7762. std::string data;
  7763. for (size_t i = 0; i < 32 * 1024; ++i) {
  7764. data.push_back(static_cast<char>('a' + i % 26));
  7765. }
  7766. std::string compressed_data;
  7767. {
  7768. httplib::detail::gzip_compressor compressor;
  7769. bool result = compressor.compress(
  7770. data.data(), data.size(),
  7771. /*last=*/true,
  7772. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7773. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7774. compressed_data_size);
  7775. return true;
  7776. });
  7777. ASSERT_TRUE(result);
  7778. }
  7779. std::string decompressed_data;
  7780. {
  7781. httplib::detail::gzip_decompressor decompressor;
  7782. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7783. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7784. size_t chunk_size = 130;
  7785. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7786. chunk_begin += chunk_size) {
  7787. size_t current_chunk_size =
  7788. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7789. bool result = decompressor.decompress(
  7790. compressed_data.data() + chunk_begin, current_chunk_size,
  7791. [&](const char *decompressed_data_chunk,
  7792. size_t decompressed_data_chunk_size) {
  7793. decompressed_data.insert(decompressed_data.size(),
  7794. decompressed_data_chunk,
  7795. decompressed_data_chunk_size);
  7796. return true;
  7797. });
  7798. ASSERT_TRUE(result);
  7799. }
  7800. }
  7801. ASSERT_EQ(data, decompressed_data);
  7802. }
  7803. TEST(GzipDecompressor, DeflateDecompression) {
  7804. std::string original_text = "Raw deflate without gzip";
  7805. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7806. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7807. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7808. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7809. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7810. std::string decompressed_data;
  7811. {
  7812. httplib::detail::gzip_decompressor decompressor;
  7813. bool result = decompressor.decompress(
  7814. compressed_data.data(), compressed_data.size(),
  7815. [&](const char *decompressed_data_chunk,
  7816. size_t decompressed_data_chunk_size) {
  7817. decompressed_data.insert(decompressed_data.size(),
  7818. decompressed_data_chunk,
  7819. decompressed_data_chunk_size);
  7820. return true;
  7821. });
  7822. ASSERT_TRUE(result);
  7823. }
  7824. ASSERT_EQ(original_text, decompressed_data);
  7825. }
  7826. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7827. std::string original_text = "Raw deflate without gzip";
  7828. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7829. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7830. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7831. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7832. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7833. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7834. std::string decompressed_data;
  7835. {
  7836. httplib::detail::gzip_decompressor decompressor;
  7837. bool result = decompressor.decompress(
  7838. compressed_data.data(), compressed_data.size(),
  7839. [&](const char *decompressed_data_chunk,
  7840. size_t decompressed_data_chunk_size) {
  7841. decompressed_data.insert(decompressed_data.size(),
  7842. decompressed_data_chunk,
  7843. decompressed_data_chunk_size);
  7844. return true;
  7845. });
  7846. ASSERT_TRUE(result);
  7847. }
  7848. ASSERT_EQ(original_text, decompressed_data);
  7849. }
  7850. #endif
  7851. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7852. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7853. Headers headers;
  7854. headers.emplace("Accept-Encoding", "br");
  7855. auto res = cli_.Get("/streamed-chunked", headers);
  7856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7857. EXPECT_EQ(StatusCode::OK_200, res->status);
  7858. EXPECT_EQ(std::string("123456789"), res->body);
  7859. }
  7860. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7861. Headers headers;
  7862. headers.emplace("Accept-Encoding", "br");
  7863. auto res = cli_.Get("/streamed-chunked2", headers);
  7864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7865. EXPECT_EQ(StatusCode::OK_200, res->status);
  7866. EXPECT_EQ(std::string("123456789"), res->body);
  7867. }
  7868. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7869. cli_.set_compress(true);
  7870. auto res = cli_.Put(
  7871. "/put", 3,
  7872. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7873. sink.os << "PUT";
  7874. return true;
  7875. },
  7876. "text/plain");
  7877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7878. EXPECT_EQ(StatusCode::OK_200, res->status);
  7879. EXPECT_EQ("PUT", res->body);
  7880. }
  7881. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7882. cli_.set_compress(true);
  7883. auto res = cli_.Put(
  7884. "/put",
  7885. [](size_t /*offset*/, DataSink &sink) {
  7886. sink.os << "PUT";
  7887. sink.done();
  7888. return true;
  7889. },
  7890. "text/plain");
  7891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7892. EXPECT_EQ(StatusCode::OK_200, res->status);
  7893. EXPECT_EQ("PUT", res->body);
  7894. }
  7895. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7896. cli_.set_compress(true);
  7897. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7899. EXPECT_EQ(StatusCode::OK_200, res->status);
  7900. EXPECT_EQ(LARGE_DATA, res->body);
  7901. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7902. }
  7903. #endif
  7904. TEST_F(ServerTest, Patch) {
  7905. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7907. EXPECT_EQ(StatusCode::OK_200, res->status);
  7908. EXPECT_EQ("PATCH", res->body);
  7909. }
  7910. TEST_F(ServerTest, Delete) {
  7911. auto res = cli_.Delete("/delete");
  7912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7913. EXPECT_EQ(StatusCode::OK_200, res->status);
  7914. EXPECT_EQ("DELETE", res->body);
  7915. }
  7916. TEST_F(ServerTest, DeleteContentReceiver) {
  7917. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7919. EXPECT_EQ(StatusCode::OK_200, res->status);
  7920. EXPECT_EQ("content", res->body);
  7921. }
  7922. TEST_F(ServerTest, Options) {
  7923. auto res = cli_.Options("*");
  7924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7925. EXPECT_EQ(StatusCode::OK_200, res->status);
  7926. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7927. EXPECT_TRUE(res->body.empty());
  7928. }
  7929. TEST_F(ServerTest, URL) {
  7930. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7932. EXPECT_EQ(StatusCode::OK_200, res->status);
  7933. }
  7934. TEST_F(ServerTest, ArrayParam) {
  7935. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7937. EXPECT_EQ(StatusCode::OK_200, res->status);
  7938. }
  7939. TEST_F(ServerTest, ArrayParamValues) {
  7940. auto res =
  7941. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7943. EXPECT_EQ(StatusCode::OK_200, res->status);
  7944. }
  7945. TEST_F(ServerTest, NoMultipleHeaders) {
  7946. Headers headers = {{"Content-Length", "5"}};
  7947. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7948. "text/plain");
  7949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7950. EXPECT_EQ(StatusCode::OK_200, res->status);
  7951. }
  7952. TEST_F(ServerTest, PostContentReceiver) {
  7953. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7955. ASSERT_EQ(StatusCode::OK_200, res->status);
  7956. ASSERT_EQ("content", res->body);
  7957. }
  7958. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7959. UploadFormDataItems items = {
  7960. {"text1", "text default", "", ""},
  7961. {"text2", "aωb", "", ""},
  7962. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7963. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7964. {"file3", "", "", "application/octet-stream"},
  7965. };
  7966. auto res = cli_.Post("/content_receiver", items);
  7967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7968. EXPECT_EQ(StatusCode::OK_200, res->status);
  7969. }
  7970. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7971. UploadFormDataItems items = {
  7972. {"text1", "text default", "", ""},
  7973. {"text2", "aωb", "", ""},
  7974. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7975. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7976. {"file3", "", "", "application/octet-stream"},
  7977. };
  7978. auto boundary = std::string("+++++");
  7979. std::string body;
  7980. for (const auto &item : items) {
  7981. body += "--" + boundary + "\r\n";
  7982. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7983. if (!item.filename.empty()) {
  7984. body += "; filename=\"" + item.filename + "\"";
  7985. }
  7986. body += "\r\n";
  7987. if (!item.content_type.empty()) {
  7988. body += "Content-Type: " + item.content_type + "\r\n";
  7989. }
  7990. body += "\r\n";
  7991. body += item.content + "\r\n";
  7992. }
  7993. body += "--" + boundary + "--\r\n";
  7994. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7995. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7997. EXPECT_EQ(StatusCode::OK_200, res->status);
  7998. }
  7999. TEST(MultipartFormDataTest, FieldEscaping) {
  8000. Server svr;
  8001. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8002. const ContentReader &content_reader) {
  8003. ASSERT_TRUE(req.is_multipart_form_data());
  8004. std::vector<FormData> received;
  8005. content_reader(
  8006. [&](const FormData &file) {
  8007. received.push_back(file);
  8008. return true;
  8009. },
  8010. [&](const char *data, size_t data_length) {
  8011. received.back().content.append(data, data_length);
  8012. return true;
  8013. });
  8014. // '"', CR and LF in names and filenames are escaped following the
  8015. // WHATWG HTML standard, so each part still parses as a single part
  8016. // with no injected headers. Content types get CR/LF escaped too,
  8017. // while '"' (legal there, e.g. quoted charset) is preserved.
  8018. ASSERT_EQ(4U, received.size());
  8019. EXPECT_EQ("na%22me", received[0].name);
  8020. EXPECT_EQ("quoted name", received[0].content);
  8021. EXPECT_EQ("file", received[1].name);
  8022. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8023. received[1].filename);
  8024. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8025. EXPECT_EQ("injected", received[1].content);
  8026. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8027. EXPECT_EQ("my%22file.txt", received[2].filename);
  8028. EXPECT_EQ("cr lf name", received[2].content);
  8029. EXPECT_EQ("typed", received[3].name);
  8030. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8031. received[3].content_type);
  8032. EXPECT_EQ("typed content", received[3].content);
  8033. });
  8034. auto port = svr.bind_to_any_port("localhost");
  8035. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8036. auto se = detail::scope_exit([&] {
  8037. svr.stop();
  8038. t.join();
  8039. ASSERT_FALSE(svr.is_running());
  8040. });
  8041. svr.wait_until_ready();
  8042. Client cli("localhost", port);
  8043. UploadFormDataItems items = {
  8044. {"na\"me", "quoted name", "", ""},
  8045. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8046. "application/octet-stream"},
  8047. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8048. {"typed", "typed content", "",
  8049. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8050. };
  8051. auto res = cli.Post("/post", items);
  8052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8053. EXPECT_EQ(StatusCode::OK_200, res->status);
  8054. }
  8055. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8056. const UploadFormDataItems items = {
  8057. {"name1", "Content 1", "", ""},
  8058. {"name2", "Content 2", "file2.txt", "text/plain"},
  8059. };
  8060. Server svr;
  8061. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8062. const ContentReader &content_reader) {
  8063. ASSERT_TRUE(req.is_multipart_form_data());
  8064. std::vector<FormData> received;
  8065. content_reader(
  8066. [&](const FormData &file) {
  8067. received.push_back(file);
  8068. return true;
  8069. },
  8070. [&](const char *data, size_t data_length) {
  8071. received.back().content.append(data, data_length);
  8072. return true;
  8073. });
  8074. ASSERT_EQ(2U, received.size());
  8075. EXPECT_EQ("name1", received[0].name);
  8076. EXPECT_EQ("Content 1", received[0].content);
  8077. EXPECT_EQ("name2", received[1].name);
  8078. EXPECT_EQ("Content 2", received[1].content);
  8079. EXPECT_EQ("file2.txt", received[1].filename);
  8080. EXPECT_EQ("text/plain", received[1].content_type);
  8081. });
  8082. auto port = svr.bind_to_any_port("localhost");
  8083. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8084. auto se = detail::scope_exit([&] {
  8085. svr.stop();
  8086. t.join();
  8087. ASSERT_FALSE(svr.is_running());
  8088. });
  8089. svr.wait_until_ready();
  8090. Client cli("localhost", port);
  8091. // Whole-body serialization with a generated boundary
  8092. {
  8093. MultipartFormDataWriter writer;
  8094. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8095. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8096. writer.content_type());
  8097. auto body = writer.serialize(items);
  8098. EXPECT_EQ(body.size(), writer.content_length(items));
  8099. auto res = cli.Post("/post", body, writer.content_type());
  8100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8101. EXPECT_EQ(StatusCode::OK_200, res->status);
  8102. }
  8103. // Per-part framing with a custom boundary via a content provider
  8104. {
  8105. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8106. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8107. MultipartFormDataWriter writer("custom-boundary_123");
  8108. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8109. std::string body;
  8110. for (const auto &item : items) {
  8111. body += writer.item_begin(item);
  8112. body += item.content;
  8113. body += MultipartFormDataWriter::item_end();
  8114. }
  8115. body += writer.finish();
  8116. EXPECT_EQ(body.size(), writer.content_length(items));
  8117. auto res = cli.Post(
  8118. "/post", body.size(),
  8119. [&](size_t offset, size_t length, DataSink &sink) {
  8120. sink.write(body.data() + offset, length);
  8121. return true;
  8122. },
  8123. writer.content_type());
  8124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8125. EXPECT_EQ(StatusCode::OK_200, res->status);
  8126. }
  8127. }
  8128. TEST_F(ServerTest, PostContentReceiverGzip) {
  8129. cli_.set_compress(true);
  8130. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8132. ASSERT_EQ(StatusCode::OK_200, res->status);
  8133. ASSERT_EQ("content", res->body);
  8134. }
  8135. TEST_F(ServerTest, PutContentReceiver) {
  8136. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8138. ASSERT_EQ(StatusCode::OK_200, res->status);
  8139. ASSERT_EQ("content", res->body);
  8140. }
  8141. TEST_F(ServerTest, PatchContentReceiver) {
  8142. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. ASSERT_EQ(StatusCode::OK_200, res->status);
  8145. ASSERT_EQ("content", res->body);
  8146. }
  8147. template <typename ClientType>
  8148. void TestWithHeadersAndContentReceiver(
  8149. ClientType &cli,
  8150. std::function<Result(ClientType &, const std::string &, const Headers &,
  8151. const std::string &, const std::string &,
  8152. ContentReceiver, DownloadProgress)>
  8153. request_func) {
  8154. Headers headers;
  8155. headers.emplace("X-Custom-Header", "test-value");
  8156. std::string received_body;
  8157. auto res = request_func(
  8158. cli, "/content_receiver", headers, "content", "application/json",
  8159. [&](const char *data, size_t data_length) {
  8160. received_body.append(data, data_length);
  8161. return true;
  8162. },
  8163. nullptr);
  8164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8165. EXPECT_EQ(StatusCode::OK_200, res->status);
  8166. EXPECT_EQ("content", received_body);
  8167. }
  8168. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8169. #ifdef CPPHTTPLIB_SSL_ENABLED
  8170. using ClientT = SSLClient;
  8171. #else
  8172. using ClientT = Client;
  8173. #endif
  8174. TestWithHeadersAndContentReceiver<ClientT>(
  8175. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8176. const std::string &body, const std::string &content_type,
  8177. ContentReceiver receiver, DownloadProgress progress) {
  8178. return cli.Post(path, headers, body, content_type, receiver, progress);
  8179. });
  8180. }
  8181. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8182. #ifdef CPPHTTPLIB_SSL_ENABLED
  8183. using ClientT = SSLClient;
  8184. #else
  8185. using ClientT = Client;
  8186. #endif
  8187. TestWithHeadersAndContentReceiver<ClientT>(
  8188. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8189. const std::string &body, const std::string &content_type,
  8190. ContentReceiver receiver, DownloadProgress progress) {
  8191. return cli.Put(path, headers, body, content_type, receiver, progress);
  8192. });
  8193. }
  8194. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8195. #ifdef CPPHTTPLIB_SSL_ENABLED
  8196. using ClientT = SSLClient;
  8197. #else
  8198. using ClientT = Client;
  8199. #endif
  8200. TestWithHeadersAndContentReceiver<ClientT>(
  8201. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8202. const std::string &body, const std::string &content_type,
  8203. ContentReceiver receiver, DownloadProgress progress) {
  8204. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8205. });
  8206. }
  8207. template <typename ClientType>
  8208. void TestWithHeadersAndContentReceiverWithProgress(
  8209. ClientType &cli,
  8210. std::function<Result(ClientType &, const std::string &, const Headers &,
  8211. const std::string &, const std::string &,
  8212. ContentReceiver, DownloadProgress)>
  8213. request_func) {
  8214. Headers headers;
  8215. headers.emplace("X-Test-Header", "progress-test");
  8216. std::string received_body;
  8217. auto progress_called = false;
  8218. auto res = request_func(
  8219. cli, "/content_receiver", headers, "content", "text/plain",
  8220. [&](const char *data, size_t data_length) {
  8221. received_body.append(data, data_length);
  8222. return true;
  8223. },
  8224. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8225. progress_called = true;
  8226. return true;
  8227. });
  8228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8229. EXPECT_EQ(StatusCode::OK_200, res->status);
  8230. EXPECT_EQ("content", received_body);
  8231. EXPECT_TRUE(progress_called);
  8232. }
  8233. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8234. #ifdef CPPHTTPLIB_SSL_ENABLED
  8235. using ClientT = SSLClient;
  8236. #else
  8237. using ClientT = Client;
  8238. #endif
  8239. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8240. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8241. const std::string &body, const std::string &content_type,
  8242. ContentReceiver receiver, DownloadProgress progress) {
  8243. return cli.Post(path, headers, body, content_type, receiver, progress);
  8244. });
  8245. }
  8246. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8247. #ifdef CPPHTTPLIB_SSL_ENABLED
  8248. using ClientT = SSLClient;
  8249. #else
  8250. using ClientT = Client;
  8251. #endif
  8252. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8253. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8254. const std::string &body, const std::string &content_type,
  8255. ContentReceiver receiver, DownloadProgress progress) {
  8256. return cli.Put(path, headers, body, content_type, receiver, progress);
  8257. });
  8258. }
  8259. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8260. #ifdef CPPHTTPLIB_SSL_ENABLED
  8261. using ClientT = SSLClient;
  8262. #else
  8263. using ClientT = Client;
  8264. #endif
  8265. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8266. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8267. const std::string &body, const std::string &content_type,
  8268. ContentReceiver receiver, DownloadProgress progress) {
  8269. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8270. });
  8271. }
  8272. template <typename ClientType>
  8273. void TestWithHeadersAndContentReceiverError(
  8274. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8275. const Headers &, const std::string &,
  8276. const std::string &, ContentReceiver)>
  8277. request_func) {
  8278. Headers headers;
  8279. headers.emplace("X-Error-Test", "true");
  8280. std::string received_body;
  8281. auto receiver_failed = false;
  8282. auto res =
  8283. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8284. [&](const char *data, size_t data_length) {
  8285. received_body.append(data, data_length);
  8286. receiver_failed = true;
  8287. return false;
  8288. });
  8289. ASSERT_FALSE(res);
  8290. EXPECT_TRUE(receiver_failed);
  8291. }
  8292. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8293. #ifdef CPPHTTPLIB_SSL_ENABLED
  8294. using ClientT = SSLClient;
  8295. #else
  8296. using ClientT = Client;
  8297. #endif
  8298. TestWithHeadersAndContentReceiverError<ClientT>(
  8299. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8300. const std::string &body, const std::string &content_type,
  8301. ContentReceiver receiver) {
  8302. return cli.Post(path, headers, body, content_type, receiver);
  8303. });
  8304. }
  8305. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8306. #ifdef CPPHTTPLIB_SSL_ENABLED
  8307. using ClientT = SSLClient;
  8308. #else
  8309. using ClientT = Client;
  8310. #endif
  8311. TestWithHeadersAndContentReceiverError<ClientT>(
  8312. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8313. const std::string &body, const std::string &content_type,
  8314. ContentReceiver receiver) {
  8315. return cli.Put(path, headers, body, content_type, receiver);
  8316. });
  8317. }
  8318. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8319. #ifdef CPPHTTPLIB_SSL_ENABLED
  8320. using ClientT = SSLClient;
  8321. #else
  8322. using ClientT = Client;
  8323. #endif
  8324. TestWithHeadersAndContentReceiverError<ClientT>(
  8325. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8326. const std::string &body, const std::string &content_type,
  8327. ContentReceiver receiver) {
  8328. return cli.Patch(path, headers, body, content_type, receiver);
  8329. });
  8330. }
  8331. TEST_F(ServerTest, PostQueryStringAndBody) {
  8332. auto res =
  8333. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8335. ASSERT_EQ(StatusCode::OK_200, res->status);
  8336. }
  8337. TEST_F(ServerTest, HTTP2Magic) {
  8338. Request req;
  8339. req.method = "PRI";
  8340. req.path = "*";
  8341. req.body = "SM";
  8342. auto res = std::make_shared<Response>();
  8343. auto error = Error::Success;
  8344. auto ret = cli_.send(req, *res, error);
  8345. ASSERT_TRUE(ret);
  8346. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8347. }
  8348. TEST_F(ServerTest, KeepAlive) {
  8349. auto res = cli_.Get("/hi");
  8350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8351. EXPECT_EQ(StatusCode::OK_200, res->status);
  8352. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8353. EXPECT_EQ("Hello World!", res->body);
  8354. res = cli_.Get("/hi");
  8355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8356. EXPECT_EQ(StatusCode::OK_200, res->status);
  8357. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8358. EXPECT_EQ("Hello World!", res->body);
  8359. res = cli_.Get("/hi");
  8360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8361. EXPECT_EQ(StatusCode::OK_200, res->status);
  8362. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8363. EXPECT_EQ("Hello World!", res->body);
  8364. res = cli_.Get("/not-exist");
  8365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8366. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8367. res = cli_.Post("/empty", "", "text/plain");
  8368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8369. EXPECT_EQ(StatusCode::OK_200, res->status);
  8370. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8371. EXPECT_EQ("empty", res->body);
  8372. EXPECT_EQ("close", res->get_header_value("Connection"));
  8373. res = cli_.Post(
  8374. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8375. "text/plain");
  8376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8377. EXPECT_EQ(StatusCode::OK_200, res->status);
  8378. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8379. EXPECT_EQ("empty", res->body);
  8380. cli_.set_keep_alive(false);
  8381. res = cli_.Get("/last-request");
  8382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8383. EXPECT_EQ(StatusCode::OK_200, res->status);
  8384. EXPECT_EQ("close", res->get_header_value("Connection"));
  8385. }
  8386. TEST_F(ServerTest, TooManyRedirect) {
  8387. cli_.set_follow_location(true);
  8388. auto res = cli_.Get("/redirect/0");
  8389. ASSERT_TRUE(!res);
  8390. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8391. }
  8392. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8393. Request req;
  8394. req.method = "FOOBAR";
  8395. req.path = "/hi";
  8396. cli_.set_keep_alive(true);
  8397. auto res = cli_.send(req);
  8398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8399. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8400. EXPECT_EQ("close", res->get_header_value("Connection"));
  8401. EXPECT_FALSE(cli_.is_socket_open());
  8402. }
  8403. TEST_F(ServerTest, CustomRouteReadsBody) {
  8404. const std::string xml =
  8405. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8406. Request req;
  8407. req.method = "PROPFIND";
  8408. req.path = "/dav/dir";
  8409. req.set_header("Depth", "1");
  8410. req.body = xml;
  8411. auto res = cli_.send(req);
  8412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8413. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8414. EXPECT_EQ(xml, res->body);
  8415. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8416. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8417. }
  8418. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8419. Request req;
  8420. req.method = "PROPFIND";
  8421. req.path = "/dav/42";
  8422. auto res = cli_.send(req);
  8423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8424. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8425. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8426. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8427. }
  8428. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8429. Request req;
  8430. req.method = "PROPFIND";
  8431. req.path = "/dav-re/123";
  8432. auto res = cli_.send(req);
  8433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8434. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8435. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8436. }
  8437. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8438. Request req;
  8439. req.method = "MKCOL";
  8440. req.path = "/dav-mkcol";
  8441. auto res = cli_.send(req);
  8442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8443. EXPECT_EQ(StatusCode::Created_201, res->status);
  8444. }
  8445. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8446. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8447. Request req;
  8448. req.method = "REPORT";
  8449. req.path = "/dav-report";
  8450. req.body = xml;
  8451. auto res = cli_.send(req);
  8452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8453. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8454. EXPECT_EQ(xml, res->body);
  8455. }
  8456. // A content reader route must fire even when the request carries no body,
  8457. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8458. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8459. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8460. Request req;
  8461. req.method = "REPORT";
  8462. req.path = "/dav-report";
  8463. auto res = cli_.send(req);
  8464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8465. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8466. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8467. }
  8468. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8469. Request req;
  8470. req.method = "PROPFIND";
  8471. req.path = "/not-dav";
  8472. auto res = cli_.send(req);
  8473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8474. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8475. }
  8476. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8477. Request req;
  8478. req.method = "UNLOCK";
  8479. req.path = "/dav/dir";
  8480. cli_.set_keep_alive(true);
  8481. auto res = cli_.send(req);
  8482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8483. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8484. EXPECT_EQ("close", res->get_header_value("Connection"));
  8485. EXPECT_FALSE(cli_.is_socket_open());
  8486. }
  8487. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8488. // The mount point serves this path, but only for GET and HEAD.
  8489. auto get_res = cli_.Get("/dir/index.html");
  8490. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8491. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8492. Request req;
  8493. req.method = "PROPFIND";
  8494. req.path = "/dir/index.html";
  8495. auto res = cli_.send(req);
  8496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8497. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8498. }
  8499. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8500. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8501. cli_.set_keep_alive(true);
  8502. for (auto i = 0; i < 2; i++) {
  8503. Request req;
  8504. req.method = "PROPFIND";
  8505. req.path = "/dav/dir";
  8506. req.body = xml;
  8507. auto res = cli_.send(req);
  8508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8509. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8510. EXPECT_EQ(xml, res->body);
  8511. EXPECT_TRUE(cli_.is_socket_open());
  8512. }
  8513. // A built-in method must still be served on the same connection.
  8514. cli_.set_keep_alive(false);
  8515. auto res = cli_.Get("/hi");
  8516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8517. EXPECT_EQ(StatusCode::OK_200, res->status);
  8518. EXPECT_EQ("close", res->get_header_value("Connection"));
  8519. }
  8520. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8521. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8522. Request req;
  8523. req.method = "PROPFIND";
  8524. req.path = "/dav/dir";
  8525. req.set_header("Expect", "100-continue");
  8526. req.body = xml;
  8527. auto res = cli_.send(req);
  8528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8529. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8530. EXPECT_EQ(xml, res->body);
  8531. }
  8532. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8533. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8534. TEST_F(ServerTest, Gzip) {
  8535. Headers headers;
  8536. headers.emplace("Accept-Encoding", "gzip, deflate");
  8537. auto res = cli_.Get("/compress", headers);
  8538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8539. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8540. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8541. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8542. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8543. "7890123456789012345678901234567890",
  8544. res->body);
  8545. EXPECT_EQ(StatusCode::OK_200, res->status);
  8546. }
  8547. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8548. Headers headers;
  8549. headers.emplace("Accept-Encoding", "gzip, deflate");
  8550. auto res = cli_.Get("/compress-with-charset", headers);
  8551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8552. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8553. EXPECT_EQ("application/json; charset=utf-8",
  8554. res->get_header_value("Content-Type"));
  8555. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8556. "7890123456789012345678901234567890",
  8557. res->body);
  8558. EXPECT_EQ(StatusCode::OK_200, res->status);
  8559. }
  8560. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8561. Headers headers;
  8562. headers.emplace("Accept-Encoding", "");
  8563. auto res = cli_.Get("/compress", headers);
  8564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8565. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8566. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8567. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8568. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8569. "7890123456789012345678901234567890",
  8570. res->body);
  8571. EXPECT_EQ(StatusCode::OK_200, res->status);
  8572. }
  8573. TEST_F(ServerTest, GzipWithContentReceiver) {
  8574. Headers headers;
  8575. headers.emplace("Accept-Encoding", "gzip, deflate");
  8576. std::string body;
  8577. auto res =
  8578. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8579. EXPECT_EQ(100U, data_length);
  8580. body.append(data, data_length);
  8581. return true;
  8582. });
  8583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8584. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8585. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8586. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8587. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8588. "7890123456789012345678901234567890",
  8589. body);
  8590. EXPECT_EQ(StatusCode::OK_200, res->status);
  8591. }
  8592. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8593. Headers headers;
  8594. headers.emplace("Accept-Encoding", "gzip, deflate");
  8595. cli_.set_decompress(false);
  8596. auto res = cli_.Get("/compress", headers);
  8597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8598. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8599. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8600. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8601. EXPECT_EQ(33U, res->body.size());
  8602. EXPECT_EQ(StatusCode::OK_200, res->status);
  8603. }
  8604. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8605. Headers headers;
  8606. headers.emplace("Accept-Encoding", "");
  8607. std::string body;
  8608. auto res =
  8609. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8610. EXPECT_EQ(100U, data_length);
  8611. body.append(data, data_length);
  8612. return true;
  8613. });
  8614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8615. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8616. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8617. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8618. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8619. "7890123456789012345678901234567890",
  8620. body);
  8621. EXPECT_EQ(StatusCode::OK_200, res->status);
  8622. }
  8623. TEST_F(ServerTest, NoGzip) {
  8624. Headers headers;
  8625. headers.emplace("Accept-Encoding", "gzip, deflate");
  8626. auto res = cli_.Get("/nocompress", headers);
  8627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8628. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8629. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8630. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8631. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8632. "7890123456789012345678901234567890",
  8633. res->body);
  8634. EXPECT_EQ(StatusCode::OK_200, res->status);
  8635. }
  8636. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8637. Headers headers;
  8638. headers.emplace("Accept-Encoding", "gzip, deflate");
  8639. std::string body;
  8640. auto res = cli_.Get("/nocompress", headers,
  8641. [&](const char *data, size_t data_length) {
  8642. EXPECT_EQ(100U, data_length);
  8643. body.append(data, data_length);
  8644. return true;
  8645. });
  8646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8647. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8648. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8649. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8650. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8651. "7890123456789012345678901234567890",
  8652. body);
  8653. EXPECT_EQ(StatusCode::OK_200, res->status);
  8654. }
  8655. TEST_F(ServerTest, MultipartFormDataGzip) {
  8656. UploadFormDataItems items = {
  8657. {"key1", "test", "", ""},
  8658. {"key2", "--abcdefg123", "", ""},
  8659. };
  8660. cli_.set_compress(true);
  8661. auto res = cli_.Post("/compress-multipart", items);
  8662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8663. EXPECT_EQ(StatusCode::OK_200, res->status);
  8664. }
  8665. #endif
  8666. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8667. // Static file compression is opt-in, so these run their own server rather than
  8668. // flipping it on for the shared ServerTest fixture, which would silently
  8669. // rewrite what every other static file test is asserting.
  8670. class StaticFileCompressionTest : public ::testing::Test {
  8671. protected:
  8672. void TearDown() override {
  8673. if (t_.joinable()) {
  8674. svr_.stop();
  8675. t_.join();
  8676. }
  8677. }
  8678. int start(const std::function<void(Server &)> &configure = nullptr) {
  8679. // Serves the same tree as a directory of build-time compressed assets
  8680. // would be served: the mount point names the coding the files are already
  8681. // stored in. Registered before "/" so it is the one that matches.
  8682. svr_.set_mount_point("/pre-encoded", "./www",
  8683. {{"Content-Encoding", "gzip"}});
  8684. svr_.set_mount_point("/", "./www");
  8685. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8686. res.set_file_content("./www/dir/index.html", "text/html");
  8687. });
  8688. svr_.Get("/pre-encoded-file-content",
  8689. [](const Request & /*req*/, Response &res) {
  8690. res.set_header("Content-Encoding", "gzip");
  8691. res.set_file_content("./www/dir/index.html", "text/html");
  8692. });
  8693. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8694. res.set_content_provider(
  8695. 6, "text/plain",
  8696. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8697. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8698. return true;
  8699. });
  8700. });
  8701. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8702. res.set_content_provider(
  8703. 1000, "text/plain",
  8704. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8705. if (offset < 100) {
  8706. std::string data(100, 'A');
  8707. sink.write(data.data(), data.size());
  8708. return true;
  8709. }
  8710. std::this_thread::sleep_for(std::chrono::seconds(2));
  8711. std::string data(900, 'B');
  8712. sink.write(data.data(), data.size());
  8713. return true;
  8714. });
  8715. });
  8716. if (configure) { configure(svr_); }
  8717. auto port = svr_.bind_to_any_port(HOST);
  8718. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8719. svr_.wait_until_ready();
  8720. return port;
  8721. }
  8722. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8723. // Every file under ./www except 1MB.txt is smaller than the default
  8724. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8725. // it out of the way.
  8726. static void enable_without_floor(Server &svr) {
  8727. svr.set_static_file_compression(true);
  8728. svr.set_static_file_compression_min_length(0);
  8729. }
  8730. Server svr_;
  8731. std::thread t_;
  8732. };
  8733. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8734. auto port = start();
  8735. Client cli(HOST, port);
  8736. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8738. EXPECT_EQ(StatusCode::OK_200, res->status);
  8739. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8740. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8741. EXPECT_EQ(1048576U, res->body.size());
  8742. }
  8743. TEST_F(StaticFileCompressionTest, MountPoint) {
  8744. auto port = start(enable);
  8745. Client cli(HOST, port);
  8746. cli.set_decompress(false);
  8747. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8749. EXPECT_EQ(StatusCode::OK_200, res->status);
  8750. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8751. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8752. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8753. // The response stays self-delimiting: a length, not a chunked body.
  8754. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8755. EXPECT_EQ(std::to_string(res->body.size()),
  8756. res->get_header_value("Content-Length"));
  8757. EXPECT_LT(res->body.size(), 1048576U);
  8758. EXPECT_FALSE(res->body.empty());
  8759. }
  8760. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8761. auto port = start(enable);
  8762. Client cli(HOST, port);
  8763. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8765. EXPECT_EQ(StatusCode::OK_200, res->status);
  8766. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8767. EXPECT_EQ(1048576U, res->body.size());
  8768. }
  8769. TEST_F(StaticFileCompressionTest, FileContent) {
  8770. auto port = start(enable_without_floor);
  8771. Client cli(HOST, port);
  8772. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8774. EXPECT_EQ(StatusCode::OK_200, res->status);
  8775. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8776. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8777. EXPECT_EQ(104U, res->body.size());
  8778. }
  8779. // A handler that serves an already-encoded file names the coding itself. The
  8780. // file-backed path decided its coding from Accept-Encoding and the content
  8781. // type alone, so it compressed the stored bytes a second time and appended a
  8782. // second Content-Encoding field line.
  8783. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8784. auto port = start(enable_without_floor);
  8785. Client cli(HOST, port);
  8786. cli.set_decompress(false);
  8787. auto res = cli.Get("/pre-encoded-file-content",
  8788. Headers{{"Accept-Encoding", "gzip"}});
  8789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8790. EXPECT_EQ(StatusCode::OK_200, res->status);
  8791. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8792. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8793. // Vary belongs to a coding the server chose, and it chose none here.
  8794. EXPECT_FALSE(res->has_header("Vary"));
  8795. // The file travels exactly as it is stored on disk.
  8796. EXPECT_EQ(104U, res->body.size());
  8797. }
  8798. // The 1MB file clears the default floor, so this one runs the configuration a
  8799. // deployment would actually have.
  8800. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8801. auto port = start(enable);
  8802. Client cli(HOST, port);
  8803. cli.set_decompress(false);
  8804. auto res =
  8805. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8807. EXPECT_EQ(StatusCode::OK_200, res->status);
  8808. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8809. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8810. EXPECT_FALSE(res->has_header("Vary"));
  8811. EXPECT_EQ(1048576U, res->body.size());
  8812. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8813. }
  8814. TEST_F(StaticFileCompressionTest, Head) {
  8815. auto port = start(enable);
  8816. Client cli(HOST, port);
  8817. cli.set_decompress(false);
  8818. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8819. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8820. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8822. EXPECT_EQ(StatusCode::OK_200, res->status);
  8823. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8824. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8825. // HEAD still reports the size a GET would return.
  8826. EXPECT_EQ(get->get_header_value("Content-Length"),
  8827. res->get_header_value("Content-Length"));
  8828. EXPECT_TRUE(res->body.empty());
  8829. }
  8830. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8831. auto port = start(enable);
  8832. Client cli(HOST, port);
  8833. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8834. {"Accept-Encoding", "gzip"}});
  8835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8836. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8837. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8838. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8839. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8840. EXPECT_EQ("cd", res->body);
  8841. }
  8842. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8843. auto port = start(enable);
  8844. Client cli(HOST, port);
  8845. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8847. EXPECT_EQ(StatusCode::OK_200, res->status);
  8848. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8849. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8850. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8851. }
  8852. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8853. auto port = start(enable);
  8854. Client cli(HOST, port);
  8855. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8857. EXPECT_EQ(StatusCode::OK_200, res->status);
  8858. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8859. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8860. EXPECT_TRUE(res->body.empty());
  8861. }
  8862. TEST_F(StaticFileCompressionTest, MinLength) {
  8863. auto port = start(enable);
  8864. Client cli(HOST, port);
  8865. // 104 bytes, well under the default floor. Compressing it would add the
  8866. // gzip header and trailer to a body that already fits in one packet.
  8867. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8869. EXPECT_EQ(StatusCode::OK_200, res->status);
  8870. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8871. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8872. }
  8873. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8874. auto port = start([](Server &svr) {
  8875. svr.set_static_file_compression(true);
  8876. svr.set_static_file_compression_min_length(1);
  8877. });
  8878. Client cli(HOST, port);
  8879. cli.set_decompress(false);
  8880. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8882. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8883. // A 9-byte file comes back larger than it went in, because gzip's header and
  8884. // trailer outweigh anything deflate can save. That is the end of the range
  8885. // the floor exists to keep out.
  8886. EXPECT_GT(res->body.size(), 9U);
  8887. }
  8888. TEST_F(StaticFileCompressionTest, MaxLength) {
  8889. auto port = start([](Server &svr) {
  8890. svr.set_static_file_compression(true);
  8891. svr.set_static_file_compression_min_length(0);
  8892. svr.set_static_file_compression_max_length(1024);
  8893. });
  8894. Client cli(HOST, port);
  8895. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8896. // defines `small` as a macro on Windows.
  8897. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8898. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8899. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8900. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8901. // Under it: compressed.
  8902. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8903. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8904. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8905. }
  8906. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8907. auto port = start(enable_without_floor);
  8908. Client cli(HOST, port);
  8909. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8910. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8911. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8912. auto identity_etag = identity->get_header_value("ETag");
  8913. ASSERT_FALSE(identity_etag.empty());
  8914. auto gzipped =
  8915. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8916. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8917. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8918. auto gzip_etag = gzipped->get_header_value("ETag");
  8919. ASSERT_FALSE(gzip_etag.empty());
  8920. // Two representations, two validators.
  8921. EXPECT_NE(identity_etag, gzip_etag);
  8922. // Each one revalidates against the request that would produce it...
  8923. auto fresh =
  8924. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8925. {"If-None-Match", gzip_etag}});
  8926. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8927. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8928. auto fresh_identity =
  8929. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8930. {"If-None-Match", identity_etag}});
  8931. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8932. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8933. // ...and not against the other representation.
  8934. auto crossed =
  8935. cli.Get("/dir/index.html",
  8936. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8937. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8938. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8939. }
  8940. // The opt-in covers responses the server reads off disk itself. A caller's own
  8941. // known-length provider keeps its Content-Length and, more importantly, keeps
  8942. // delivering incrementally: routing it through a compressor would hold every
  8943. // write back until zlib's window filled.
  8944. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8945. auto port = start(enable);
  8946. Client cli(HOST, port);
  8947. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8949. EXPECT_EQ(StatusCode::OK_200, res->status);
  8950. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8951. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8952. EXPECT_EQ("aaabbb", res->body);
  8953. }
  8954. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8955. auto port = start(enable);
  8956. Client cli(HOST, port);
  8957. cli.set_read_timeout(1, 0);
  8958. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8959. Headers{{"Accept-Encoding", "gzip"}});
  8960. ASSERT_TRUE(handle.is_valid());
  8961. // The provider writes 100 bytes and then stalls for longer than the read
  8962. // timeout. Those first bytes have to arrive anyway: run the response through
  8963. // a compressor and zlib holds them until its window fills, so the read would
  8964. // come back empty instead.
  8965. char buf[256];
  8966. auto n = handle.read(buf, sizeof(buf));
  8967. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8968. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8969. }
  8970. #endif
  8971. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8972. TEST_F(ServerTest, Brotli) {
  8973. Headers headers;
  8974. headers.emplace("Accept-Encoding", "br");
  8975. auto res = cli_.Get("/compress", headers);
  8976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8977. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8978. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8979. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8980. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8981. "7890123456789012345678901234567890",
  8982. res->body);
  8983. EXPECT_EQ(StatusCode::OK_200, res->status);
  8984. }
  8985. #endif
  8986. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8987. TEST_F(ServerTest, Zstd) {
  8988. Headers headers;
  8989. headers.emplace("Accept-Encoding", "zstd");
  8990. auto res = cli_.Get("/compress", headers);
  8991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8992. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8993. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8994. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8995. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8996. "7890123456789012345678901234567890",
  8997. res->body);
  8998. EXPECT_EQ(StatusCode::OK_200, res->status);
  8999. }
  9000. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9001. Headers headers;
  9002. headers.emplace("Accept-Encoding", "");
  9003. auto res = cli_.Get("/compress", headers);
  9004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9005. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9006. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9007. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9008. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9009. "7890123456789012345678901234567890",
  9010. res->body);
  9011. EXPECT_EQ(StatusCode::OK_200, res->status);
  9012. }
  9013. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9014. Headers headers;
  9015. headers.emplace("Accept-Encoding", "zstd");
  9016. std::string body;
  9017. auto res =
  9018. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9019. EXPECT_EQ(100U, data_length);
  9020. body.append(data, data_length);
  9021. return true;
  9022. });
  9023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9024. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9025. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9026. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9027. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9028. "7890123456789012345678901234567890",
  9029. body);
  9030. EXPECT_EQ(StatusCode::OK_200, res->status);
  9031. }
  9032. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9033. Headers headers;
  9034. headers.emplace("Accept-Encoding", "zstd");
  9035. cli_.set_decompress(false);
  9036. auto res = cli_.Get("/compress", headers);
  9037. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9038. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9039. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9040. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9042. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9043. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9044. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9045. EXPECT_EQ(StatusCode::OK_200, res->status);
  9046. ASSERT_EQ(26U, res->body.size());
  9047. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9048. 0);
  9049. }
  9050. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9051. Headers headers;
  9052. headers.emplace("Accept-Encoding", "");
  9053. std::string body;
  9054. auto res =
  9055. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9056. EXPECT_EQ(100U, data_length);
  9057. body.append(data, data_length);
  9058. return true;
  9059. });
  9060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9061. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9062. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9063. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9064. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9065. "7890123456789012345678901234567890",
  9066. body);
  9067. EXPECT_EQ(StatusCode::OK_200, res->status);
  9068. }
  9069. TEST_F(ServerTest, NoZstd) {
  9070. Headers headers;
  9071. headers.emplace("Accept-Encoding", "zstd");
  9072. auto res = cli_.Get("/nocompress", headers);
  9073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9074. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9075. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9076. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9077. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9078. "7890123456789012345678901234567890",
  9079. res->body);
  9080. EXPECT_EQ(StatusCode::OK_200, res->status);
  9081. }
  9082. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9083. Headers headers;
  9084. headers.emplace("Accept-Encoding", "zstd");
  9085. std::string body;
  9086. auto res = cli_.Get("/nocompress", headers,
  9087. [&](const char *data, size_t data_length) {
  9088. EXPECT_EQ(100U, data_length);
  9089. body.append(data, data_length);
  9090. return true;
  9091. });
  9092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9093. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9094. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9095. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9096. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9097. "7890123456789012345678901234567890",
  9098. body);
  9099. EXPECT_EQ(StatusCode::OK_200, res->status);
  9100. }
  9101. // TODO: How to enable zstd ??
  9102. TEST_F(ServerTest, MultipartFormDataZstd) {
  9103. UploadFormDataItems items = {
  9104. {"key1", "test", "", ""},
  9105. {"key2", "--abcdefg123", "", ""},
  9106. };
  9107. Headers headers;
  9108. headers.emplace("Accept-Encoding", "zstd");
  9109. cli_.set_compress(true);
  9110. auto res = cli_.Post("/compress-multipart", headers, items);
  9111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9112. EXPECT_EQ(StatusCode::OK_200, res->status);
  9113. }
  9114. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9115. Headers headers;
  9116. headers.emplace("Accept-Encoding", "zstd");
  9117. cli_.set_compress(true);
  9118. auto res = cli_.Put(
  9119. "/put", headers, 3,
  9120. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9121. sink.os << "PUT";
  9122. return true;
  9123. },
  9124. "text/plain");
  9125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9126. EXPECT_EQ(StatusCode::OK_200, res->status);
  9127. EXPECT_EQ("PUT", res->body);
  9128. }
  9129. // Pre-compression logging tests
  9130. TEST_F(ServerTest, PreCompressionLogging) {
  9131. // Test data for compression (matches the actual /compress endpoint content)
  9132. const std::string test_content =
  9133. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9134. "3456789012345678901234567890";
  9135. // Variables to capture logging data
  9136. std::string pre_compression_body;
  9137. std::string pre_compression_content_type;
  9138. std::string pre_compression_content_encoding;
  9139. std::string post_compression_body;
  9140. std::string post_compression_content_type;
  9141. std::string post_compression_content_encoding;
  9142. // Set up pre-compression logger
  9143. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9144. const Response &res) {
  9145. pre_compression_body = res.body;
  9146. pre_compression_content_type = res.get_header_value("Content-Type");
  9147. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9148. });
  9149. // Set up post-compression logger
  9150. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9151. post_compression_body = res.body;
  9152. post_compression_content_type = res.get_header_value("Content-Type");
  9153. post_compression_content_encoding =
  9154. res.get_header_value("Content-Encoding");
  9155. });
  9156. // Test with gzip compression
  9157. Headers headers;
  9158. headers.emplace("Accept-Encoding", "gzip");
  9159. auto res = cli_.Get("/compress", headers);
  9160. // Verify response was compressed
  9161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9162. EXPECT_EQ(StatusCode::OK_200, res->status);
  9163. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9164. // Verify pre-compression logger captured uncompressed content
  9165. EXPECT_EQ(test_content, pre_compression_body);
  9166. EXPECT_EQ("text/plain", pre_compression_content_type);
  9167. EXPECT_TRUE(pre_compression_content_encoding
  9168. .empty()); // No encoding header before compression
  9169. // Verify post-compression logger captured compressed content
  9170. EXPECT_NE(test_content,
  9171. post_compression_body); // Should be different after compression
  9172. EXPECT_EQ("text/plain", post_compression_content_type);
  9173. EXPECT_EQ("gzip", post_compression_content_encoding);
  9174. // Verify compressed content is smaller
  9175. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9176. }
  9177. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9178. const std::string test_content =
  9179. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9180. "3456789012345678901234567890";
  9181. std::string pre_compression_body;
  9182. std::string post_compression_body;
  9183. svr_.set_pre_compression_logger(
  9184. [&](const Request & /*req*/, const Response &res) {
  9185. pre_compression_body = res.body;
  9186. });
  9187. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9188. post_compression_body = res.body;
  9189. });
  9190. Headers headers;
  9191. headers.emplace("Accept-Encoding", "br");
  9192. auto res = cli_.Get("/compress", headers);
  9193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9194. EXPECT_EQ(StatusCode::OK_200, res->status);
  9195. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9196. // Verify pre-compression content is uncompressed
  9197. EXPECT_EQ(test_content, pre_compression_body);
  9198. // Verify post-compression content is compressed
  9199. EXPECT_NE(test_content, post_compression_body);
  9200. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9201. }
  9202. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9203. const std::string test_content =
  9204. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9205. "3456789012345678901234567890";
  9206. std::string pre_compression_body;
  9207. std::string post_compression_body;
  9208. svr_.set_pre_compression_logger(
  9209. [&](const Request & /*req*/, const Response &res) {
  9210. pre_compression_body = res.body;
  9211. });
  9212. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9213. post_compression_body = res.body;
  9214. });
  9215. // Request without compression (use /nocompress endpoint)
  9216. Headers headers;
  9217. auto res = cli_.Get("/nocompress", headers);
  9218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9219. EXPECT_EQ(StatusCode::OK_200, res->status);
  9220. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9221. // Pre-compression logger should not be called when no compression is applied
  9222. EXPECT_TRUE(
  9223. pre_compression_body.empty()); // Pre-compression logger not called
  9224. EXPECT_EQ(
  9225. test_content,
  9226. post_compression_body); // Post-compression logger captures final content
  9227. }
  9228. TEST_F(ServerTest, LoggerSeesContentLength) {
  9229. size_t logged_content_length = 0;
  9230. std::string logged_content_length_header;
  9231. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9232. logged_content_length = res.content_length_;
  9233. logged_content_length_header = res.get_header_value("Content-Length");
  9234. });
  9235. auto res = cli_.Get("/nocompress");
  9236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9237. EXPECT_EQ(StatusCode::OK_200, res->status);
  9238. EXPECT_EQ(res->body.size(), logged_content_length);
  9239. EXPECT_EQ(std::to_string(logged_content_length),
  9240. logged_content_length_header);
  9241. }
  9242. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9243. const std::string test_content =
  9244. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9245. "3456789012345678901234567890";
  9246. std::string pre_compression_body;
  9247. bool pre_logger_called = false;
  9248. // Set only pre-compression logger
  9249. svr_.set_pre_compression_logger(
  9250. [&](const Request & /*req*/, const Response &res) {
  9251. pre_compression_body = res.body;
  9252. pre_logger_called = true;
  9253. });
  9254. Headers headers;
  9255. headers.emplace("Accept-Encoding", "gzip");
  9256. auto res = cli_.Get("/compress", headers);
  9257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9258. EXPECT_EQ(StatusCode::OK_200, res->status);
  9259. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9260. // Verify pre-compression logger was called
  9261. EXPECT_TRUE(pre_logger_called);
  9262. EXPECT_EQ(test_content, pre_compression_body);
  9263. }
  9264. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9265. {
  9266. // Test with Expect: 100-continue header - success case
  9267. // Server returns 100 Continue, client sends body, server returns 200 OK
  9268. Request req;
  9269. req.method = "POST";
  9270. req.path = "/post-large";
  9271. req.set_header("Expect", "100-continue");
  9272. req.body = LARGE_DATA;
  9273. Response res;
  9274. auto error = Error::Success;
  9275. cli_.set_keep_alive(true);
  9276. auto ret = cli_.send(req, res, error);
  9277. EXPECT_TRUE(ret);
  9278. EXPECT_EQ(StatusCode::OK_200, res.status);
  9279. EXPECT_EQ(LARGE_DATA, res.body);
  9280. }
  9281. {
  9282. // Test with Expect: 100-continue header - error case
  9283. // Client should not send the body when server returns an error
  9284. Request req;
  9285. req.method = "POST";
  9286. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9287. req.set_header("Expect", "100-continue");
  9288. req.body = LARGE_DATA;
  9289. Response res;
  9290. auto error = Error::Success;
  9291. auto start = std::chrono::high_resolution_clock::now();
  9292. cli_.set_keep_alive(true);
  9293. auto ret = cli_.send(req, res, error);
  9294. auto end = std::chrono::high_resolution_clock::now();
  9295. auto elapsed =
  9296. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9297. .count();
  9298. // With Expect: 100-continue, request completes successfully but with error
  9299. EXPECT_TRUE(ret);
  9300. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9301. EXPECT_EQ("close", res.get_header_value("Connection"));
  9302. EXPECT_FALSE(cli_.is_socket_open());
  9303. EXPECT_LE(elapsed, 2000);
  9304. }
  9305. {
  9306. // Send an extra GET request to ensure error recovery without hanging
  9307. Request req;
  9308. req.method = "GET";
  9309. req.path = "/hi";
  9310. auto start = std::chrono::high_resolution_clock::now();
  9311. auto res = cli_.send(req);
  9312. auto end = std::chrono::high_resolution_clock::now();
  9313. auto elapsed =
  9314. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9315. .count();
  9316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9317. EXPECT_EQ(StatusCode::OK_200, res->status);
  9318. EXPECT_EQ("Hello World!", res->body);
  9319. EXPECT_LE(elapsed, 500);
  9320. }
  9321. }
  9322. TEST(ZstdDecompressor, ChunkedDecompression) {
  9323. std::string data;
  9324. for (size_t i = 0; i < 32 * 1024; ++i) {
  9325. data.push_back(static_cast<char>('a' + i % 26));
  9326. }
  9327. std::string compressed_data;
  9328. {
  9329. httplib::detail::zstd_compressor compressor;
  9330. bool result = compressor.compress(
  9331. data.data(), data.size(),
  9332. /*last=*/true,
  9333. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9334. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9335. compressed_data_size);
  9336. return true;
  9337. });
  9338. ASSERT_TRUE(result);
  9339. }
  9340. std::string decompressed_data;
  9341. {
  9342. httplib::detail::zstd_decompressor decompressor;
  9343. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9344. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9345. size_t chunk_size = 130;
  9346. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9347. chunk_begin += chunk_size) {
  9348. size_t current_chunk_size =
  9349. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9350. bool result = decompressor.decompress(
  9351. compressed_data.data() + chunk_begin, current_chunk_size,
  9352. [&](const char *decompressed_data_chunk,
  9353. size_t decompressed_data_chunk_size) {
  9354. decompressed_data.insert(decompressed_data.size(),
  9355. decompressed_data_chunk,
  9356. decompressed_data_chunk_size);
  9357. return true;
  9358. });
  9359. ASSERT_TRUE(result);
  9360. }
  9361. }
  9362. ASSERT_EQ(data, decompressed_data);
  9363. }
  9364. TEST(ZstdDecompressor, Decompress) {
  9365. std::string original_text = "Compressed with ZSTD";
  9366. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9367. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9368. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9369. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9370. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9371. std::string decompressed_data;
  9372. {
  9373. httplib::detail::zstd_decompressor decompressor;
  9374. bool result = decompressor.decompress(
  9375. compressed_data.data(), compressed_data.size(),
  9376. [&](const char *decompressed_data_chunk,
  9377. size_t decompressed_data_chunk_size) {
  9378. decompressed_data.insert(decompressed_data.size(),
  9379. decompressed_data_chunk,
  9380. decompressed_data_chunk_size);
  9381. return true;
  9382. });
  9383. ASSERT_TRUE(result);
  9384. }
  9385. ASSERT_EQ(original_text, decompressed_data);
  9386. }
  9387. #endif
  9388. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9389. // separate chunks so that the server sees each part in its own read(). Used to
  9390. // place a read boundary at a specific offset of a request body.
  9391. static bool send_request_in_parts(time_t read_timeout_sec,
  9392. const std::vector<std::string> &parts,
  9393. std::string *resp = nullptr,
  9394. int port = PORT) {
  9395. auto error = Error::Success;
  9396. auto client_sock = detail::create_client_socket(
  9397. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9398. /*connection_timeout_sec=*/5, 0,
  9399. /*read_timeout_sec=*/5, 0,
  9400. /*write_timeout_sec=*/5, 0, std::string(), error);
  9401. if (client_sock == INVALID_SOCKET) { return false; }
  9402. auto ret = detail::process_client_socket(
  9403. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9404. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9405. for (size_t i = 0; i < parts.size(); i++) {
  9406. const auto &part = parts[i];
  9407. if (part.size() !=
  9408. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9409. return false;
  9410. }
  9411. if (i + 1 < parts.size()) {
  9412. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9413. }
  9414. }
  9415. char buf[512];
  9416. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9417. while (line_reader.getline()) {
  9418. if (resp) { *resp += line_reader.ptr(); }
  9419. }
  9420. return true;
  9421. });
  9422. detail::close_socket(client_sock);
  9423. return ret;
  9424. }
  9425. // Sends a raw request to a server listening at HOST:PORT.
  9426. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9427. std::string *resp = nullptr, int port = PORT) {
  9428. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9429. }
  9430. #ifdef CPPHTTPLIB_SSL_ENABLED
  9431. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9432. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9433. ASSERT_TRUE(svr.is_valid());
  9434. svr.set_read_timeout(1, 0);
  9435. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9436. auto se = detail::scope_exit([&] {
  9437. svr.stop();
  9438. t.join();
  9439. ASSERT_FALSE(svr.is_running());
  9440. });
  9441. svr.wait_until_ready();
  9442. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9443. // keeps each wait well within the read timeout. The server gives up a
  9444. // second in, so the bytes sent after that fail.
  9445. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9446. parts.resize(26, std::string(1, '\0'));
  9447. EXPECT_FALSE(send_request_in_parts(5, parts));
  9448. }
  9449. #endif
  9450. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9451. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9452. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9453. const std::vector<std::string> &parts,
  9454. std::string *resp = nullptr,
  9455. int port = PORT) {
  9456. auto error = Error::Success;
  9457. auto sock = detail::create_client_socket(
  9458. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9459. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9460. /*write_timeout_sec=*/5, 0, std::string(), error);
  9461. if (sock == INVALID_SOCKET) { return false; }
  9462. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9463. auto ctx = SSL_CTX_new(TLS_client_method());
  9464. auto ssl = SSL_new(ctx);
  9465. auto ssl_se = detail::scope_exit([&] {
  9466. SSL_free(ssl);
  9467. SSL_CTX_free(ctx);
  9468. });
  9469. SSL_set_fd(ssl, static_cast<int>(sock));
  9470. if (SSL_connect(ssl) != 1) { return false; }
  9471. for (size_t i = 0; i < parts.size(); i++) {
  9472. const auto &part = parts[i];
  9473. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9474. static_cast<int>(part.size())) {
  9475. return false;
  9476. }
  9477. if (i + 1 < parts.size()) {
  9478. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9479. }
  9480. }
  9481. char buf[512];
  9482. int n;
  9483. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9484. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9485. }
  9486. return true;
  9487. }
  9488. #endif
  9489. // The request line, then a header value a byte at a time.
  9490. static std::vector<std::string> slow_request_head_parts() {
  9491. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9492. parts.resize(26, "a");
  9493. parts.emplace_back("\r\n\r\n");
  9494. return parts;
  9495. }
  9496. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9497. // within the one-second read timeout. The server gives up a second in, before
  9498. // the head is complete.
  9499. static void
  9500. expect_slow_request_head_dropped(Server &svr,
  9501. const std::function<std::string()> &send) {
  9502. std::atomic<bool> handled(false);
  9503. svr.Get("/", [&](const Request &, Response &res) {
  9504. handled = true;
  9505. res.set_content("ok", "text/plain");
  9506. });
  9507. svr.set_read_timeout(1, 0);
  9508. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9509. auto se = detail::scope_exit([&] {
  9510. svr.stop();
  9511. t.join();
  9512. ASSERT_FALSE(svr.is_running());
  9513. });
  9514. svr.wait_until_ready();
  9515. auto resp = send();
  9516. EXPECT_FALSE(handled);
  9517. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9518. }
  9519. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9520. Server svr;
  9521. expect_slow_request_head_dropped(svr, [] {
  9522. std::string resp;
  9523. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9524. return resp;
  9525. });
  9526. }
  9527. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9528. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9529. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9530. ASSERT_TRUE(svr.is_valid());
  9531. expect_slow_request_head_dropped(svr, [] {
  9532. std::string resp;
  9533. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9534. return resp;
  9535. });
  9536. }
  9537. #endif
  9538. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9539. Server svr;
  9540. std::string header_value;
  9541. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9542. header_value = req.get_header_value("foo");
  9543. res.set_content("ok", "text/plain");
  9544. });
  9545. thread t = thread([&] { svr.listen(HOST, PORT); });
  9546. auto se = detail::scope_exit([&] {
  9547. svr.stop();
  9548. t.join();
  9549. ASSERT_FALSE(svr.is_running());
  9550. });
  9551. svr.wait_until_ready();
  9552. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9553. // like characters are not treated the same - use vertical tab and escape.
  9554. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9555. "foo: \t \v bar \x1B\t \r\n"
  9556. "Connection: close\r\n"
  9557. "\r\n";
  9558. std::string res;
  9559. ASSERT_TRUE(send_request(5, req, &res));
  9560. EXPECT_EQ(header_value, "");
  9561. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9562. }
  9563. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9564. Server svr;
  9565. std::string received;
  9566. svr.Get("/order", [&](const Request &req, Response &res) {
  9567. received = entries_to_string(req.headers);
  9568. res.set_content("ok", "text/plain");
  9569. });
  9570. auto port = svr.bind_to_any_port(HOST);
  9571. thread t = thread([&] { svr.listen_after_bind(); });
  9572. auto se = detail::scope_exit([&] {
  9573. svr.stop();
  9574. t.join();
  9575. ASSERT_FALSE(svr.is_running());
  9576. });
  9577. svr.wait_until_ready();
  9578. const std::string req = "GET /order HTTP/1.1\r\n"
  9579. "Host: localhost\r\n"
  9580. "X-First: 1\r\n"
  9581. "X-Dup: a\r\n"
  9582. "X-Second: 2\r\n"
  9583. "X-Dup: b\r\n"
  9584. "Connection: close\r\n"
  9585. "\r\n";
  9586. std::string res;
  9587. ASSERT_TRUE(send_request(5, req, &res, port));
  9588. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9589. EXPECT_EQ(
  9590. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9591. received);
  9592. }
  9593. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9594. Server svr;
  9595. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9596. res.set_header("Set-Cookie", "first=1");
  9597. res.set_header("X-Between", "y");
  9598. res.set_header("Set-Cookie", "second=2");
  9599. res.set_content("ok", "text/plain");
  9600. });
  9601. auto port = svr.bind_to_any_port(HOST);
  9602. thread t = thread([&] { svr.listen_after_bind(); });
  9603. auto se = detail::scope_exit([&] {
  9604. svr.stop();
  9605. t.join();
  9606. ASSERT_FALSE(svr.is_running());
  9607. });
  9608. svr.wait_until_ready();
  9609. Client cli(HOST, port);
  9610. auto res = cli.Get("/cookies");
  9611. ASSERT_TRUE(res);
  9612. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9613. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9614. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9615. }
  9616. // A stream may send a byte at a time with a small extension on each chunk,
  9617. // however long it runs
  9618. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9619. Server svr;
  9620. svr.Post("/count", [](const Request &req, Response &res) {
  9621. res.set_content(std::to_string(req.body.size()), "text/plain");
  9622. });
  9623. auto port = svr.bind_to_any_port(HOST);
  9624. ASSERT_LT(0, port);
  9625. thread t = thread([&] { svr.listen_after_bind(); });
  9626. auto se = detail::scope_exit([&] {
  9627. svr.stop();
  9628. t.join();
  9629. ASSERT_FALSE(svr.is_running());
  9630. });
  9631. svr.wait_until_ready();
  9632. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9633. "\r\nTransfer-Encoding: chunked\r\n"
  9634. "Connection: close\r\n\r\n";
  9635. for (auto i = 0; i < 4096; i++) {
  9636. req += "1;a=b\r\nx\r\n";
  9637. }
  9638. req += "0\r\n\r\n";
  9639. std::string res;
  9640. ASSERT_TRUE(send_request(5, req, &res, port));
  9641. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9642. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9643. }
  9644. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9645. Server svr;
  9646. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9647. auto i = new int(0);
  9648. res.set_header("Trailer", "X-Safe, X-Reflected");
  9649. res.set_chunked_content_provider(
  9650. "text/plain",
  9651. [i](size_t /*offset*/, DataSink &sink) {
  9652. if (*i == 0) {
  9653. sink.os << "body";
  9654. } else {
  9655. Headers trailer;
  9656. // A valid trailer that must survive.
  9657. trailer.emplace("X-Safe", "safe");
  9658. // Attacker-controlled value carrying CR/LF (response splitting).
  9659. trailer.emplace("X-Reflected",
  9660. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9661. // Attacker-controlled name carrying CR/LF.
  9662. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9663. sink.done_with_trailer(trailer);
  9664. }
  9665. (*i)++;
  9666. return true;
  9667. },
  9668. [i](bool /*success*/) { delete i; });
  9669. });
  9670. thread t = thread([&] { svr.listen(HOST, PORT); });
  9671. auto se = detail::scope_exit([&] {
  9672. svr.stop();
  9673. t.join();
  9674. ASSERT_FALSE(svr.is_running());
  9675. });
  9676. svr.wait_until_ready();
  9677. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9678. "Host: " + HOST +
  9679. "\r\n"
  9680. "Connection: close\r\n"
  9681. "\r\n";
  9682. std::string res;
  9683. ASSERT_TRUE(send_request(5, req, &res));
  9684. // The injected fields must not appear anywhere in the raw response.
  9685. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9686. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9687. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9688. // Invalid trailers are dropped entirely, matching set_header().
  9689. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9690. // The valid trailer still passes through.
  9691. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9692. }
  9693. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9694. // A custom header writer gets only the fields the default one writes
  9695. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9696. std::string s;
  9697. for (const auto &h : hdrs) {
  9698. s += h.first + ": " + h.second + "\r\n";
  9699. }
  9700. s += "\r\n";
  9701. return strm.write(s.data(), s.size());
  9702. };
  9703. for (auto custom_writer : {false, true}) {
  9704. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9705. Server svr;
  9706. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9707. svr.set_post_routing_handler([](const Request &, Response &res) {
  9708. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9709. });
  9710. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9711. // res.headers is a public field an application can populate directly,
  9712. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9713. // A valid header that must survive.
  9714. res.headers.emplace("X-Safe", "safe");
  9715. // Attacker-controlled value carrying CR/LF (response splitting).
  9716. res.headers.emplace("X-Reflected",
  9717. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9718. // Attacker-controlled name carrying CR/LF.
  9719. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9720. res.set_content("body", "text/plain");
  9721. });
  9722. thread t = thread([&] { svr.listen(HOST, PORT); });
  9723. auto se = detail::scope_exit([&] {
  9724. svr.stop();
  9725. t.join();
  9726. ASSERT_FALSE(svr.is_running());
  9727. });
  9728. svr.wait_until_ready();
  9729. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9730. "Host: " + HOST +
  9731. "\r\n"
  9732. "Connection: close\r\n"
  9733. "\r\n";
  9734. std::string res;
  9735. ASSERT_TRUE(send_request(5, req, &res));
  9736. // The injected fields must not appear anywhere in the raw response.
  9737. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9738. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9739. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9740. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9741. // Invalid headers are dropped entirely, matching set_header().
  9742. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9743. // The valid header still passes through.
  9744. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9745. }
  9746. }
  9747. // Forward declaration: in split builds split.py strips `inline` and moves the
  9748. // definition into httplib.cc, so detail::write_request_line is not visible from
  9749. // the public httplib.h. Re-declaring it here lets the tests link against the
  9750. // symbol in both header-only and split builds.
  9751. namespace httplib {
  9752. namespace detail {
  9753. ssize_t write_request_line(Stream &strm, const std::string &method,
  9754. const std::string &path);
  9755. } // namespace detail
  9756. } // namespace httplib
  9757. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9758. // A well-formed target is written verbatim.
  9759. {
  9760. detail::BufferStream strm;
  9761. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9762. EXPECT_GT(n, 0);
  9763. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9764. }
  9765. // A target carrying CR/LF, SP or other control octets must be rejected
  9766. // before anything reaches the wire, otherwise it splits the request line and
  9767. // injects a header or a whole request.
  9768. const std::string evil_targets[] = {
  9769. "/a\r\nInjected: pwned",
  9770. "/a\rInjected",
  9771. "/a\nInjected",
  9772. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9773. "/a b",
  9774. "/a\tb",
  9775. "/a\x7f",
  9776. };
  9777. for (const auto &evil : evil_targets) {
  9778. detail::BufferStream strm;
  9779. auto n = detail::write_request_line(strm, "GET", evil);
  9780. EXPECT_LT(n, 0);
  9781. EXPECT_TRUE(strm.get_buffer().empty());
  9782. }
  9783. }
  9784. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9785. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9786. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9787. // target reaches write_request. The client must fail cleanly with
  9788. // Error::Write instead of putting a request-line-less, header-injecting
  9789. // request on the wire.
  9790. Server svr;
  9791. svr.Get("/a", [](const Request &, Response &res) {
  9792. res.set_content("ok", "text/plain");
  9793. });
  9794. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9795. auto se = detail::scope_exit([&] {
  9796. svr.stop();
  9797. thread.join();
  9798. ASSERT_FALSE(svr.is_running());
  9799. });
  9800. svr.wait_until_ready();
  9801. {
  9802. Client cli(HOST, PORT);
  9803. cli.set_path_encode(false);
  9804. // The request is rejected before anything is written, so the connection
  9805. // stays silent and the subsequent response read would otherwise block for
  9806. // the full default read timeout. Shorten it -- the assertion is on the
  9807. // error, not the timeout.
  9808. cli.set_read_timeout(1, 0);
  9809. auto res = cli.Get("/a\r\nInjected: pwned");
  9810. EXPECT_FALSE(res);
  9811. EXPECT_EQ(Error::Write, res.error());
  9812. }
  9813. }
  9814. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9815. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9816. // including extension methods.
  9817. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9818. for (const auto &method : good_methods) {
  9819. detail::BufferStream strm;
  9820. auto n = detail::write_request_line(strm, method, "/");
  9821. EXPECT_GT(n, 0);
  9822. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9823. }
  9824. // A method carrying CR/LF would split the request line and smuggle a whole
  9825. // request ahead of the real one. A space or an empty method corrupts the
  9826. // request line. All must be rejected before anything reaches the wire.
  9827. const std::string evil_methods[] = {
  9828. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9829. "GET\r\nInjected: pwned",
  9830. "GET\r",
  9831. "GET\n",
  9832. "GE T",
  9833. "",
  9834. };
  9835. for (const auto &evil : evil_methods) {
  9836. detail::BufferStream strm;
  9837. auto n = detail::write_request_line(strm, evil, "/");
  9838. EXPECT_LT(n, 0);
  9839. EXPECT_TRUE(strm.get_buffer().empty());
  9840. }
  9841. }
  9842. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9843. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9844. // through Client::send must fail with Error::Write and no request, neither
  9845. // the smuggled one nor the real one, may reach the server.
  9846. Server svr;
  9847. std::atomic<int> request_count(0);
  9848. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9849. request_count++;
  9850. res.status = StatusCode::OK_200;
  9851. return Server::HandlerResponse::Handled;
  9852. });
  9853. auto port = svr.bind_to_any_port(HOST);
  9854. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9855. auto se = detail::scope_exit([&] {
  9856. svr.stop();
  9857. thread.join();
  9858. ASSERT_FALSE(svr.is_running());
  9859. });
  9860. svr.wait_until_ready();
  9861. {
  9862. Client cli(HOST, port);
  9863. const std::string evil_methods[] = {
  9864. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9865. "GE T",
  9866. "",
  9867. };
  9868. for (const auto &evil : evil_methods) {
  9869. Request req;
  9870. req.method = evil;
  9871. req.path = "/";
  9872. auto res = cli.send(req);
  9873. EXPECT_FALSE(res);
  9874. EXPECT_EQ(Error::Write, res.error());
  9875. }
  9876. auto handle =
  9877. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9878. EXPECT_FALSE(handle.is_valid());
  9879. EXPECT_EQ(Error::Write, handle.error);
  9880. // A valid request on the same client still goes through.
  9881. auto res = cli.Get("/");
  9882. ASSERT_TRUE(res);
  9883. EXPECT_EQ(StatusCode::OK_200, res->status);
  9884. }
  9885. EXPECT_EQ(1, request_count.load());
  9886. }
  9887. // Sends a raw request and verifies that there isn't a crash or exception.
  9888. static void test_raw_request(const std::string &req,
  9889. std::string *out = nullptr) {
  9890. Server svr;
  9891. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9892. res.set_content("ok", "text/plain");
  9893. });
  9894. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9895. res.set_content("ok", "text/plain");
  9896. });
  9897. svr.Get("/header_field_value_check",
  9898. [&](const Request & /*req*/, Response &res) {
  9899. res.set_content("ok", "text/plain");
  9900. });
  9901. svr.CustomRoute("PROPFIND", "/dav",
  9902. [&](const Request & /*req*/, Response &res) {
  9903. res.status = StatusCode::MultiStatus_207;
  9904. });
  9905. // Server read timeout must be longer than the client read timeout for the
  9906. // bug to reproduce, probably to force the server to process a request
  9907. // without a trailing blank line.
  9908. const time_t client_read_timeout_sec = 1;
  9909. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9910. bool listen_thread_ok = false;
  9911. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9912. auto se = detail::scope_exit([&] {
  9913. svr.stop();
  9914. t.join();
  9915. ASSERT_FALSE(svr.is_running());
  9916. EXPECT_TRUE(listen_thread_ok);
  9917. });
  9918. svr.wait_until_ready();
  9919. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9920. }
  9921. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9922. // A certain header line causes an exception if the header property is parsed
  9923. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9924. test_raw_request(
  9925. "GET /hi HTTP/1.1\r\n"
  9926. " : "
  9927. " "
  9928. " ");
  9929. }
  9930. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9931. // A certain header line causes an exception if the header property *name* is
  9932. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9933. // greedy matcher and requires backtracking when there are a lot of ":"
  9934. // characters.
  9935. // This occurs with libc++ but not libstdc++.
  9936. test_raw_request(
  9937. "GET /hi HTTP/1.1\r\n"
  9938. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9939. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9940. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9941. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9942. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9943. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9944. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9945. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9946. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9947. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9948. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9949. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9950. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9951. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9952. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9953. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9954. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9955. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9956. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9957. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9958. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9959. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9960. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9961. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9962. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9963. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9964. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9965. "&&&%%%");
  9966. }
  9967. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9968. // Make sure this doesn't crash the server.
  9969. // In a previous version of the header line regex, the "\r" rendered the line
  9970. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9971. // a new position where the leading white space ended and the field value
  9972. // began.
  9973. // The crash occurs with libc++ but not libstdc++.
  9974. test_raw_request("GET /hi HTTP/1.1\r\n"
  9975. "a:" +
  9976. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9977. "\r\n"
  9978. "\r\n");
  9979. }
  9980. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9981. const char *rejected[] = {
  9982. // RFC 9112 §3: one SP between the parts, and nothing else
  9983. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9984. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9985. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9986. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9987. // A request-target has no fragment
  9988. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9989. // An HTTP/1.1 request needs a Host
  9990. "GET /hi HTTP/1.1\r\n\r\n",
  9991. };
  9992. for (auto request : rejected) {
  9993. std::string out;
  9994. test_raw_request(request, &out);
  9995. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9996. }
  9997. std::string out;
  9998. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9999. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10000. }
  10001. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10002. // RFC 9112 §6.1
  10003. const char *requests[] = {
  10004. "PUT /put_hi HTTP/1.1\r\n"
  10005. "Host: localhost\r\n"
  10006. "Content-Length: 0\r\n"
  10007. "Transfer-Encoding: chunked\r\n"
  10008. "\r\n"
  10009. "0\r\n\r\n",
  10010. "PUT /put_hi HTTP/1.0\r\n"
  10011. "Connection: keep-alive\r\n"
  10012. "Transfer-Encoding: chunked\r\n"
  10013. "\r\n"
  10014. "0\r\n\r\n",
  10015. };
  10016. for (auto request : requests) {
  10017. std::string out;
  10018. test_raw_request(request, &out);
  10019. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10020. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10021. }
  10022. }
  10023. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10024. std::string out;
  10025. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10026. "Content-Type: text/plain\r\n"
  10027. "Transfer-Encoding: chunked\r\n"
  10028. "\r\n"
  10029. "nothex\r\n",
  10030. &out);
  10031. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10032. }
  10033. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10034. std::string out;
  10035. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10036. "Content-Type: text/plain\r\n"
  10037. "Transfer-Encoding: chunked\r\n"
  10038. "\r\n"
  10039. "3\r\n"
  10040. "xyz\r\n"
  10041. "NaN\r\n",
  10042. &out);
  10043. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10044. }
  10045. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10046. std::string out;
  10047. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10048. "Content-Type: text/plain\r\n"
  10049. "Transfer-Encoding: chunked\r\n"
  10050. "\r\n"
  10051. // Length is too large for 64 bits.
  10052. "1ffffffffffffffff\r\n"
  10053. "xyz\r\n",
  10054. &out);
  10055. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10056. }
  10057. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10058. test_raw_request("GET /hi HTTP/1.1\r\n"
  10059. "Content-Type: text/plain\r\n\r");
  10060. }
  10061. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10062. std::string out;
  10063. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10064. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10065. }
  10066. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10067. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10068. std::string out;
  10069. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10070. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10071. }
  10072. }
  10073. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10074. std::string out;
  10075. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10076. "Host: localhost\r\n"
  10077. "Connection: close\r\n\r\n",
  10078. &out);
  10079. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10080. }
  10081. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10082. Server svr;
  10083. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10084. EXPECT_TRUE(!req.remote_addr.empty());
  10085. });
  10086. thread t = thread([&] { svr.listen(HOST, PORT); });
  10087. auto se = detail::scope_exit([&] {
  10088. svr.stop();
  10089. t.join();
  10090. ASSERT_FALSE(svr.is_running());
  10091. });
  10092. svr.wait_until_ready();
  10093. // Send an invalid request line to trigger Bad Request
  10094. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10095. std::string out;
  10096. ASSERT_TRUE(send_request(5, bad_req, &out));
  10097. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10098. }
  10099. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10100. // answered right away rather than blocking on a read that waits for EOF.
  10101. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10102. std::string out;
  10103. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10104. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10105. }
  10106. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10107. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10108. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10109. for (const auto *method : methods) {
  10110. Server svr;
  10111. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10112. EXPECT_FALSE(svr.is_valid()) << method;
  10113. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10114. }
  10115. }
  10116. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10117. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10118. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10119. for (const auto *method : methods) {
  10120. Server svr;
  10121. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10122. EXPECT_FALSE(svr.is_valid()) << method;
  10123. }
  10124. }
  10125. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10126. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10127. "COPY", "MOVE", "LOCK",
  10128. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10129. Server svr;
  10130. for (const auto *method : methods) {
  10131. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10132. }
  10133. EXPECT_TRUE(svr.is_valid());
  10134. }
  10135. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10136. Server svr;
  10137. svr.CustomRoute("POST", "/x",
  10138. [](const Request &, Response &, const ContentReader &) {});
  10139. EXPECT_FALSE(svr.is_valid());
  10140. }
  10141. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10142. Server svr;
  10143. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10144. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10145. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10146. EXPECT_FALSE(svr.is_valid());
  10147. }
  10148. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10149. Server svr;
  10150. auto captured = Error::Success;
  10151. svr.set_error_logger(
  10152. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10153. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10154. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10155. }
  10156. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10157. std::string out;
  10158. std::string request(
  10159. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10160. test_raw_request(request, &out);
  10161. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10162. }
  10163. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10164. std::string out;
  10165. std::string request(
  10166. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10167. test_raw_request(request, &out);
  10168. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10169. }
  10170. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10171. std::string out;
  10172. std::string request(
  10173. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10174. test_raw_request(request, &out);
  10175. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10176. }
  10177. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10178. std::string out;
  10179. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10180. "Host: localhost\r\n"
  10181. "Test: \r\n\r\n",
  10182. &out);
  10183. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10184. }
  10185. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10186. Server svr;
  10187. std::string x_custom;
  10188. std::string cookie;
  10189. std::string xff;
  10190. std::string x_unicode;
  10191. std::string x_iis;
  10192. svr.Get("/check", [&](const Request &req, Response &res) {
  10193. x_custom = req.get_header_value("X-Custom");
  10194. cookie = req.get_header_value("Cookie");
  10195. xff = req.get_header_value("X-Forwarded-For");
  10196. x_unicode = req.get_header_value("X-Unicode");
  10197. x_iis = req.get_header_value("X-IIS");
  10198. res.set_content("ok", "text/plain");
  10199. });
  10200. thread t = thread([&] { svr.listen(HOST, PORT); });
  10201. auto se = detail::scope_exit([&] {
  10202. svr.stop();
  10203. t.join();
  10204. ASSERT_FALSE(svr.is_running());
  10205. });
  10206. svr.wait_until_ready();
  10207. const std::string req = "GET /check HTTP/1.1\r\n"
  10208. "Host: localhost\r\n"
  10209. "X-Custom: a%0D%0AInjected: b\r\n"
  10210. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10211. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10212. "X-Unicode: %E3%81%82\r\n"
  10213. "X-IIS: %u00E9\r\n"
  10214. "Connection: close\r\n"
  10215. "\r\n";
  10216. std::string res;
  10217. ASSERT_TRUE(send_request(5, req, &res));
  10218. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10219. // Every value must be returned verbatim (wire form), with no decoding.
  10220. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10221. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10222. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10223. EXPECT_EQ("%E3%81%82", x_unicode);
  10224. EXPECT_EQ("%u00E9", x_iis);
  10225. }
  10226. // Applications that previously relied on automatic percent-decoding can
  10227. // reproduce the old behavior by explicitly calling decode_path_component()
  10228. // or, for RFC 3986 conformance, decode_uri_component().
  10229. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10230. Server svr;
  10231. std::string decoded;
  10232. svr.Get("/check", [&](const Request &req, Response &res) {
  10233. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10234. res.set_content("ok", "text/plain");
  10235. });
  10236. thread t = thread([&] { svr.listen(HOST, PORT); });
  10237. auto se = detail::scope_exit([&] {
  10238. svr.stop();
  10239. t.join();
  10240. ASSERT_FALSE(svr.is_running());
  10241. });
  10242. svr.wait_until_ready();
  10243. const std::string req = "GET /check HTTP/1.1\r\n"
  10244. "Host: localhost\r\n"
  10245. "X-Custom: hello%20world\r\n"
  10246. "Connection: close\r\n"
  10247. "\r\n";
  10248. std::string res;
  10249. ASSERT_TRUE(send_request(5, req, &res));
  10250. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10251. EXPECT_EQ("hello world", decoded);
  10252. }
  10253. // Regression test for #2033. Browsers send Referer values that include
  10254. // percent-encoded characters such as %0A inside the URL. Decoding the
  10255. // header value would either trip the post-decode CR/LF/NUL guard (the
  10256. // original bug, returning 400) or, after that guard was relaxed, silently
  10257. // store a literal LF — both unacceptable. The wire form must round-trip.
  10258. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10259. Server svr;
  10260. std::string referer;
  10261. svr.Get("/check", [&](const Request &req, Response &res) {
  10262. referer = req.get_header_value("Referer");
  10263. res.set_content("ok", "text/plain");
  10264. });
  10265. thread t = thread([&] { svr.listen(HOST, PORT); });
  10266. auto se = detail::scope_exit([&] {
  10267. svr.stop();
  10268. t.join();
  10269. ASSERT_FALSE(svr.is_running());
  10270. });
  10271. svr.wait_until_ready();
  10272. const std::string req = "GET /check HTTP/1.1\r\n"
  10273. "Host: localhost\r\n"
  10274. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10275. "Connection: close\r\n"
  10276. "\r\n";
  10277. std::string res;
  10278. ASSERT_TRUE(send_request(5, req, &res));
  10279. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10280. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10281. }
  10282. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10283. Server svr;
  10284. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10285. res.set_header("Cache-Control", "no-cache");
  10286. res.set_chunked_content_provider(
  10287. "text/event-stream", [](size_t offset, DataSink &sink) {
  10288. std::string s = "data:";
  10289. s += std::to_string(offset);
  10290. s += "\n\n";
  10291. auto ret = sink.write(s.data(), s.size());
  10292. EXPECT_TRUE(ret);
  10293. std::this_thread::sleep_for(std::chrono::seconds(1));
  10294. return true;
  10295. });
  10296. });
  10297. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10298. svr.wait_until_ready();
  10299. Client client(HOST, PORT);
  10300. const Headers headers = {{"Accept", "text/event-stream"}};
  10301. auto get_thread = std::thread([&client, &headers]() {
  10302. auto res = client.Get(
  10303. "/events", headers,
  10304. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10305. });
  10306. auto se = detail::scope_exit([&] {
  10307. svr.stop();
  10308. get_thread.join();
  10309. listen_thread.join();
  10310. ASSERT_FALSE(svr.is_running());
  10311. });
  10312. // Give GET time to get a few messages.
  10313. std::this_thread::sleep_for(std::chrono::seconds(2));
  10314. }
  10315. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10316. httplib::Server svr;
  10317. svr.Post("/hi",
  10318. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10319. res.status = StatusCode::OK_200;
  10320. });
  10321. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10322. svr.wait_until_ready();
  10323. Client cli(HOST, PORT);
  10324. auto res = cli.Post("/hi", "data", "text/plain");
  10325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10326. EXPECT_EQ(StatusCode::OK_200, res->status);
  10327. svr.stop();
  10328. thread.join();
  10329. ASSERT_FALSE(svr.is_running());
  10330. res = cli.Post("/hi", "data", "text/plain");
  10331. ASSERT_FALSE(res);
  10332. }
  10333. TEST(ServerStopTest, ListenFailure) {
  10334. Server svr;
  10335. auto t = thread([&]() {
  10336. auto ret = svr.listen("????", PORT);
  10337. EXPECT_FALSE(ret);
  10338. });
  10339. svr.wait_until_ready();
  10340. svr.stop();
  10341. t.join();
  10342. }
  10343. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10344. TEST(ServerStopTest, Decommision) {
  10345. Server svr;
  10346. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10347. for (int i = 0; i < 4; i++) {
  10348. auto is_even = !(i % 2);
  10349. std::thread t{[&] {
  10350. try {
  10351. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10352. if (is_even) {
  10353. throw std::runtime_error("Some thing that happens to go wrong.");
  10354. }
  10355. svr.listen(HOST, PORT);
  10356. } catch (...) { svr.decommission(); }
  10357. }};
  10358. svr.wait_until_ready();
  10359. // Server is up
  10360. {
  10361. Client cli(HOST, PORT);
  10362. auto res = cli.Get("/hi");
  10363. if (is_even) {
  10364. EXPECT_FALSE(res);
  10365. } else {
  10366. EXPECT_TRUE(res);
  10367. EXPECT_EQ("hi...", res->body);
  10368. }
  10369. }
  10370. svr.stop();
  10371. t.join();
  10372. // Server is down...
  10373. {
  10374. Client cli(HOST, PORT);
  10375. auto res = cli.Get("/hi");
  10376. EXPECT_FALSE(res);
  10377. }
  10378. }
  10379. }
  10380. #endif
  10381. // Helper function for string body upload progress tests
  10382. template <typename SetupHandler, typename ClientCall>
  10383. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10384. ClientCall &&client_call,
  10385. const string &body) {
  10386. Server svr;
  10387. setup_handler(svr);
  10388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10389. auto se = detail::scope_exit([&] {
  10390. svr.stop();
  10391. t.join();
  10392. });
  10393. svr.wait_until_ready();
  10394. Client cli(HOST, PORT);
  10395. vector<uint64_t> progress_values;
  10396. bool progress_called = false;
  10397. auto res =
  10398. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10399. progress_values.push_back(current);
  10400. progress_called = true;
  10401. return true;
  10402. });
  10403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10404. EXPECT_EQ(200, res->status);
  10405. EXPECT_TRUE(progress_called);
  10406. }
  10407. TEST(UploadProgressTest, PostStringBodyBasic) {
  10408. TestStringBodyUploadProgress(
  10409. [](Server &svr) {
  10410. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10411. res.set_content("received", "text/plain");
  10412. });
  10413. },
  10414. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10415. return cli.Post("/test", body, "text/plain", progress_callback);
  10416. },
  10417. "test data for upload progress");
  10418. }
  10419. TEST(UploadProgressTest, PutStringBodyBasic) {
  10420. TestStringBodyUploadProgress(
  10421. [](Server &svr) {
  10422. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10423. res.set_content("put received", "text/plain");
  10424. });
  10425. },
  10426. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10427. return cli.Put("/test", body, "text/plain", progress_callback);
  10428. },
  10429. "put test data for upload progress");
  10430. }
  10431. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10432. TestStringBodyUploadProgress(
  10433. [](Server &svr) {
  10434. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10435. res.set_content("patch received", "text/plain");
  10436. });
  10437. },
  10438. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10439. return cli.Patch("/test", body, "text/plain", progress_callback);
  10440. },
  10441. "patch test data for upload progress");
  10442. }
  10443. // Helper function for content provider upload progress tests
  10444. template <typename SetupHandler, typename ClientCall>
  10445. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10446. ClientCall &&client_call) {
  10447. Server svr;
  10448. setup_handler(svr);
  10449. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10450. auto se = detail::scope_exit([&] {
  10451. svr.stop();
  10452. t.join();
  10453. });
  10454. svr.wait_until_ready();
  10455. Client cli(HOST, PORT);
  10456. vector<uint64_t> progress_values;
  10457. auto res =
  10458. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10459. progress_values.push_back(current);
  10460. return true;
  10461. });
  10462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10463. EXPECT_EQ(200, res->status);
  10464. EXPECT_FALSE(progress_values.empty());
  10465. }
  10466. TEST(UploadProgressTest, PostContentProviderProgress) {
  10467. TestContentProviderUploadProgress(
  10468. [](Server &svr) {
  10469. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10470. res.set_content("provider received", "text/plain");
  10471. });
  10472. },
  10473. [](Client &cli, UploadProgress progress_callback) {
  10474. return cli.Post(
  10475. "/test", 9,
  10476. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10477. sink.os << "test data";
  10478. return true;
  10479. },
  10480. "text/plain", progress_callback);
  10481. });
  10482. }
  10483. // Helper function for multipart upload progress tests
  10484. template <typename SetupHandler, typename ClientCall>
  10485. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10486. ClientCall &&client_call,
  10487. const string &endpoint) {
  10488. Server svr;
  10489. setup_handler(svr);
  10490. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10491. auto se = detail::scope_exit([&] {
  10492. svr.stop();
  10493. t.join();
  10494. });
  10495. svr.wait_until_ready();
  10496. Client cli(HOST, PORT);
  10497. vector<uint64_t> progress_values;
  10498. UploadFormDataItems items = {
  10499. {"field1", "value1", "", ""},
  10500. {"field2", "longer value for progress tracking test", "", ""},
  10501. {"file1", "file content data for upload progress", "test.txt",
  10502. "text/plain"}};
  10503. auto res = client_call(cli, endpoint, items,
  10504. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10505. progress_values.push_back(current);
  10506. return true;
  10507. });
  10508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10509. EXPECT_EQ(200, res->status);
  10510. EXPECT_FALSE(progress_values.empty());
  10511. }
  10512. TEST(UploadProgressTest, PostMultipartProgress) {
  10513. TestMultipartUploadProgress(
  10514. [](Server &svr) {
  10515. svr.Post("/multipart", [](const Request &req, Response &res) {
  10516. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10517. res.set_content("multipart received", "text/plain");
  10518. });
  10519. },
  10520. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10521. UploadProgress progress_callback) {
  10522. return cli.Post(endpoint, items, progress_callback);
  10523. },
  10524. "/multipart");
  10525. }
  10526. // Helper function for basic download progress tests
  10527. template <typename SetupHandler, typename ClientCall>
  10528. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10529. ClientCall &&client_call, const string &endpoint,
  10530. size_t expected_content_size) {
  10531. Server svr;
  10532. setup_handler(svr);
  10533. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10534. auto se = detail::scope_exit([&] {
  10535. svr.stop();
  10536. t.join();
  10537. });
  10538. svr.wait_until_ready();
  10539. Client cli(HOST, PORT);
  10540. vector<uint64_t> progress_values;
  10541. auto res = client_call(cli, endpoint,
  10542. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10543. progress_values.push_back(current);
  10544. return true;
  10545. });
  10546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10547. EXPECT_EQ(200, res->status);
  10548. EXPECT_FALSE(progress_values.empty());
  10549. EXPECT_EQ(expected_content_size, res->body.size());
  10550. }
  10551. TEST(DownloadProgressTest, GetBasic) {
  10552. TestBasicDownloadProgress(
  10553. [](Server &svr) {
  10554. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10555. string content(1000, 'D');
  10556. res.set_content(content, "text/plain");
  10557. });
  10558. },
  10559. [](Client &cli, const string &endpoint,
  10560. DownloadProgress progress_callback) {
  10561. return cli.Get(endpoint, progress_callback);
  10562. },
  10563. "/download", 1000u);
  10564. }
  10565. // Helper function for content receiver download progress tests
  10566. template <typename SetupHandler, typename ClientCall>
  10567. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10568. ClientCall &&client_call,
  10569. const string &endpoint,
  10570. size_t expected_content_size) {
  10571. Server svr;
  10572. setup_handler(svr);
  10573. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10574. auto se = detail::scope_exit([&] {
  10575. svr.stop();
  10576. t.join();
  10577. });
  10578. svr.wait_until_ready();
  10579. Client cli(HOST, PORT);
  10580. vector<uint64_t> progress_values;
  10581. string received_body;
  10582. auto res = client_call(
  10583. cli, endpoint,
  10584. [&](const char *data, size_t data_length) -> bool {
  10585. received_body.append(data, data_length);
  10586. return true;
  10587. },
  10588. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10589. progress_values.push_back(current);
  10590. return true;
  10591. });
  10592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10593. EXPECT_EQ(200, res->status);
  10594. EXPECT_FALSE(progress_values.empty());
  10595. EXPECT_EQ(expected_content_size, received_body.size());
  10596. EXPECT_TRUE(res->body.empty());
  10597. }
  10598. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10599. TestContentReceiverDownloadProgress(
  10600. [](Server &svr) {
  10601. svr.Get("/download-receiver",
  10602. [](const Request & /*req*/, Response &res) {
  10603. string content(2000, 'R');
  10604. res.set_content(content, "text/plain");
  10605. });
  10606. },
  10607. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10608. DownloadProgress progress_callback) {
  10609. return cli.Get(endpoint, content_receiver, progress_callback);
  10610. },
  10611. "/download-receiver", 2000u);
  10612. }
  10613. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10614. // A provider reaching a pass with nothing to hand over - an empty buffer
  10615. // popped off a queue, say - must not be taken to mean the body is finished.
  10616. // It used to end the loop with the terminating chunk unwritten while the
  10617. // server still considered the response complete, so the peer waited for an
  10618. // end that never arrived.
  10619. Server svr;
  10620. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10621. auto step = std::make_shared<int>(0);
  10622. res.set_chunked_content_provider("text/plain",
  10623. [step](size_t /*offset*/, DataSink &sink) {
  10624. switch ((*step)++) {
  10625. case 0: sink.write("", 0); break;
  10626. case 1: sink.write("hello", 5); break;
  10627. default: sink.done(); break;
  10628. }
  10629. return true;
  10630. });
  10631. });
  10632. auto port = svr.bind_to_any_port(HOST);
  10633. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10634. auto listen_se = detail::scope_exit([&] {
  10635. svr.stop();
  10636. listen_thread.join();
  10637. ASSERT_FALSE(svr.is_running());
  10638. });
  10639. svr.wait_until_ready();
  10640. Client cli(HOST, port);
  10641. // Without the fix the body is never terminated, so bound the wait rather
  10642. // than letting the test hang on the default read timeout.
  10643. cli.set_read_timeout(5, 0);
  10644. auto res = cli.Get("/stream");
  10645. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10646. EXPECT_EQ(StatusCode::OK_200, res->status);
  10647. EXPECT_EQ("hello", res->body);
  10648. }
  10649. TEST(StreamingTest, NoContentLengthStreaming) {
  10650. Server svr;
  10651. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10652. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10653. if (offset < 6) {
  10654. sink.os << (offset < 3 ? "a" : "b");
  10655. } else {
  10656. sink.done();
  10657. }
  10658. return true;
  10659. });
  10660. });
  10661. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10662. auto listen_se = detail::scope_exit([&] {
  10663. svr.stop();
  10664. listen_thread.join();
  10665. ASSERT_FALSE(svr.is_running());
  10666. });
  10667. svr.wait_until_ready();
  10668. Client client(HOST, PORT);
  10669. auto get_thread = std::thread([&client]() {
  10670. std::string s;
  10671. auto res =
  10672. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10673. s += std::string(data, len);
  10674. return true;
  10675. });
  10676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10677. EXPECT_EQ(StatusCode::OK_200, res->status);
  10678. EXPECT_EQ("aaabbb", s);
  10679. });
  10680. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10681. // Give GET time to get a few messages.
  10682. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10683. }
  10684. TEST(MountTest, Unmount) {
  10685. Server svr;
  10686. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10687. auto se = detail::scope_exit([&] {
  10688. svr.stop();
  10689. listen_thread.join();
  10690. ASSERT_FALSE(svr.is_running());
  10691. });
  10692. svr.wait_until_ready();
  10693. Client cli("localhost", PORT);
  10694. svr.set_mount_point("/mount2", "./www2");
  10695. auto res = cli.Get("/");
  10696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10697. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10698. res = cli.Get("/mount2/dir/test.html");
  10699. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10700. EXPECT_EQ(StatusCode::OK_200, res->status);
  10701. svr.set_mount_point("/", "./www");
  10702. res = cli.Get("/dir/");
  10703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10704. EXPECT_EQ(StatusCode::OK_200, res->status);
  10705. svr.remove_mount_point("/");
  10706. res = cli.Get("/dir/");
  10707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10709. svr.remove_mount_point("/mount2");
  10710. res = cli.Get("/mount2/dir/test.html");
  10711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10712. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10713. }
  10714. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10715. Server svr;
  10716. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10717. svr.Get("/api/hello", [](const Request &, Response &res) {
  10718. res.set_content("api", "text/plain");
  10719. });
  10720. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10721. auto se = detail::scope_exit([&] {
  10722. svr.stop();
  10723. listen_thread.join();
  10724. ASSERT_FALSE(svr.is_running());
  10725. });
  10726. svr.wait_until_ready();
  10727. Client cli(HOST, PORT);
  10728. auto res = cli.Get("/dir/test.html");
  10729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10730. EXPECT_EQ(StatusCode::OK_200, res->status);
  10731. res = cli.Get("/api/hello");
  10732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10733. EXPECT_EQ(StatusCode::OK_200, res->status);
  10734. EXPECT_EQ("api", res->body);
  10735. }
  10736. TEST(MountTest, PathSegmentBoundary) {
  10737. Server svr;
  10738. svr.set_mount_point("/mount2", "./www2");
  10739. svr.set_mount_point("/", "./www");
  10740. auto port = svr.bind_to_any_port(HOST);
  10741. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10742. auto se = detail::scope_exit([&] {
  10743. svr.stop();
  10744. listen_thread.join();
  10745. ASSERT_FALSE(svr.is_running());
  10746. });
  10747. svr.wait_until_ready();
  10748. Client cli(HOST, port);
  10749. auto res = cli.Get("/mount2/dir/test.html");
  10750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10751. EXPECT_EQ(StatusCode::OK_200, res->status);
  10752. // "/mount2" must not match part-way through a path segment.
  10753. res = cli.Get("/mount2dir/test.html");
  10754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10755. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10756. // A mount point ending in '/' keeps matching every path below it.
  10757. res = cli.Get("/dir/test.html");
  10758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10759. EXPECT_EQ(StatusCode::OK_200, res->status);
  10760. }
  10761. TEST(MountTest, Redicect) {
  10762. Server svr;
  10763. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10764. auto se = detail::scope_exit([&] {
  10765. svr.stop();
  10766. listen_thread.join();
  10767. ASSERT_FALSE(svr.is_running());
  10768. });
  10769. svr.set_mount_point("/", "./www");
  10770. svr.wait_until_ready();
  10771. Client cli("localhost", PORT);
  10772. auto res = cli.Get("/dir/");
  10773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10774. EXPECT_EQ(StatusCode::OK_200, res->status);
  10775. res = cli.Get("/dir");
  10776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10777. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10778. res = cli.Get("/file");
  10779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10780. EXPECT_EQ(StatusCode::OK_200, res->status);
  10781. res = cli.Get("/file/");
  10782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10783. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10784. cli.set_follow_location(true);
  10785. res = cli.Get("/dir");
  10786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10787. EXPECT_EQ(StatusCode::OK_200, res->status);
  10788. }
  10789. TEST(MountTest, MultibytesPathName) {
  10790. Server svr;
  10791. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10792. auto se = detail::scope_exit([&] {
  10793. svr.stop();
  10794. listen_thread.join();
  10795. ASSERT_FALSE(svr.is_running());
  10796. });
  10797. svr.set_mount_point("/", "./www");
  10798. svr.wait_until_ready();
  10799. Client cli("localhost", PORT);
  10800. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10802. EXPECT_EQ(StatusCode::OK_200, res->status);
  10803. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10804. }
  10805. // A mount point serves no path with an empty segment or one ending in '.' or
  10806. // a space, so a guard in the pre-routing handler sees the path of every file
  10807. // that is served
  10808. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10809. Server svr;
  10810. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10811. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10812. if (req.path == "/dir/test.html") {
  10813. res.status = StatusCode::Unauthorized_401;
  10814. return Server::HandlerResponse::Handled;
  10815. }
  10816. return Server::HandlerResponse::Unhandled;
  10817. });
  10818. auto port = svr.bind_to_any_port(HOST);
  10819. ASSERT_LT(0, port);
  10820. thread t = thread([&] { svr.listen_after_bind(); });
  10821. auto se = detail::scope_exit([&] {
  10822. svr.stop();
  10823. t.join();
  10824. ASSERT_FALSE(svr.is_running());
  10825. });
  10826. svr.wait_until_ready();
  10827. Client cli(HOST, port);
  10828. for (auto path :
  10829. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10830. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10831. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  10832. "/dir/test.html%3A%3A$DATA"}) {
  10833. SCOPED_TRACE(path);
  10834. auto res = cli.Get(path);
  10835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10836. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10837. }
  10838. }
  10839. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10840. Server svr;
  10841. svr.set_mount_point("/", "./www");
  10842. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10843. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10844. auto port = svr.bind_to_any_port(HOST);
  10845. ASSERT_GT(port, 0);
  10846. thread t = thread([&] { svr.listen_after_bind(); });
  10847. auto se = detail::scope_exit([&] {
  10848. svr.stop();
  10849. t.join();
  10850. ASSERT_FALSE(svr.is_running());
  10851. });
  10852. svr.wait_until_ready();
  10853. Client cli(HOST, port);
  10854. auto res = cli.Get("/dir/test.abcde");
  10855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10856. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10857. res = cli.Get("/dir/test.html");
  10858. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10859. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10860. }
  10861. #ifdef _WIN32
  10862. // Issue #2435: mmap::open() must succeed even when another handle holds
  10863. // the file open for writing (e.g. an active log file).
  10864. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10865. const char *path = "mmap_concurrent_writer_test.txt";
  10866. const char *content = "hello";
  10867. {
  10868. std::ofstream f(path, std::ios::binary);
  10869. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10870. }
  10871. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10872. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10873. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10874. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10875. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10876. detail::mmap m(path);
  10877. ASSERT_TRUE(m.is_open());
  10878. EXPECT_EQ(strlen(content), m.size());
  10879. char buf[8];
  10880. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10881. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10882. }
  10883. #endif
  10884. #ifndef _WIN32
  10885. // A directory or a device has no size to serve.
  10886. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10887. const char *path = "./mmap_not_regular_test_dir";
  10888. ASSERT_EQ(0, ::mkdir(path, 0755));
  10889. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10890. for (auto p : {path, "/dev/null"}) {
  10891. detail::mmap m(p);
  10892. EXPECT_FALSE(m.is_open()) << p;
  10893. EXPECT_EQ(0U, m.size()) << p;
  10894. }
  10895. Server svr;
  10896. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10897. res.set_file_content("/dev/null");
  10898. });
  10899. auto port = svr.bind_to_any_port(HOST);
  10900. thread t = thread([&] { svr.listen_after_bind(); });
  10901. auto se = detail::scope_exit([&] {
  10902. svr.stop();
  10903. t.join();
  10904. });
  10905. svr.wait_until_ready();
  10906. auto res = Client(HOST, port).Get("/null");
  10907. ASSERT_TRUE(res);
  10908. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10909. }
  10910. #endif
  10911. #ifdef __linux__
  10912. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10913. TEST(MmapTest, FileIsNotMapped) {
  10914. const char *path = "mmap_not_mapped_test.txt";
  10915. {
  10916. std::ofstream f(path, std::ios::binary);
  10917. f << "hello";
  10918. }
  10919. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10920. detail::mmap m(path);
  10921. ASSERT_TRUE(m.is_open());
  10922. std::ifstream maps("/proc/self/maps");
  10923. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10924. std::istreambuf_iterator<char>());
  10925. EXPECT_EQ(std::string::npos, mappings.find(path));
  10926. }
  10927. #endif
  10928. TEST(KeepAliveTest, ReadTimeout) {
  10929. Server svr;
  10930. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10931. std::this_thread::sleep_for(std::chrono::seconds(2));
  10932. res.set_content("a", "text/plain");
  10933. });
  10934. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10935. res.set_content("b", "text/plain");
  10936. });
  10937. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10938. auto se = detail::scope_exit([&] {
  10939. svr.stop();
  10940. listen_thread.join();
  10941. ASSERT_FALSE(svr.is_running());
  10942. });
  10943. svr.wait_until_ready();
  10944. Client cli("localhost", PORT);
  10945. cli.set_keep_alive(true);
  10946. cli.set_read_timeout(std::chrono::seconds(1));
  10947. auto resa = cli.Get("/a");
  10948. ASSERT_FALSE(resa);
  10949. EXPECT_EQ(Error::Read, resa.error());
  10950. auto resb = cli.Get("/b");
  10951. ASSERT_TRUE(resb);
  10952. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10953. EXPECT_EQ("b", resb->body);
  10954. }
  10955. TEST(KeepAliveTest, MaxCount) {
  10956. size_t keep_alive_max_count = 3;
  10957. Server svr;
  10958. svr.set_keep_alive_max_count(keep_alive_max_count);
  10959. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10960. res.set_content("Hello World!", "text/plain");
  10961. });
  10962. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10963. auto se = detail::scope_exit([&] {
  10964. svr.stop();
  10965. listen_thread.join();
  10966. ASSERT_FALSE(svr.is_running());
  10967. });
  10968. svr.wait_until_ready();
  10969. Client cli(HOST, PORT);
  10970. cli.set_keep_alive(true);
  10971. for (size_t i = 0; i < 5; i++) {
  10972. auto result = cli.Get("/hi");
  10973. ASSERT_TRUE(result);
  10974. EXPECT_EQ(StatusCode::OK_200, result->status);
  10975. if (i == keep_alive_max_count - 1) {
  10976. EXPECT_EQ("close", result->get_header_value("Connection"));
  10977. } else {
  10978. EXPECT_FALSE(result->has_header("Connection"));
  10979. }
  10980. }
  10981. }
  10982. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10983. // can pull the next one into the server's buffer. The server must serve it
  10984. // without waiting for the socket to become readable again. The keep-alive
  10985. // timeout outlasts the client's read timeout, so a request left waiting for it
  10986. // shows up as a missing response.
  10987. static void serve_pipelining_routes(Server &svr,
  10988. const std::function<void(int)> &client) {
  10989. svr.set_keep_alive_timeout(5);
  10990. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10991. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10992. });
  10993. svr.Post("/echo", [](const Request &req, Response &res) {
  10994. res.set_content("echo " + req.body, "text/plain");
  10995. });
  10996. auto port = svr.bind_to_any_port(HOST);
  10997. thread t = thread([&] { svr.listen_after_bind(); });
  10998. auto se = detail::scope_exit([&] {
  10999. svr.stop();
  11000. t.join();
  11001. });
  11002. svr.wait_until_ready();
  11003. client(port);
  11004. }
  11005. static std::string
  11006. send_pipelined_requests(const std::vector<std::string> &parts) {
  11007. Server svr;
  11008. std::string res;
  11009. serve_pipelining_routes(svr, [&](int port) {
  11010. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11011. });
  11012. return res;
  11013. }
  11014. static void expect_in_order(const std::string &res,
  11015. const std::vector<std::string> &bodies) {
  11016. size_t pos = 0;
  11017. for (const auto &body : bodies) {
  11018. pos = res.find(body, pos);
  11019. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11020. pos += body.size();
  11021. }
  11022. }
  11023. TEST(KeepAliveTest, PipelinedRequests) {
  11024. auto res = send_pipelined_requests(
  11025. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11026. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11027. "Content-Length: 4\r\n\r\nbody"
  11028. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11029. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11030. }
  11031. // The second request starts in the server's buffer and ends on the socket.
  11032. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11033. auto res =
  11034. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11035. "GET /hi/2 HTTP/1.1\r\nHo",
  11036. "st: localhost\r\nConnection: close\r\n\r\n"});
  11037. expect_in_order(res, {"hi 1", "hi 2"});
  11038. }
  11039. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11040. // CRLF after a body does not turn into a 400 for the next request.
  11041. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11042. auto res = send_pipelined_requests(
  11043. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11044. "Content-Length: 4\r\n\r\nbody\r\n"
  11045. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11046. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11047. expect_in_order(res, {"echo body", "hi 2"});
  11048. }
  11049. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11050. // must not be served as the next request.
  11051. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11052. auto res = send_pipelined_requests(
  11053. {"INVALID REQUEST LINE\r\n\r\n"
  11054. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11055. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11056. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11057. }
  11058. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11059. // Over TLS, the next request is held by the TLS library as already decrypted
  11060. // data rather than on the socket.
  11061. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11062. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11063. std::string res;
  11064. serve_pipelining_routes(svr, [&](int port) {
  11065. // One part, so all three requests arrive in one TLS record
  11066. EXPECT_TRUE(send_ssl_request_in_parts(
  11067. 2,
  11068. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11069. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11070. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11071. &res, port));
  11072. });
  11073. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11074. }
  11075. #endif
  11076. TEST(KeepAliveTest, Issue1041) {
  11077. Server svr;
  11078. svr.set_keep_alive_timeout(3);
  11079. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11080. res.set_content("Hello World!", "text/plain");
  11081. });
  11082. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11083. auto se = detail::scope_exit([&] {
  11084. svr.stop();
  11085. listen_thread.join();
  11086. ASSERT_FALSE(svr.is_running());
  11087. });
  11088. svr.wait_until_ready();
  11089. Client cli(HOST, PORT);
  11090. cli.set_keep_alive(true);
  11091. auto result = cli.Get("/hi");
  11092. ASSERT_TRUE(result);
  11093. EXPECT_EQ(StatusCode::OK_200, result->status);
  11094. std::this_thread::sleep_for(std::chrono::seconds(5));
  11095. result = cli.Get("/hi");
  11096. ASSERT_TRUE(result);
  11097. EXPECT_EQ(StatusCode::OK_200, result->status);
  11098. }
  11099. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11100. Server svr;
  11101. svr.set_keep_alive_max_count(0);
  11102. std::set<int> remote_ports;
  11103. svr.Get("/hi", [&](const Request &req, Response &res) {
  11104. remote_ports.insert(req.remote_port);
  11105. res.set_content("hi", "text/plain");
  11106. });
  11107. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11108. auto se = detail::scope_exit([&] {
  11109. svr.stop();
  11110. listen_thread.join();
  11111. ASSERT_FALSE(svr.is_running());
  11112. });
  11113. svr.wait_until_ready();
  11114. Client cli(HOST, PORT);
  11115. cli.set_keep_alive(true);
  11116. for (int i = 0; i < 3; i++) {
  11117. auto res = cli.Get("/hi");
  11118. ASSERT_TRUE(res);
  11119. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11120. }
  11121. // All three over one connection
  11122. EXPECT_EQ(1u, remote_ports.size());
  11123. }
  11124. TEST(KeepAliveTest, Issue1959) {
  11125. Server svr;
  11126. svr.set_keep_alive_timeout(5);
  11127. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11128. res.set_content("a", "text/plain");
  11129. });
  11130. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11131. auto se = detail::scope_exit([&] {
  11132. if (!svr.is_running()) return;
  11133. svr.stop();
  11134. listen_thread.join();
  11135. ASSERT_FALSE(svr.is_running());
  11136. });
  11137. svr.wait_until_ready();
  11138. Client cli("localhost", PORT);
  11139. cli.set_keep_alive(true);
  11140. using namespace std::chrono;
  11141. auto start = steady_clock::now();
  11142. cli.Get("/a");
  11143. svr.stop();
  11144. listen_thread.join();
  11145. auto end = steady_clock::now();
  11146. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11147. EXPECT_LT(elapsed, 5000);
  11148. }
  11149. #ifdef CPPHTTPLIB_SSL_ENABLED
  11150. TEST(KeepAliveTest, SSLClientReconnection) {
  11151. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11152. ASSERT_TRUE(svr.is_valid());
  11153. svr.set_keep_alive_timeout(1);
  11154. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11155. res.set_content("Hello World!", "text/plain");
  11156. });
  11157. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11158. auto se = detail::scope_exit([&] {
  11159. svr.stop();
  11160. listen_thread.join();
  11161. ASSERT_FALSE(svr.is_running());
  11162. });
  11163. svr.wait_until_ready();
  11164. SSLClient cli(HOST, PORT);
  11165. cli.enable_server_certificate_verification(false);
  11166. cli.set_keep_alive(true);
  11167. auto result = cli.Get("/hi");
  11168. ASSERT_TRUE(result);
  11169. EXPECT_EQ(StatusCode::OK_200, result->status);
  11170. result = cli.Get("/hi");
  11171. ASSERT_TRUE(result);
  11172. EXPECT_EQ(StatusCode::OK_200, result->status);
  11173. std::this_thread::sleep_for(std::chrono::seconds(2));
  11174. // Recoonect
  11175. result = cli.Get("/hi");
  11176. ASSERT_TRUE(result);
  11177. EXPECT_EQ(StatusCode::OK_200, result->status);
  11178. result = cli.Get("/hi");
  11179. ASSERT_TRUE(result);
  11180. EXPECT_EQ(StatusCode::OK_200, result->status);
  11181. }
  11182. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11183. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11184. ASSERT_TRUE(svr.is_valid());
  11185. svr.set_keep_alive_timeout(1);
  11186. std::string content = "reconnect";
  11187. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11188. res.set_content("Hello World!", "text/plain");
  11189. });
  11190. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11191. auto se = detail::scope_exit([&] {
  11192. svr.stop();
  11193. listen_thread.join();
  11194. ASSERT_FALSE(svr.is_running());
  11195. });
  11196. svr.wait_until_ready();
  11197. SSLClient cli(HOST, PORT);
  11198. cli.enable_server_certificate_verification(false);
  11199. cli.set_keep_alive(true);
  11200. auto result = cli.Post(
  11201. "/hi", content.size(),
  11202. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11203. sink.write(content.c_str(), content.size());
  11204. return true;
  11205. },
  11206. "text/plain");
  11207. ASSERT_TRUE(result);
  11208. EXPECT_EQ(200, result->status);
  11209. std::this_thread::sleep_for(std::chrono::seconds(2));
  11210. // Recoonect
  11211. result = cli.Post(
  11212. "/hi", content.size(),
  11213. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11214. sink.write(content.c_str(), content.size());
  11215. return true;
  11216. },
  11217. "text/plain");
  11218. ASSERT_TRUE(result);
  11219. EXPECT_EQ(200, result->status);
  11220. result = cli.Post(
  11221. "/hi", content.size(),
  11222. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11223. sink.write(content.c_str(), content.size());
  11224. return true;
  11225. },
  11226. "text/plain");
  11227. ASSERT_TRUE(result);
  11228. EXPECT_EQ(200, result->status);
  11229. }
  11230. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11231. using namespace httplib::tls;
  11232. {
  11233. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11234. ASSERT_TRUE(svr.is_valid());
  11235. svr.Get("/sni", [&](const Request &req, Response &res) {
  11236. std::string expected = req.sni();
  11237. EXPECT_EQ(expected, req.get_param_value("expected"));
  11238. res.set_content("ok", "text/plain");
  11239. });
  11240. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11241. auto se = detail::scope_exit([&] {
  11242. svr.stop();
  11243. listen_thread.join();
  11244. ASSERT_FALSE(svr.is_running());
  11245. });
  11246. svr.wait_until_ready();
  11247. {
  11248. SSLClient cli("localhost", PORT);
  11249. cli.enable_server_certificate_verification(false);
  11250. auto res = cli.Get("/sni?expected=localhost");
  11251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11252. }
  11253. {
  11254. SSLClient cli("::1", PORT);
  11255. cli.enable_server_certificate_verification(false);
  11256. auto res = cli.Get("/sni?expected=");
  11257. // NOTE: This may fail if the server is listening on IPv4 only
  11258. // (e.g., when localhost resolves to 127.0.0.1 only)
  11259. if (res) {
  11260. EXPECT_EQ(StatusCode::OK_200, res->status);
  11261. } else {
  11262. EXPECT_EQ(Error::Connection, res.error());
  11263. }
  11264. }
  11265. }
  11266. }
  11267. // The SNI of a failed handshake does not reach the next connection that the
  11268. // same worker thread serves
  11269. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11270. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11271. ASSERT_TRUE(svr.is_valid());
  11272. svr.new_task_queue = [] { return new ThreadPool(1); };
  11273. svr.Get("/sni", [](const Request &req, Response &res) {
  11274. res.set_content(req.sni(), "text/plain");
  11275. });
  11276. auto port = svr.bind_to_any_port("127.0.0.1");
  11277. ASSERT_LT(0, port);
  11278. thread t = thread([&] { svr.listen_after_bind(); });
  11279. auto se = detail::scope_exit([&] {
  11280. svr.stop();
  11281. t.join();
  11282. ASSERT_FALSE(svr.is_running());
  11283. });
  11284. svr.wait_until_ready();
  11285. {
  11286. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11287. SSLClient cli("localhost", port);
  11288. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11289. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11290. auto res = cli.Get("/sni");
  11291. ASSERT_FALSE(res);
  11292. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11293. }
  11294. // An IP host sends no SNI (RFC 6066)
  11295. SSLClient cli("127.0.0.1", port);
  11296. cli.enable_server_certificate_verification(false);
  11297. auto res = cli.Get("/sni");
  11298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11299. EXPECT_EQ("", res->body);
  11300. }
  11301. #endif
  11302. TEST(ClientProblemDetectionTest, ContentProvider) {
  11303. Server svr;
  11304. size_t content_length = 1024 * 1024;
  11305. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11306. res.set_content_provider(
  11307. content_length, "text/plain",
  11308. [&](size_t offset, size_t length, DataSink &sink) {
  11309. auto out_len = std::min(length, static_cast<size_t>(1024));
  11310. std::string out(out_len, '@');
  11311. sink.write(out.data(), out_len);
  11312. return offset < 4096;
  11313. },
  11314. [](bool success) { ASSERT_FALSE(success); });
  11315. });
  11316. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11317. res.set_content_provider(
  11318. 0, "text/plain",
  11319. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11320. EXPECT_TRUE(false);
  11321. return true;
  11322. },
  11323. [](bool success) { ASSERT_FALSE(success); });
  11324. });
  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.wait_until_ready();
  11332. Client cli("localhost", PORT);
  11333. {
  11334. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11335. size_t /*data_length*/) { return false; });
  11336. ASSERT_FALSE(res);
  11337. }
  11338. {
  11339. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11340. size_t /*data_length*/) { return false; });
  11341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11342. }
  11343. }
  11344. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11345. // A provider that reports success without writing anything and without
  11346. // calling done() used to be handed the same offset and length again on every
  11347. // pass, so it spun for as long as the peer stayed connected.
  11348. Server svr;
  11349. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11350. res.set_content("ok", "text/plain");
  11351. });
  11352. auto port = svr.bind_to_any_port(HOST);
  11353. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11354. auto se = detail::scope_exit([&] {
  11355. svr.stop();
  11356. listen_thread.join();
  11357. ASSERT_FALSE(svr.is_running());
  11358. });
  11359. svr.wait_until_ready();
  11360. std::atomic<int> call_count{0};
  11361. Client cli(HOST, port);
  11362. auto res = cli.Post(
  11363. "/", 1024,
  11364. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11365. // Give up after enough passes to show the spin, so that losing the
  11366. // check below fails this test instead of hanging it.
  11367. return ++call_count < 100;
  11368. },
  11369. "text/plain");
  11370. ASSERT_FALSE(res);
  11371. EXPECT_EQ(Error::Write, res.error());
  11372. EXPECT_EQ(1, call_count.load());
  11373. }
  11374. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11375. // A writer only has to assign `write`. The other three used to be left as
  11376. // empty std::functions, so a provider calling one threw
  11377. // std::bad_function_call out of the thread running it and took the whole
  11378. // process down.
  11379. DataSink sink;
  11380. std::string written;
  11381. sink.write = [&](const char *data, size_t data_len) {
  11382. written.append(data, data_len);
  11383. return true;
  11384. };
  11385. EXPECT_TRUE(sink.is_writable());
  11386. sink.done();
  11387. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11388. EXPECT_TRUE(written.empty());
  11389. }
  11390. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11391. // A sink that cannot carry trailers still has to finish.
  11392. DataSink sink;
  11393. auto done_count = 0;
  11394. sink.done = [&]() { done_count++; };
  11395. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11396. EXPECT_EQ(1, done_count);
  11397. }
  11398. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11399. Server svr;
  11400. const std::string body(4096, 'x');
  11401. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11402. res.set_content_provider(body.size(), "text/plain",
  11403. [&](size_t offset, size_t length, DataSink &sink) {
  11404. sink.write(body.data() + offset, length);
  11405. sink.done();
  11406. return true;
  11407. });
  11408. });
  11409. auto port = svr.bind_to_any_port(HOST);
  11410. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11411. auto se = detail::scope_exit([&] {
  11412. svr.stop();
  11413. listen_thread.join();
  11414. ASSERT_FALSE(svr.is_running());
  11415. });
  11416. svr.wait_until_ready();
  11417. Client cli(HOST, port);
  11418. auto res = cli.Get("/");
  11419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11420. EXPECT_EQ(StatusCode::OK_200, res->status);
  11421. EXPECT_EQ(body, res->body);
  11422. }
  11423. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11424. Server svr;
  11425. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11426. res.set_content_provider(
  11427. 1024, "text/plain",
  11428. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11429. sink.write("hello", 5);
  11430. sink.done(); // short of the 1024 bytes the response promised
  11431. return true;
  11432. });
  11433. });
  11434. auto port = svr.bind_to_any_port(HOST);
  11435. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11436. auto se = detail::scope_exit([&] {
  11437. svr.stop();
  11438. listen_thread.join();
  11439. ASSERT_FALSE(svr.is_running());
  11440. });
  11441. svr.wait_until_ready();
  11442. Client cli(HOST, port);
  11443. cli.set_read_timeout(5, 0);
  11444. // The response is short of its Content-Length, so the client cannot read a
  11445. // complete body. What matters is that this returns at all: a no-op done()
  11446. // would leave the writer looping over a provider that never makes progress.
  11447. auto res = cli.Get("/");
  11448. EXPECT_FALSE(res);
  11449. }
  11450. // Read as the next response by a peer that sees it after a framed body.
  11451. static const std::string smuggled_response =
  11452. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11453. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11454. Server svr;
  11455. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11456. res.set_content_provider(
  11457. 5, "text/plain",
  11458. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11459. auto data = "AAAAA" + smuggled_response;
  11460. sink.write(data.data(), data.size());
  11461. return true;
  11462. });
  11463. });
  11464. thread t = thread([&] { svr.listen(HOST, PORT); });
  11465. auto se = detail::scope_exit([&] {
  11466. svr.stop();
  11467. t.join();
  11468. ASSERT_FALSE(svr.is_running());
  11469. });
  11470. svr.wait_until_ready();
  11471. std::string resp;
  11472. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11473. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11474. resp.clear();
  11475. ASSERT_TRUE(send_request(
  11476. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11477. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11478. }
  11479. TEST(NoContentTest, BodyIsNotSent) {
  11480. Server svr;
  11481. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11482. res.status = StatusCode::NoContent_204;
  11483. res.set_content(smuggled_response, "text/plain");
  11484. });
  11485. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11486. res.status = StatusCode::NotModified_304;
  11487. res.set_chunked_content_provider(
  11488. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11489. sink.write(smuggled_response.data(), smuggled_response.size());
  11490. sink.done();
  11491. return true;
  11492. });
  11493. });
  11494. thread t = thread([&] { svr.listen(HOST, PORT); });
  11495. auto se = detail::scope_exit([&] {
  11496. svr.stop();
  11497. t.join();
  11498. ASSERT_FALSE(svr.is_running());
  11499. });
  11500. svr.wait_until_ready();
  11501. for (auto path : {"/204", "/304"}) {
  11502. std::string resp;
  11503. ASSERT_TRUE(send_request(
  11504. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11505. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11506. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11507. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11508. }
  11509. }
  11510. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11511. Server svr;
  11512. std::atomic<bool> smuggled(false);
  11513. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11514. res.set_content("ok", "text/plain");
  11515. });
  11516. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11517. smuggled = true;
  11518. });
  11519. auto port = svr.bind_to_any_port(HOST);
  11520. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11521. auto se = detail::scope_exit([&] {
  11522. svr.stop();
  11523. listen_thread.join();
  11524. ASSERT_FALSE(svr.is_running());
  11525. });
  11526. svr.wait_until_ready();
  11527. // What follows the body would be read as the next request.
  11528. Client cli(HOST, port);
  11529. auto res = cli.Post(
  11530. "/", 5,
  11531. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11532. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11533. sink.write(data.data(), data.size());
  11534. return true;
  11535. },
  11536. "text/plain");
  11537. ASSERT_FALSE(res);
  11538. EXPECT_EQ(Error::Write, res.error());
  11539. EXPECT_FALSE(smuggled);
  11540. }
  11541. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11542. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11543. // The compressed path builds the whole body before connecting, so this
  11544. // fails client-side and never reaches a server.
  11545. Client cli(HOST, PORT);
  11546. cli.set_compress(true);
  11547. auto res = cli.Post(
  11548. "/", 1024,
  11549. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11550. sink.write("hello", 5);
  11551. sink.done(); // short of the 1024 bytes the request announced
  11552. return true;
  11553. },
  11554. "text/plain");
  11555. ASSERT_FALSE(res);
  11556. EXPECT_EQ(Error::Write, res.error());
  11557. }
  11558. #endif
  11559. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11560. Server svr;
  11561. svr.set_error_handler([](Request const &, Response &res) -> void {
  11562. res.set_chunked_content_provider(
  11563. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11564. sink.os << "hello";
  11565. sink.os << "world";
  11566. sink.done();
  11567. return true;
  11568. });
  11569. });
  11570. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11571. auto se = detail::scope_exit([&] {
  11572. svr.stop();
  11573. listen_thread.join();
  11574. ASSERT_FALSE(svr.is_running());
  11575. });
  11576. svr.wait_until_ready();
  11577. Client cli("localhost", PORT);
  11578. auto res = cli.Get("/");
  11579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11580. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11581. EXPECT_EQ("helloworld", res->body);
  11582. }
  11583. // A body set after a content provider must replace it, not be sent through it.
  11584. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11585. Server svr;
  11586. svr.set_mount_point("/", "./www");
  11587. svr.set_file_request_handler([](const Request &req, Response &res) {
  11588. if (req.path == "/dir/test.html") {
  11589. res.status = StatusCode::Forbidden_403;
  11590. res.set_content(std::string(5000, 'D'), "text/plain");
  11591. } else if (req.path == "/file") {
  11592. res.status = StatusCode::Forbidden_403;
  11593. res.body = "Denied";
  11594. }
  11595. });
  11596. auto port = svr.bind_to_any_port(HOST);
  11597. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11598. auto se = detail::scope_exit([&] {
  11599. svr.stop();
  11600. t.join();
  11601. ASSERT_FALSE(svr.is_running());
  11602. });
  11603. svr.wait_until_ready();
  11604. Client cli(HOST, port);
  11605. {
  11606. auto res = cli.Get("/dir/test.html");
  11607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11608. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11609. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11610. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11611. }
  11612. {
  11613. auto res = cli.Get("/file");
  11614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11615. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11616. EXPECT_EQ("Denied", res->body);
  11617. }
  11618. {
  11619. auto res = cli.Get("/dir/index.html");
  11620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11621. EXPECT_EQ(StatusCode::OK_200, res->status);
  11622. EXPECT_EQ(0U, res->body.find("<html>"));
  11623. }
  11624. }
  11625. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11626. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11627. Server svr;
  11628. std::vector<bool> released;
  11629. std::mutex released_mutex;
  11630. auto releaser = [&](bool success) {
  11631. std::lock_guard<std::mutex> guard(released_mutex);
  11632. released.push_back(success);
  11633. };
  11634. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11635. return sink.write(&"hello"[offset], length);
  11636. };
  11637. svr.Get("/sized", [&](const Request &, Response &res) {
  11638. res.status = StatusCode::NotFound_404;
  11639. res.set_content_provider(5, "text/plain", provider, releaser);
  11640. });
  11641. svr.Get("/chunked", [&](const Request &, Response &res) {
  11642. res.status = StatusCode::ServiceUnavailable_503;
  11643. res.set_chunked_content_provider(
  11644. "text/plain",
  11645. [](size_t, DataSink &sink) {
  11646. sink.os << "chunk";
  11647. sink.done();
  11648. return true;
  11649. },
  11650. releaser);
  11651. });
  11652. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11653. res.set_content_provider(5, "text/plain", provider, releaser);
  11654. throw std::runtime_error("after the provider");
  11655. });
  11656. svr.set_error_handler([](const Request &req, Response &res) {
  11657. // Leave the exception handler's content to it.
  11658. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11659. res.set_content(std::string(1000, 'E'), "text/html");
  11660. return Server::HandlerResponse::Handled;
  11661. });
  11662. svr.set_exception_handler(
  11663. [](const Request &, Response &res, std::exception_ptr) {
  11664. res.status = StatusCode::InternalServerError_500;
  11665. res.set_content(std::string(1000, 'X'), "text/html");
  11666. });
  11667. auto port = svr.bind_to_any_port(HOST);
  11668. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11669. auto se = detail::scope_exit([&] {
  11670. svr.stop();
  11671. t.join();
  11672. ASSERT_FALSE(svr.is_running());
  11673. });
  11674. svr.wait_until_ready();
  11675. Client cli(HOST, port);
  11676. {
  11677. auto res = cli.Get("/sized");
  11678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11679. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11680. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11681. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11682. }
  11683. {
  11684. auto res = cli.Get("/chunked");
  11685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11686. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11687. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11688. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11689. }
  11690. {
  11691. auto res = cli.Get("/throw");
  11692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11693. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11694. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11695. }
  11696. std::lock_guard<std::mutex> guard(released_mutex);
  11697. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11698. }
  11699. #endif
  11700. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11701. Server svr;
  11702. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11703. return sink.write(&"abc"[offset], length);
  11704. };
  11705. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11706. res.set_file_content("./www/dir/test.html");
  11707. res.set_content("body", "text/plain");
  11708. });
  11709. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11710. res.set_content(std::string(100, 'B'), "text/plain");
  11711. res.set_file_content("./www/dir/test.html");
  11712. });
  11713. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11714. res.set_content(std::string(100, 'B'), "text/plain");
  11715. res.set_content_provider(3, "text/x-provider", abc);
  11716. });
  11717. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11718. res.set_content_provider(3, "text/x-provider", abc);
  11719. res.set_content(std::string(100, 'B'), "text/plain");
  11720. });
  11721. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11722. res.set_content_provider(3, "text/x-provider", abc);
  11723. res.set_file_content("./www/dir/test.html", "text/x-file");
  11724. });
  11725. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11726. res.set_file_content("./www/dir/test.html");
  11727. res.set_header("Content-Type", "text/x-handler");
  11728. });
  11729. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11730. res.set_content_provider(3, "text/plain", abc);
  11731. res.body = "direct";
  11732. });
  11733. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11734. res.set_file_content("./www/dir/test.html");
  11735. res.body = "direct";
  11736. });
  11737. auto port = svr.bind_to_any_port(HOST);
  11738. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11739. auto se = detail::scope_exit([&] {
  11740. svr.stop();
  11741. t.join();
  11742. ASSERT_FALSE(svr.is_running());
  11743. });
  11744. svr.wait_until_ready();
  11745. Client cli(HOST, port);
  11746. auto expect_body = [&](const char *path, const std::string &body,
  11747. const std::string &type) {
  11748. // Uncompressed, so Content-Length can be compared with the body.
  11749. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11750. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11751. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11752. EXPECT_EQ(body, res->body) << path;
  11753. EXPECT_EQ(std::to_string(body.size()),
  11754. res->get_header_value("Content-Length"))
  11755. << path;
  11756. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11757. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11758. };
  11759. expect_body("/file-then-body", "body", "text/plain");
  11760. expect_body("/body-then-file", "test.html", "text/html");
  11761. expect_body("/body-then-provider", "abc", "text/x-provider");
  11762. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11763. expect_body("/provider-then-file", "test.html", "text/x-file");
  11764. expect_body("/file-then-header", "test.html", "text/x-handler");
  11765. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11766. expect_body("/file-then-direct-body", "direct", "text/plain");
  11767. // Ranges are checked against the body, not the dropped provider.
  11768. {
  11769. auto res = cli.Get("/provider-then-direct-body",
  11770. Headers{{make_range_header({{1, 2}})}});
  11771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11772. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11773. EXPECT_EQ("ir", res->body);
  11774. }
  11775. {
  11776. auto res = cli.Get("/file-then-direct-body",
  11777. Headers{{make_range_header({{7, 8}})}});
  11778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11779. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11780. }
  11781. }
  11782. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11783. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11784. const char *path = "./truncated_while_served.txt";
  11785. const size_t size = 32 * 1024 * 1024;
  11786. {
  11787. std::ofstream f(path, std::ios::binary);
  11788. f << std::string(size, 'x');
  11789. }
  11790. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11791. // Over TLS, where the bytes are encrypted in this process rather than
  11792. // copied by send().
  11793. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11794. svr.Get("/file", [&](const Request &, Response &res) {
  11795. res.set_file_content(path, "text/plain");
  11796. });
  11797. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11798. auto se = detail::scope_exit([&] {
  11799. svr.stop();
  11800. thread.join();
  11801. ASSERT_FALSE(svr.is_running());
  11802. });
  11803. svr.wait_until_ready();
  11804. // The file shrinks once the first bytes are in, as a rewrite in place
  11805. // would, and reading the mapping past its new end used to raise SIGBUS.
  11806. SSLClient cli(HOST, PORT);
  11807. cli.enable_server_certificate_verification(false);
  11808. size_t received = 0;
  11809. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11810. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11811. received += len;
  11812. return true;
  11813. });
  11814. EXPECT_FALSE(res);
  11815. EXPECT_LT(received, size);
  11816. }
  11817. #endif
  11818. // Forward declaration (see the base64_encode note).
  11819. namespace httplib {
  11820. namespace detail {
  11821. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11822. const std::string &content_type,
  11823. EncodingType encoding);
  11824. } // namespace detail
  11825. } // namespace httplib
  11826. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11827. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11828. ASSERT_TRUE(mm->is_open());
  11829. Response res;
  11830. detail::set_file_content_provider(res, mm, "text/html",
  11831. detail::EncodingType::None);
  11832. std::string out;
  11833. DataSink sink;
  11834. sink.write = [&](const char *d, size_t l) {
  11835. out.append(d, l);
  11836. return true;
  11837. };
  11838. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11839. EXPECT_EQ("test.html", out);
  11840. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11841. EXPECT_EQ("test.html", out);
  11842. }
  11843. TEST(LongPollingTest, ClientCloseDetection) {
  11844. Server svr;
  11845. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11846. res.set_chunked_content_provider(
  11847. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11848. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11849. sink.os << "hello";
  11850. auto count = 10;
  11851. while (count > 0 && sink.is_writable()) {
  11852. this_thread::sleep_for(chrono::milliseconds(10));
  11853. count--;
  11854. }
  11855. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11856. return true;
  11857. });
  11858. });
  11859. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11860. auto se = detail::scope_exit([&] {
  11861. svr.stop();
  11862. listen_thread.join();
  11863. ASSERT_FALSE(svr.is_running());
  11864. });
  11865. svr.wait_until_ready();
  11866. Client cli("localhost", PORT);
  11867. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11868. EXPECT_EQ("hello", string(data, data_length));
  11869. return false; // close the socket immediately.
  11870. });
  11871. ASSERT_FALSE(res);
  11872. }
  11873. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11874. Server svr;
  11875. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11876. res.set_chunked_content_provider(
  11877. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11878. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11879. sink.os << "hello";
  11880. EXPECT_TRUE(sink.os.good());
  11881. // Wait for the client to close the connection
  11882. auto count = 10;
  11883. while (count > 0 && sink.is_writable()) {
  11884. this_thread::sleep_for(chrono::milliseconds(10));
  11885. count--;
  11886. }
  11887. // After client disconnect, write repeatedly until the socket
  11888. // write actually fails (small writes may be absorbed by the
  11889. // kernel buffer)
  11890. std::string chunk(1024, 'x');
  11891. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11892. sink.os << chunk;
  11893. }
  11894. EXPECT_TRUE(sink.os.fail());
  11895. return true;
  11896. });
  11897. });
  11898. auto port = svr.bind_to_any_port("localhost");
  11899. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11900. auto se = detail::scope_exit([&] {
  11901. svr.stop();
  11902. listen_thread.join();
  11903. ASSERT_FALSE(svr.is_running());
  11904. });
  11905. svr.wait_until_ready();
  11906. Client cli("localhost", port);
  11907. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11908. EXPECT_EQ("hello", string(data, data_length));
  11909. return false; // close the socket immediately.
  11910. });
  11911. ASSERT_FALSE(res);
  11912. }
  11913. TEST(GetWithParametersTest, GetWithParameters) {
  11914. Server svr;
  11915. svr.Get("/", [&](const Request &req, Response &) {
  11916. EXPECT_EQ("world", req.get_param_value("hello"));
  11917. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11918. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11919. });
  11920. svr.Get("/params", [&](const Request &req, Response &) {
  11921. EXPECT_EQ("world", req.get_param_value("hello"));
  11922. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11923. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11924. });
  11925. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11926. EXPECT_EQ("resource-id", req.matches[1]);
  11927. EXPECT_EQ("foo", req.get_param_value("param1"));
  11928. EXPECT_EQ("bar", req.get_param_value("param2"));
  11929. });
  11930. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11931. EXPECT_EQ("user-id", req.path_params.at("id"));
  11932. EXPECT_EQ("foo", req.get_param_value("param1"));
  11933. EXPECT_EQ("bar", req.get_param_value("param2"));
  11934. });
  11935. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11936. auto se = detail::scope_exit([&] {
  11937. svr.stop();
  11938. listen_thread.join();
  11939. ASSERT_FALSE(svr.is_running());
  11940. });
  11941. svr.wait_until_ready();
  11942. {
  11943. Client cli(HOST, PORT);
  11944. Params params;
  11945. params.emplace("hello", "world");
  11946. params.emplace("hello2", "world2");
  11947. params.emplace("hello3", "world3");
  11948. auto res = cli.Get("/", params, Headers{});
  11949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11950. EXPECT_EQ(StatusCode::OK_200, res->status);
  11951. }
  11952. {
  11953. Client cli(HOST, PORT);
  11954. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11956. EXPECT_EQ(StatusCode::OK_200, res->status);
  11957. }
  11958. {
  11959. Client cli(HOST, PORT);
  11960. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11962. EXPECT_EQ(StatusCode::OK_200, res->status);
  11963. }
  11964. {
  11965. Client cli(HOST, PORT);
  11966. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11968. EXPECT_EQ(StatusCode::OK_200, res->status);
  11969. }
  11970. }
  11971. TEST(GetWithParametersTest, GetWithParameters2) {
  11972. Server svr;
  11973. svr.Get("/", [&](const Request &req, Response &res) {
  11974. auto text = req.get_param_value("hello");
  11975. res.set_content(text, "text/plain");
  11976. });
  11977. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11978. auto se = detail::scope_exit([&] {
  11979. svr.stop();
  11980. listen_thread.join();
  11981. ASSERT_FALSE(svr.is_running());
  11982. });
  11983. svr.wait_until_ready();
  11984. Client cli("localhost", PORT);
  11985. Params params;
  11986. params.emplace("hello", "world");
  11987. std::string body;
  11988. auto res = cli.Get("/", params, Headers{},
  11989. [&](const char *data, size_t data_length) {
  11990. body.append(data, data_length);
  11991. return true;
  11992. });
  11993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11994. EXPECT_EQ(StatusCode::OK_200, res->status);
  11995. EXPECT_EQ("world", body);
  11996. }
  11997. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11998. Server svr;
  11999. svr.Get("/search", [&](const Request &req, Response &res) {
  12000. auto q = req.get_param_value("q");
  12001. res.set_content(q, "text/plain");
  12002. });
  12003. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12004. auto se = detail::scope_exit([&] {
  12005. svr.stop();
  12006. listen_thread.join();
  12007. ASSERT_FALSE(svr.is_running());
  12008. });
  12009. svr.wait_until_ready();
  12010. Client cli("localhost", PORT);
  12011. // Verify that Get(path, params) works without requiring Headers argument
  12012. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12014. EXPECT_EQ(StatusCode::OK_200, res->status);
  12015. EXPECT_EQ("cpp-httplib", res->body);
  12016. }
  12017. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12018. auto host = "httpbingo.org";
  12019. auto path = std::string{"/range/32"};
  12020. #ifdef CPPHTTPLIB_SSL_ENABLED
  12021. SSLClient cli(host);
  12022. #else
  12023. Client cli(host);
  12024. #endif
  12025. cli.set_default_headers({make_range_header({{1, 10}})});
  12026. cli.set_connection_timeout(5);
  12027. {
  12028. auto res = cli.Get(path);
  12029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12030. EXPECT_EQ("bcdefghijk", res->body);
  12031. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12032. }
  12033. {
  12034. auto res = cli.Get(path);
  12035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12036. EXPECT_EQ("bcdefghijk", res->body);
  12037. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12038. }
  12039. }
  12040. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12041. Server svr;
  12042. svr.set_default_headers({{"Hello", "World"}});
  12043. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12044. res.set_content("ok", "text/plain");
  12045. });
  12046. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12047. auto se = detail::scope_exit([&] {
  12048. svr.stop();
  12049. listen_thread.join();
  12050. ASSERT_FALSE(svr.is_running());
  12051. });
  12052. svr.wait_until_ready();
  12053. Client cli("localhost", PORT);
  12054. auto res = cli.Get("/");
  12055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12056. EXPECT_EQ(StatusCode::OK_200, res->status);
  12057. EXPECT_EQ("ok", res->body);
  12058. EXPECT_EQ("World", res->get_header_value("Hello"));
  12059. }
  12060. #ifdef CPPHTTPLIB_SSL_ENABLED
  12061. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12062. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12063. ASSERT_TRUE(svr.is_valid());
  12064. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12065. std::this_thread::sleep_for(std::chrono::seconds(2));
  12066. res.set_content("a", "text/plain");
  12067. });
  12068. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12069. res.set_content("b", "text/plain");
  12070. });
  12071. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12072. auto se = detail::scope_exit([&] {
  12073. svr.stop();
  12074. listen_thread.join();
  12075. ASSERT_FALSE(svr.is_running());
  12076. });
  12077. svr.wait_until_ready();
  12078. SSLClient cli("localhost", PORT);
  12079. cli.enable_server_certificate_verification(false);
  12080. cli.set_keep_alive(true);
  12081. cli.set_read_timeout(std::chrono::seconds(1));
  12082. auto resa = cli.Get("/a");
  12083. ASSERT_TRUE(!resa);
  12084. EXPECT_EQ(Error::Read, resa.error());
  12085. auto resb = cli.Get("/b");
  12086. ASSERT_TRUE(resb);
  12087. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12088. EXPECT_EQ("b", resb->body);
  12089. }
  12090. // Closing an idle keep-alive connection sends close_notify and returns. The
  12091. // server must not wait for the client's close_notify: an idle client never
  12092. // sends one, so the worker would be held until the read timeout expires, and
  12093. // stop() would wait for it.
  12094. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12095. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12096. ASSERT_TRUE(svr.is_valid());
  12097. svr.set_keep_alive_timeout(1);
  12098. svr.set_read_timeout(10, 0);
  12099. svr.Get("/", [](const Request &, Response &res) {
  12100. res.set_content("ok", "text/plain");
  12101. });
  12102. auto port = svr.bind_to_any_port(HOST);
  12103. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12104. auto se = detail::scope_exit([&] {
  12105. if (listen_thread.joinable()) {
  12106. svr.stop();
  12107. listen_thread.join();
  12108. }
  12109. });
  12110. svr.wait_until_ready();
  12111. SSLClient cli(HOST, port);
  12112. cli.enable_server_certificate_verification(false);
  12113. cli.set_keep_alive(true);
  12114. auto res = cli.Get("/");
  12115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12116. EXPECT_EQ(StatusCode::OK_200, res->status);
  12117. // Stay idle past the keep-alive timeout so the server closes the connection.
  12118. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12119. auto start = std::chrono::steady_clock::now();
  12120. svr.stop();
  12121. listen_thread.join();
  12122. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12123. std::chrono::steady_clock::now() - start)
  12124. .count();
  12125. EXPECT_LT(elapsed, 3000);
  12126. }
  12127. #endif
  12128. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12129. protected:
  12130. ServerTestWithAI_PASSIVE()
  12131. : cli_(HOST, PORT)
  12132. #ifdef CPPHTTPLIB_SSL_ENABLED
  12133. ,
  12134. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12135. #endif
  12136. {
  12137. #ifdef CPPHTTPLIB_SSL_ENABLED
  12138. cli_.enable_server_certificate_verification(false);
  12139. #endif
  12140. }
  12141. virtual void SetUp() {
  12142. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12143. res.set_content("Hello World!", "text/plain");
  12144. });
  12145. t_ = thread(
  12146. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12147. svr_.wait_until_ready();
  12148. }
  12149. virtual void TearDown() {
  12150. svr_.stop();
  12151. t_.join();
  12152. }
  12153. #ifdef CPPHTTPLIB_SSL_ENABLED
  12154. SSLClient cli_;
  12155. SSLServer svr_;
  12156. #else
  12157. Client cli_;
  12158. Server svr_;
  12159. #endif
  12160. thread t_;
  12161. };
  12162. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12163. auto res = cli_.Get("/hi");
  12164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12165. EXPECT_EQ(StatusCode::OK_200, res->status);
  12166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12167. EXPECT_EQ("Hello World!", res->body);
  12168. }
  12169. class ServerUpDownTest : public ::testing::Test {
  12170. protected:
  12171. ServerUpDownTest() : cli_(HOST, PORT) {}
  12172. virtual void SetUp() {
  12173. t_ = thread([&]() {
  12174. svr_.bind_to_any_port(HOST);
  12175. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12176. ASSERT_TRUE(svr_.listen_after_bind());
  12177. });
  12178. svr_.wait_until_ready();
  12179. }
  12180. virtual void TearDown() {
  12181. svr_.stop();
  12182. t_.join();
  12183. }
  12184. Client cli_;
  12185. Server svr_;
  12186. thread t_;
  12187. };
  12188. TEST_F(ServerUpDownTest, QuickStartStop) {
  12189. // Should not crash, especially when run with
  12190. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12191. }
  12192. class PayloadMaxLengthTest : public ::testing::Test {
  12193. protected:
  12194. PayloadMaxLengthTest()
  12195. : cli_(HOST, PORT)
  12196. #ifdef CPPHTTPLIB_SSL_ENABLED
  12197. ,
  12198. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12199. #endif
  12200. {
  12201. #ifdef CPPHTTPLIB_SSL_ENABLED
  12202. cli_.enable_server_certificate_verification(false);
  12203. #endif
  12204. }
  12205. virtual void SetUp() {
  12206. svr_.set_payload_max_length(8);
  12207. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12208. res.set_content("test", "text/plain");
  12209. });
  12210. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12211. svr_.wait_until_ready();
  12212. }
  12213. virtual void TearDown() {
  12214. svr_.stop();
  12215. t_.join();
  12216. }
  12217. #ifdef CPPHTTPLIB_SSL_ENABLED
  12218. SSLClient cli_;
  12219. SSLServer svr_;
  12220. #else
  12221. Client cli_;
  12222. Server svr_;
  12223. #endif
  12224. thread t_;
  12225. };
  12226. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12227. auto res = cli_.Post("/test", "123456789", "text/plain");
  12228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12229. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12230. res = cli_.Post("/test", "12345678", "text/plain");
  12231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12232. EXPECT_EQ(StatusCode::OK_200, res->status);
  12233. }
  12234. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12235. // Test chunked encoding with payload exceeding the 8-byte limit
  12236. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12237. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12239. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12240. }
  12241. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12242. // Test chunked encoding with payload within the 8-byte limit
  12243. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12244. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12246. EXPECT_EQ(StatusCode::OK_200, res->status);
  12247. }
  12248. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12249. // Test using send_request to send chunked data exceeding payload limit
  12250. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12251. "Host: " +
  12252. std::string(HOST) + ":" + std::to_string(PORT) +
  12253. "\r\n"
  12254. "Transfer-Encoding: chunked\r\n"
  12255. "Connection: close\r\n"
  12256. "\r\n"
  12257. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12258. "0123456789\r\n"
  12259. "0\r\n" // End chunk
  12260. "\r\n";
  12261. std::string response;
  12262. bool result = send_request(1, chunked_request, &response);
  12263. if (!result) {
  12264. // If send_request fails, it might be because the server closed the
  12265. // connection due to payload limit enforcement, which is acceptable
  12266. SUCCEED()
  12267. << "Server rejected oversized chunked request (connection closed)";
  12268. } else {
  12269. // If we got a response, check if it's an error response or connection was
  12270. // closed early Short response length indicates connection was closed due to
  12271. // payload limit
  12272. if (response.length() <= 10) {
  12273. SUCCEED() << "Server closed connection for oversized chunked request";
  12274. } else {
  12275. // Check for error status codes
  12276. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12277. response.find("Payload Too Large") != std::string::npos ||
  12278. response.find("400") != std::string::npos);
  12279. }
  12280. }
  12281. }
  12282. class LargePayloadMaxLengthTest : public ::testing::Test {
  12283. protected:
  12284. LargePayloadMaxLengthTest()
  12285. : cli_(HOST, PORT)
  12286. #ifdef CPPHTTPLIB_SSL_ENABLED
  12287. ,
  12288. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12289. #endif
  12290. {
  12291. #ifdef CPPHTTPLIB_SSL_ENABLED
  12292. cli_.enable_server_certificate_verification(false);
  12293. #endif
  12294. }
  12295. virtual void SetUp() {
  12296. // Set 10MB payload limit
  12297. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12298. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12299. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12300. res.set_content("Large payload test", "text/plain");
  12301. });
  12302. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12303. svr_.wait_until_ready();
  12304. }
  12305. virtual void TearDown() {
  12306. svr_.stop();
  12307. t_.join();
  12308. }
  12309. #ifdef CPPHTTPLIB_SSL_ENABLED
  12310. SSLClient cli_;
  12311. SSLServer svr_;
  12312. #else
  12313. Client cli_;
  12314. Server svr_;
  12315. #endif
  12316. thread t_;
  12317. };
  12318. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12319. // Test chunked encoding with payload within 10MB limit
  12320. std::string medium_payload(5 * 1024 * 1024,
  12321. 'A'); // 5MB payload, within 10MB limit
  12322. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12324. EXPECT_EQ(StatusCode::OK_200, res->status);
  12325. }
  12326. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12327. // Test chunked encoding with payload exceeding 10MB limit
  12328. std::string large_payload(12 * 1024 * 1024,
  12329. 'B'); // 12MB payload, exceeds 10MB limit
  12330. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12331. // Server may either return 413 or close the connection
  12332. if (res) {
  12333. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12334. } else {
  12335. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12336. }
  12337. }
  12338. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12339. Server svr;
  12340. svr.Get("/", [](const Request &, Response &res) {
  12341. // Claims the most the client accepts, far more than it sends, then drops
  12342. // the connection.
  12343. res.set_content_provider(std::string().max_size(), "text/plain",
  12344. [](size_t, size_t, DataSink &sink) {
  12345. sink.write("abc", 3);
  12346. return false;
  12347. });
  12348. });
  12349. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12350. auto se = detail::scope_exit([&] {
  12351. svr.stop();
  12352. thread.join();
  12353. ASSERT_FALSE(svr.is_running());
  12354. });
  12355. svr.wait_until_ready();
  12356. Client cli(HOST, PORT);
  12357. cli.set_payload_max_length(0);
  12358. EXPECT_FALSE(cli.Get("/"));
  12359. }
  12360. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12361. // Stream API does, not as a plain read failure
  12362. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12363. Server svr;
  12364. svr.Get("/big", [](const Request &, Response &res) {
  12365. res.set_content(std::string(100000, 'b'), "text/plain");
  12366. });
  12367. auto port = svr.bind_to_any_port(HOST);
  12368. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12369. auto se = detail::scope_exit([&] {
  12370. svr.stop();
  12371. thread.join();
  12372. });
  12373. svr.wait_until_ready();
  12374. Client cli(HOST, port);
  12375. cli.set_payload_max_length(1000);
  12376. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12377. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12378. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12379. [](const char *, size_t) { return true; });
  12380. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12381. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12382. // Small on the wire, over the limit once decompressed
  12383. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12384. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12385. #endif
  12386. }
  12387. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12388. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12389. // path.
  12390. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12391. Server svr;
  12392. const size_t LIMIT = 64 * 1024; // 64KB
  12393. svr.set_payload_max_length(LIMIT);
  12394. size_t total = 0;
  12395. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12396. const ContentReader &content_reader) {
  12397. content_reader([&](const char * /*data*/, size_t len) {
  12398. total += len;
  12399. return true;
  12400. });
  12401. res.status = 200;
  12402. res.set_content("stream_ok", "text/plain");
  12403. });
  12404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12405. auto se = detail::scope_exit([&] {
  12406. svr.stop();
  12407. thread.join();
  12408. ASSERT_FALSE(svr.is_running());
  12409. });
  12410. svr.wait_until_ready();
  12411. // Prepare 256KB raw data and gzip-compress it
  12412. std::string raw(256 * 1024, 'A');
  12413. std::string gz;
  12414. {
  12415. z_stream zs{};
  12416. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12417. Z_DEFAULT_STRATEGY);
  12418. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12419. zs.avail_in = static_cast<uInt>(raw.size());
  12420. char outbuf[4096];
  12421. int ret;
  12422. do {
  12423. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12424. zs.avail_out = sizeof(outbuf);
  12425. ret = deflate(&zs, Z_FINISH);
  12426. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12427. } while (ret != Z_STREAM_END);
  12428. deflateEnd(&zs);
  12429. }
  12430. Client cli(HOST, PORT);
  12431. cli.set_connection_timeout(std::chrono::seconds(5));
  12432. Headers headers = {{"Content-Encoding", "gzip"}};
  12433. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12434. "application/octet-stream");
  12435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12436. // Server must reject oversized decompressed payloads with 413.
  12437. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12438. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12439. EXPECT_LE(total, LIMIT);
  12440. }
  12441. #endif
  12442. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12443. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12444. // the payload must be passed through untouched instead of being rejected.
  12445. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12446. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12447. Server svr;
  12448. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12449. res.set_content(body, "image/jpeg");
  12450. res.set_header("Content-Encoding", "UTF-8");
  12451. });
  12452. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12453. res.set_content(body, "image/jpeg");
  12454. res.set_header("Content-Encoding", "identity");
  12455. });
  12456. svr.Post("/echo", [](const Request &req, Response &res) {
  12457. res.set_content(req.body, "image/jpeg");
  12458. });
  12459. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12460. auto se = detail::scope_exit([&] {
  12461. svr.stop();
  12462. t.join();
  12463. ASSERT_FALSE(svr.is_running());
  12464. });
  12465. svr.wait_until_ready();
  12466. Client cli(HOST, PORT);
  12467. {
  12468. auto res = cli.Get("/image");
  12469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12470. EXPECT_EQ(StatusCode::OK_200, res->status);
  12471. EXPECT_EQ(body, res->body);
  12472. }
  12473. {
  12474. auto res = cli.Get("/identity");
  12475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12476. EXPECT_EQ(StatusCode::OK_200, res->status);
  12477. EXPECT_EQ(body, res->body);
  12478. }
  12479. {
  12480. // The same applies to a request body reaching the server.
  12481. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12482. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12484. EXPECT_EQ(StatusCode::OK_200, res->status);
  12485. EXPECT_EQ(body, res->body);
  12486. }
  12487. }
  12488. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12489. // gzip-encoded response even when the build has no zlib support.
  12490. static const char GZIPPED_HELLO_WORLD[] = {
  12491. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12492. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12493. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12494. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12495. // A content coding is a whole token, not something the field value merely
  12496. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12497. // as "fibre" look like Brotli, and turned a multi-coding value like
  12498. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12499. // it was never meant to see.
  12500. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12501. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12502. Server svr;
  12503. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12504. res.set_content(body, "image/jpeg");
  12505. res.set_header("Content-Encoding", "fibre");
  12506. });
  12507. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12508. res.set_content(body, "image/jpeg");
  12509. res.set_header("Content-Encoding", "gzip, br");
  12510. });
  12511. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12512. res.set_content(body, "image/jpeg");
  12513. res.set_header("Content-Encoding", "x-zstd-ish");
  12514. });
  12515. auto port = svr.bind_to_any_port(HOST);
  12516. thread t = thread([&]() { svr.listen_after_bind(); });
  12517. auto se = detail::scope_exit([&] {
  12518. svr.stop();
  12519. t.join();
  12520. ASSERT_FALSE(svr.is_running());
  12521. });
  12522. svr.wait_until_ready();
  12523. Client cli(HOST, port);
  12524. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12525. auto res = cli.Get(path);
  12526. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12527. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12528. // Not a coding we recognize, so the payload comes back untouched
  12529. EXPECT_EQ(body, res->body) << path;
  12530. }
  12531. }
  12532. // A content coding cpp-httplib recognizes but was not built with must be
  12533. // reported as such. Handing the still-compressed payload back to the caller
  12534. // would silently corrupt it.
  12535. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12536. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12537. Server svr;
  12538. // "image/jpeg" keeps the server from applying a content coding of its own,
  12539. // so the hand-crafted Content-Encoding below survives.
  12540. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12541. res.set_content(gzipped, "image/jpeg");
  12542. res.set_header("Content-Encoding", "gzip");
  12543. });
  12544. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12545. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12546. res.set_content(gzipped, "image/jpeg");
  12547. res.set_header("Content-Encoding", "GZIP");
  12548. });
  12549. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12550. auto se = detail::scope_exit([&] {
  12551. svr.stop();
  12552. t.join();
  12553. ASSERT_FALSE(svr.is_running());
  12554. });
  12555. svr.wait_until_ready();
  12556. Client cli(HOST, PORT);
  12557. {
  12558. auto res = cli.Get("/gzipped");
  12559. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12561. EXPECT_EQ("Hello World!", res->body);
  12562. #else
  12563. ASSERT_FALSE(res);
  12564. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12565. #endif
  12566. }
  12567. {
  12568. // open_stream() must behave the same way.
  12569. auto handle = cli.open_stream("GET", "/gzipped");
  12570. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12571. ASSERT_TRUE(handle.is_valid());
  12572. std::string received;
  12573. char buf[256];
  12574. ssize_t n;
  12575. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12576. received.append(buf, static_cast<size_t>(n));
  12577. }
  12578. EXPECT_EQ("Hello World!", received);
  12579. #else
  12580. EXPECT_FALSE(handle.is_valid());
  12581. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12582. #endif
  12583. }
  12584. {
  12585. // A differently-cased coding must not be mistaken for an unknown one, or
  12586. // the body would be handed back still compressed.
  12587. auto res = cli.Get("/gzipped-uppercase");
  12588. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12590. EXPECT_EQ("Hello World!", res->body);
  12591. #else
  12592. ASSERT_FALSE(res);
  12593. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12594. #endif
  12595. }
  12596. }
  12597. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12598. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12599. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12600. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12601. // body a second time and appending a second Content-Encoding field line, so
  12602. // clients that decode one coding per listed value handed back raw gzip bytes.
  12603. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12604. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12605. Server svr;
  12606. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12607. // keeps the server from applying a coding of its own.
  12608. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12609. res.set_content(gzipped, "text/plain");
  12610. res.set_header("Content-Encoding", "gzip");
  12611. });
  12612. auto port = svr.bind_to_any_port(HOST);
  12613. thread t = thread([&]() { svr.listen_after_bind(); });
  12614. auto se = detail::scope_exit([&] {
  12615. svr.stop();
  12616. t.join();
  12617. ASSERT_FALSE(svr.is_running());
  12618. });
  12619. svr.wait_until_ready();
  12620. Client cli(HOST, port);
  12621. Headers headers = {{"Accept-Encoding", "gzip"}};
  12622. auto res = cli.Get("/pre-gzipped", headers);
  12623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12624. EXPECT_EQ(StatusCode::OK_200, res->status);
  12625. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12626. EXPECT_EQ("Hello World!", res->body);
  12627. }
  12628. // set_compress(false) sends every handler response as it is, buffered or
  12629. // streamed
  12630. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12631. const std::string text(1000, 'a');
  12632. Server svr;
  12633. svr.set_compress(false);
  12634. svr.Get("/buffered", [&](const Request &, Response &res) {
  12635. res.set_content(text, "text/plain");
  12636. });
  12637. svr.Get("/streamed", [&](const Request &, Response &res) {
  12638. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12639. sink.write(text.data(), text.size());
  12640. sink.done();
  12641. return true;
  12642. });
  12643. });
  12644. auto port = svr.bind_to_any_port(HOST);
  12645. ASSERT_LT(0, port);
  12646. thread t = thread([&] { svr.listen_after_bind(); });
  12647. auto se = detail::scope_exit([&] {
  12648. svr.stop();
  12649. t.join();
  12650. ASSERT_FALSE(svr.is_running());
  12651. });
  12652. svr.wait_until_ready();
  12653. Client cli(HOST, port);
  12654. cli.set_decompress(false);
  12655. for (auto path : {"/buffered", "/streamed"}) {
  12656. SCOPED_TRACE(path);
  12657. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12659. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12660. EXPECT_EQ(text, res->body);
  12661. }
  12662. }
  12663. // A chunked provider settles its coding where the headers are written and
  12664. // reuses it at write time. Both ends of that have to hold: a handler's own
  12665. // Content-Encoding suppresses the coding, and a response without one is still
  12666. // compressed as it always was.
  12667. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12668. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12669. const std::string plain = "Hello World! Hello World! Hello World!";
  12670. Server svr;
  12671. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12672. res.set_header("Content-Encoding", "gzip");
  12673. res.set_chunked_content_provider(
  12674. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12675. sink.write(gzipped.data(), gzipped.size());
  12676. sink.done();
  12677. return true;
  12678. });
  12679. });
  12680. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12681. res.set_chunked_content_provider(
  12682. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12683. sink.write(plain.data(), plain.size());
  12684. sink.done();
  12685. return true;
  12686. });
  12687. });
  12688. auto port = svr.bind_to_any_port(HOST);
  12689. thread t = thread([&]() { svr.listen_after_bind(); });
  12690. auto se = detail::scope_exit([&] {
  12691. svr.stop();
  12692. t.join();
  12693. ASSERT_FALSE(svr.is_running());
  12694. });
  12695. svr.wait_until_ready();
  12696. Client cli(HOST, port);
  12697. Headers headers = {{"Accept-Encoding", "gzip"}};
  12698. {
  12699. auto res = cli.Get("/pre-gzipped", headers);
  12700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12701. EXPECT_EQ(StatusCode::OK_200, res->status);
  12702. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12703. EXPECT_EQ("Hello World!", res->body);
  12704. }
  12705. {
  12706. auto res = cli.Get("/negotiated", headers);
  12707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12708. EXPECT_EQ(StatusCode::OK_200, res->status);
  12709. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12710. EXPECT_EQ(plain, res->body);
  12711. }
  12712. }
  12713. #endif
  12714. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12715. // the same message as the comma-joined one, so both have to be read the same
  12716. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12717. // single gzip coding, and a body the sender says was encoded twice was handed
  12718. // back after one pass, still compressed but presented as decoded.
  12719. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12720. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12721. Server svr;
  12722. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12723. res.set_content(body, "image/jpeg");
  12724. res.headers.emplace("Content-Encoding", "gzip");
  12725. res.headers.emplace("Content-Encoding", "gzip");
  12726. });
  12727. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12728. res.set_content(body, "image/jpeg");
  12729. res.set_header("Content-Encoding", "gzip, gzip");
  12730. });
  12731. auto port = svr.bind_to_any_port(HOST);
  12732. thread t = thread([&]() { svr.listen_after_bind(); });
  12733. auto se = detail::scope_exit([&] {
  12734. svr.stop();
  12735. t.join();
  12736. ASSERT_FALSE(svr.is_running());
  12737. });
  12738. svr.wait_until_ready();
  12739. Client cli(HOST, port);
  12740. // Two codings is not something cpp-httplib decodes, so both representations
  12741. // take the pass-through path rather than one of them being gunzipped once.
  12742. for (const char *path : {"/split", "/joined"}) {
  12743. auto res = cli.Get(path);
  12744. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12745. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12746. EXPECT_EQ(body, res->body) << path;
  12747. }
  12748. }
  12749. // Regression test for DoS vulnerability: a malicious server sending a response
  12750. // without Content-Length header must not cause unbounded memory consumption on
  12751. // the client side. The client should stop reading after a reasonable limit,
  12752. // similar to the server-side set_payload_max_length protection.
  12753. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12754. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12755. #ifndef _WIN32
  12756. signal(SIGPIPE, SIG_IGN);
  12757. #endif
  12758. auto server_thread = std::thread([] {
  12759. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12760. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12761. default_socket_options(srv);
  12762. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12763. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12764. sockaddr_in addr{};
  12765. addr.sin_family = AF_INET;
  12766. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12767. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12768. int opt = 1;
  12769. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12770. #ifdef _WIN32
  12771. reinterpret_cast<const char *>(&opt),
  12772. #else
  12773. &opt,
  12774. #endif
  12775. sizeof(opt));
  12776. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12777. ::listen(srv, 1);
  12778. sockaddr_in cli_addr{};
  12779. socklen_t cli_len = sizeof(cli_addr);
  12780. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12781. if (cli != INVALID_SOCKET) {
  12782. char buf[4096];
  12783. ::recv(cli, buf, sizeof(buf), 0);
  12784. // Malicious response: no Content-Length, no chunked encoding
  12785. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12786. "Connection: close\r\n"
  12787. "\r\n";
  12788. ::send(cli,
  12789. #ifdef _WIN32
  12790. static_cast<const char *>(response_header.c_str()),
  12791. static_cast<int>(response_header.size()),
  12792. #else
  12793. response_header.c_str(), response_header.size(),
  12794. #endif
  12795. 0);
  12796. // Send 10MB of data
  12797. std::string chunk(64 * 1024, 'A');
  12798. size_t total_sent = 0;
  12799. while (total_sent < MALICIOUS_DATA_SIZE) {
  12800. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12801. auto sent = ::send(cli,
  12802. #ifdef _WIN32
  12803. static_cast<const char *>(chunk.c_str()),
  12804. static_cast<int>(to_send),
  12805. #else
  12806. chunk.c_str(), to_send,
  12807. #endif
  12808. 0);
  12809. if (sent <= 0) break;
  12810. total_sent += static_cast<size_t>(sent);
  12811. }
  12812. detail::close_socket(cli);
  12813. }
  12814. detail::close_socket(srv);
  12815. });
  12816. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12817. size_t total_read = 0;
  12818. {
  12819. Client cli("127.0.0.1", PORT + 2);
  12820. cli.set_read_timeout(5, 0);
  12821. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12822. auto stream = cli.open_stream("GET", "/malicious");
  12823. ASSERT_TRUE(stream.is_valid());
  12824. char buffer[64 * 1024];
  12825. ssize_t n;
  12826. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12827. total_read += static_cast<size_t>(n);
  12828. }
  12829. } // StreamHandle and Client destroyed here, closing the socket
  12830. server_thread.join();
  12831. // With set_payload_max_length, the client must stop reading before consuming
  12832. // all 10MB. The read loop should be cut off at or near the configured limit.
  12833. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12834. << "Client read " << total_read << " bytes, exceeding the configured "
  12835. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12836. }
  12837. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12838. // the entire response body without truncation.
  12839. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12840. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12841. #ifndef _WIN32
  12842. signal(SIGPIPE, SIG_IGN);
  12843. #endif
  12844. auto server_thread = std::thread([] {
  12845. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12846. default_socket_options(srv);
  12847. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12848. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12849. sockaddr_in addr{};
  12850. addr.sin_family = AF_INET;
  12851. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12852. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12853. int opt = 1;
  12854. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12855. #ifdef _WIN32
  12856. reinterpret_cast<const char *>(&opt),
  12857. #else
  12858. &opt,
  12859. #endif
  12860. sizeof(opt));
  12861. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12862. ::listen(srv, 1);
  12863. sockaddr_in cli_addr{};
  12864. socklen_t cli_len = sizeof(cli_addr);
  12865. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12866. if (cli != INVALID_SOCKET) {
  12867. char buf[4096];
  12868. ::recv(cli, buf, sizeof(buf), 0);
  12869. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12870. "Connection: close\r\n"
  12871. "\r\n";
  12872. ::send(cli,
  12873. #ifdef _WIN32
  12874. static_cast<const char *>(response_header.c_str()),
  12875. static_cast<int>(response_header.size()),
  12876. #else
  12877. response_header.c_str(), response_header.size(),
  12878. #endif
  12879. 0);
  12880. std::string chunk(64 * 1024, 'A');
  12881. size_t total_sent = 0;
  12882. while (total_sent < DATA_SIZE) {
  12883. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12884. auto sent = ::send(cli,
  12885. #ifdef _WIN32
  12886. static_cast<const char *>(chunk.c_str()),
  12887. static_cast<int>(to_send),
  12888. #else
  12889. chunk.c_str(), to_send,
  12890. #endif
  12891. 0);
  12892. if (sent <= 0) break;
  12893. total_sent += static_cast<size_t>(sent);
  12894. }
  12895. #ifdef _WIN32
  12896. ::shutdown(cli, SD_SEND);
  12897. #else
  12898. ::shutdown(cli, SHUT_WR);
  12899. #endif
  12900. // Drain until the client closes its end, ensuring all data is delivered
  12901. char drain[1024];
  12902. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12903. detail::close_socket(cli);
  12904. }
  12905. detail::close_socket(srv);
  12906. });
  12907. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12908. size_t total_read = 0;
  12909. {
  12910. Client cli("127.0.0.1", PORT + 2);
  12911. cli.set_read_timeout(5, 0);
  12912. cli.set_payload_max_length(0); // 0 means no limit
  12913. auto stream = cli.open_stream("GET", "/data");
  12914. ASSERT_TRUE(stream.is_valid());
  12915. char buffer[64 * 1024];
  12916. ssize_t n;
  12917. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12918. total_read += static_cast<size_t>(n);
  12919. }
  12920. }
  12921. server_thread.join();
  12922. EXPECT_EQ(total_read, DATA_SIZE)
  12923. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12924. << " bytes without truncation, but only read " << total_read << " bytes.";
  12925. }
  12926. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12927. // enormous Content-Length must not cause the client to pre-allocate a huge
  12928. // response body buffer. The reservation is capped at payload_max_length_, and
  12929. // the read itself fails when the body exceeds the limit.
  12930. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12931. #ifndef _WIN32
  12932. signal(SIGPIPE, SIG_IGN);
  12933. #endif
  12934. auto server_thread = std::thread([] {
  12935. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12936. default_socket_options(srv);
  12937. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12938. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12939. sockaddr_in addr{};
  12940. addr.sin_family = AF_INET;
  12941. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12942. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12943. int opt = 1;
  12944. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12945. #ifdef _WIN32
  12946. reinterpret_cast<const char *>(&opt),
  12947. #else
  12948. &opt,
  12949. #endif
  12950. sizeof(opt));
  12951. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12952. ::listen(srv, 1);
  12953. sockaddr_in cli_addr{};
  12954. socklen_t cli_len = sizeof(cli_addr);
  12955. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12956. if (cli != INVALID_SOCKET) {
  12957. char buf[4096];
  12958. ::recv(cli, buf, sizeof(buf), 0);
  12959. // Malicious response: claim a 20GB body but send only a tiny payload.
  12960. std::string response = "HTTP/1.1 200 OK\r\n"
  12961. "Content-Length: 20000000000\r\n"
  12962. "\r\n"
  12963. "abc";
  12964. ::send(cli,
  12965. #ifdef _WIN32
  12966. static_cast<const char *>(response.c_str()),
  12967. static_cast<int>(response.size()),
  12968. #else
  12969. response.c_str(), response.size(),
  12970. #endif
  12971. 0);
  12972. detail::close_socket(cli);
  12973. }
  12974. detail::close_socket(srv);
  12975. });
  12976. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12977. {
  12978. Client cli("127.0.0.1", PORT + 2);
  12979. cli.set_read_timeout(5, 0);
  12980. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12981. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12982. // (server claims more bytes than payload_max_length permits), but it must
  12983. // not exhaust memory before getting there.
  12984. auto res = cli.Get("/malicious");
  12985. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12986. }
  12987. server_thread.join();
  12988. }
  12989. // Verify that content_receiver bypasses the default payload_max_length,
  12990. // allowing streaming downloads larger than 100MB without requiring an explicit
  12991. // set_payload_max_length call.
  12992. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12993. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12994. #ifndef _WIN32
  12995. signal(SIGPIPE, SIG_IGN);
  12996. #endif
  12997. auto server_thread = std::thread([] {
  12998. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12999. default_socket_options(srv);
  13000. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13001. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13002. sockaddr_in addr{};
  13003. addr.sin_family = AF_INET;
  13004. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13005. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13006. int opt = 1;
  13007. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13008. #ifdef _WIN32
  13009. reinterpret_cast<const char *>(&opt),
  13010. #else
  13011. &opt,
  13012. #endif
  13013. sizeof(opt));
  13014. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13015. ::listen(srv, 1);
  13016. sockaddr_in cli_addr{};
  13017. socklen_t cli_len = sizeof(cli_addr);
  13018. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13019. if (cli != INVALID_SOCKET) {
  13020. char buf[4096];
  13021. ::recv(cli, buf, sizeof(buf), 0);
  13022. // Response with Content-Length larger than default 100MB limit
  13023. auto content_length = std::to_string(DATA_SIZE);
  13024. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13025. "Content-Length: " +
  13026. content_length +
  13027. "\r\n"
  13028. "Connection: close\r\n"
  13029. "\r\n";
  13030. ::send(cli,
  13031. #ifdef _WIN32
  13032. static_cast<const char *>(response_header.c_str()),
  13033. static_cast<int>(response_header.size()),
  13034. #else
  13035. response_header.c_str(), response_header.size(),
  13036. #endif
  13037. 0);
  13038. std::string chunk(64 * 1024, 'A');
  13039. size_t total_sent = 0;
  13040. while (total_sent < DATA_SIZE) {
  13041. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13042. auto sent = ::send(cli,
  13043. #ifdef _WIN32
  13044. static_cast<const char *>(chunk.c_str()),
  13045. static_cast<int>(to_send),
  13046. #else
  13047. chunk.c_str(), to_send,
  13048. #endif
  13049. 0);
  13050. if (sent <= 0) break;
  13051. total_sent += static_cast<size_t>(sent);
  13052. }
  13053. detail::close_socket(cli);
  13054. }
  13055. detail::close_socket(srv);
  13056. });
  13057. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13058. size_t total_received = 0;
  13059. {
  13060. Client cli("127.0.0.1", PORT + 2);
  13061. cli.set_read_timeout(10, 0);
  13062. // Do NOT call set_payload_max_length — use the default 100MB limit
  13063. auto res =
  13064. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13065. total_received += data_length;
  13066. return true;
  13067. });
  13068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13069. EXPECT_EQ(StatusCode::OK_200, res->status);
  13070. }
  13071. server_thread.join();
  13072. EXPECT_EQ(total_received, DATA_SIZE)
  13073. << "With content_receiver, the client should read all " << DATA_SIZE
  13074. << " bytes despite the default 100MB payload_max_length, but only read "
  13075. << total_received << " bytes.";
  13076. }
  13077. // Verify that an explicit set_payload_max_length smaller than the response is
  13078. // enforced even when a content_receiver is used.
  13079. TEST(ClientVulnerabilityTest,
  13080. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13081. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13082. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13083. #ifndef _WIN32
  13084. signal(SIGPIPE, SIG_IGN);
  13085. #endif
  13086. auto server_thread = std::thread([] {
  13087. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13088. default_socket_options(srv);
  13089. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13090. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13091. sockaddr_in addr{};
  13092. addr.sin_family = AF_INET;
  13093. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13094. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13095. int opt = 1;
  13096. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13097. #ifdef _WIN32
  13098. reinterpret_cast<const char *>(&opt),
  13099. #else
  13100. &opt,
  13101. #endif
  13102. sizeof(opt));
  13103. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13104. ::listen(srv, 1);
  13105. sockaddr_in cli_addr{};
  13106. socklen_t cli_len = sizeof(cli_addr);
  13107. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13108. if (cli != INVALID_SOCKET) {
  13109. char buf[4096];
  13110. ::recv(cli, buf, sizeof(buf), 0);
  13111. auto content_length = std::to_string(DATA_SIZE);
  13112. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13113. "Content-Length: " +
  13114. content_length +
  13115. "\r\n"
  13116. "Connection: close\r\n"
  13117. "\r\n";
  13118. ::send(cli,
  13119. #ifdef _WIN32
  13120. static_cast<const char *>(response_header.c_str()),
  13121. static_cast<int>(response_header.size()),
  13122. #else
  13123. response_header.c_str(), response_header.size(),
  13124. #endif
  13125. 0);
  13126. std::string chunk(64 * 1024, 'A');
  13127. size_t total_sent = 0;
  13128. while (total_sent < DATA_SIZE) {
  13129. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13130. auto sent = ::send(cli,
  13131. #ifdef _WIN32
  13132. static_cast<const char *>(chunk.c_str()),
  13133. static_cast<int>(to_send),
  13134. #else
  13135. chunk.c_str(), to_send,
  13136. #endif
  13137. 0);
  13138. if (sent <= 0) break;
  13139. total_sent += static_cast<size_t>(sent);
  13140. }
  13141. detail::close_socket(cli);
  13142. }
  13143. detail::close_socket(srv);
  13144. });
  13145. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13146. size_t total_received = 0;
  13147. {
  13148. Client cli("127.0.0.1", PORT + 2);
  13149. cli.set_read_timeout(10, 0);
  13150. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13151. auto res =
  13152. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13153. total_received += data_length;
  13154. return true;
  13155. });
  13156. // Should fail because 200MB exceeds the explicit 150MB limit
  13157. EXPECT_FALSE(res);
  13158. }
  13159. server_thread.join();
  13160. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13161. << "Client with content_receiver should respect the explicit "
  13162. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13163. << total_received << " bytes.";
  13164. }
  13165. // Verify that an explicit set_payload_max_length larger than the response
  13166. // allows the content_receiver to read all data successfully.
  13167. TEST(ClientVulnerabilityTest,
  13168. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13169. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13170. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13171. #ifndef _WIN32
  13172. signal(SIGPIPE, SIG_IGN);
  13173. #endif
  13174. auto server_thread = std::thread([] {
  13175. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13176. default_socket_options(srv);
  13177. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13178. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13179. sockaddr_in addr{};
  13180. addr.sin_family = AF_INET;
  13181. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13182. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13183. int opt = 1;
  13184. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13185. #ifdef _WIN32
  13186. reinterpret_cast<const char *>(&opt),
  13187. #else
  13188. &opt,
  13189. #endif
  13190. sizeof(opt));
  13191. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13192. ::listen(srv, 1);
  13193. sockaddr_in cli_addr{};
  13194. socklen_t cli_len = sizeof(cli_addr);
  13195. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13196. if (cli != INVALID_SOCKET) {
  13197. char buf[4096];
  13198. ::recv(cli, buf, sizeof(buf), 0);
  13199. auto content_length = std::to_string(DATA_SIZE);
  13200. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13201. "Content-Length: " +
  13202. content_length +
  13203. "\r\n"
  13204. "Connection: close\r\n"
  13205. "\r\n";
  13206. ::send(cli,
  13207. #ifdef _WIN32
  13208. static_cast<const char *>(response_header.c_str()),
  13209. static_cast<int>(response_header.size()),
  13210. #else
  13211. response_header.c_str(), response_header.size(),
  13212. #endif
  13213. 0);
  13214. std::string chunk(64 * 1024, 'A');
  13215. size_t total_sent = 0;
  13216. while (total_sent < DATA_SIZE) {
  13217. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13218. auto sent = ::send(cli,
  13219. #ifdef _WIN32
  13220. static_cast<const char *>(chunk.c_str()),
  13221. static_cast<int>(to_send),
  13222. #else
  13223. chunk.c_str(), to_send,
  13224. #endif
  13225. 0);
  13226. if (sent <= 0) break;
  13227. total_sent += static_cast<size_t>(sent);
  13228. }
  13229. #ifdef _WIN32
  13230. ::shutdown(cli, SD_SEND);
  13231. #else
  13232. ::shutdown(cli, SHUT_WR);
  13233. #endif
  13234. char drain[1024];
  13235. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13236. detail::close_socket(cli);
  13237. }
  13238. detail::close_socket(srv);
  13239. });
  13240. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13241. size_t total_received = 0;
  13242. {
  13243. Client cli("127.0.0.1", PORT + 2);
  13244. cli.set_read_timeout(10, 0);
  13245. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13246. auto res =
  13247. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13248. total_received += data_length;
  13249. return true;
  13250. });
  13251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13252. EXPECT_EQ(StatusCode::OK_200, res->status);
  13253. }
  13254. server_thread.join();
  13255. EXPECT_EQ(total_received, DATA_SIZE)
  13256. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13257. << " bytes (larger than " << DATA_SIZE
  13258. << " bytes response), content_receiver should read all data, but only "
  13259. "read "
  13260. << total_received << " bytes.";
  13261. }
  13262. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13263. // Regression test for "zip bomb" attack on the client side: a malicious server
  13264. // sends a small gzip-compressed response that decompresses to a huge payload.
  13265. // The client must enforce payload_max_length on the decompressed size.
  13266. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13267. constexpr size_t DECOMPRESSED_SIZE =
  13268. 10 * 1024 * 1024; // 10MB after decompression
  13269. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13270. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13271. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13272. std::string compressed;
  13273. {
  13274. httplib::detail::gzip_compressor compressor;
  13275. bool ok =
  13276. compressor.compress(uncompressed.data(), uncompressed.size(),
  13277. /*last=*/true, [&](const char *buf, size_t len) {
  13278. compressed.append(buf, len);
  13279. return true;
  13280. });
  13281. ASSERT_TRUE(ok);
  13282. }
  13283. // Sanity: compressed data should be much smaller than the decompressed size
  13284. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13285. #ifndef _WIN32
  13286. signal(SIGPIPE, SIG_IGN);
  13287. #endif
  13288. // Set up the listening socket in the main thread so the server is guaranteed
  13289. // to be ready before the client connects (eliminates race condition).
  13290. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13291. default_socket_options(srv);
  13292. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13293. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13294. sockaddr_in addr{};
  13295. addr.sin_family = AF_INET;
  13296. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13297. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13298. int opt = 1;
  13299. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13300. #ifdef _WIN32
  13301. reinterpret_cast<const char *>(&opt),
  13302. #else
  13303. &opt,
  13304. #endif
  13305. sizeof(opt));
  13306. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13307. ASSERT_EQ(0, ::listen(srv, 1));
  13308. auto server_thread = std::thread([&compressed, srv] {
  13309. sockaddr_in cli_addr{};
  13310. socklen_t cli_len = sizeof(cli_addr);
  13311. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13312. if (cli != INVALID_SOCKET) {
  13313. // Read the full HTTP request (until \r\n\r\n)
  13314. char buf[4096];
  13315. size_t total = 0;
  13316. while (total < sizeof(buf)) {
  13317. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13318. if (n <= 0) break;
  13319. total += static_cast<size_t>(n);
  13320. // Check for end of headers
  13321. if (total >= 4) {
  13322. std::string req(buf, total);
  13323. if (req.find("\r\n\r\n") != std::string::npos) break;
  13324. }
  13325. }
  13326. // Malicious response: gzip-compressed body, no Content-Length
  13327. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13328. "Content-Encoding: gzip\r\n"
  13329. "Connection: close\r\n"
  13330. "\r\n";
  13331. ::send(cli,
  13332. #ifdef _WIN32
  13333. static_cast<const char *>(response_header.c_str()),
  13334. static_cast<int>(response_header.size()),
  13335. #else
  13336. response_header.c_str(), response_header.size(),
  13337. #endif
  13338. 0);
  13339. // Send the compressed payload (small on the wire, huge when decompressed)
  13340. size_t total_sent = 0;
  13341. while (total_sent < compressed.size()) {
  13342. auto to_send = std::min(compressed.size() - total_sent,
  13343. static_cast<size_t>(64 * 1024));
  13344. auto sent =
  13345. ::send(cli,
  13346. #ifdef _WIN32
  13347. static_cast<const char *>(compressed.c_str() + total_sent),
  13348. static_cast<int>(to_send),
  13349. #else
  13350. compressed.c_str() + total_sent, to_send,
  13351. #endif
  13352. 0);
  13353. if (sent <= 0) break;
  13354. total_sent += static_cast<size_t>(sent);
  13355. }
  13356. detail::close_socket(cli);
  13357. }
  13358. });
  13359. auto se = detail::scope_exit([&] {
  13360. detail::close_socket(srv);
  13361. server_thread.join();
  13362. });
  13363. size_t total_decompressed = 0;
  13364. {
  13365. Client cli("127.0.0.1", PORT + 3);
  13366. cli.set_read_timeout(5, 0);
  13367. cli.set_decompress(true);
  13368. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13369. auto stream = cli.open_stream("GET", "/zipbomb");
  13370. ASSERT_TRUE(stream.is_valid());
  13371. char buffer[64 * 1024];
  13372. ssize_t n;
  13373. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13374. total_decompressed += static_cast<size_t>(n);
  13375. }
  13376. }
  13377. // The decompressed size must be capped by payload_max_length. Without
  13378. // protection, the client would decompress the full 10MB from a tiny
  13379. // compressed payload, enabling a zip bomb DoS attack.
  13380. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13381. << "Client decompressed " << total_decompressed
  13382. << " bytes from a gzip response. The decompressed size should be "
  13383. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13384. }
  13385. #endif
  13386. TEST(HostAndPortPropertiesTest, NoSSL) {
  13387. httplib::Client cli("www.google.com", 1234);
  13388. ASSERT_EQ("www.google.com", cli.host());
  13389. ASSERT_EQ(1234, cli.port());
  13390. }
  13391. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13392. httplib::Client cli("www.google.com:1234");
  13393. ASSERT_EQ("www.google.com", cli.host());
  13394. ASSERT_EQ(1234, cli.port());
  13395. }
  13396. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13397. // Port number that overflows int — should not crash, client becomes invalid
  13398. httplib::Client cli("http://www.google.com:99999999999999999999");
  13399. ASSERT_FALSE(cli.is_valid());
  13400. }
  13401. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13402. // Port 99999 exceeds valid range (1-65535) — should not crash
  13403. httplib::Client cli("http://www.google.com:99999");
  13404. ASSERT_FALSE(cli.is_valid());
  13405. auto res = cli.Get("/");
  13406. EXPECT_FALSE(res);
  13407. EXPECT_EQ(Error::Connection, res.error());
  13408. }
  13409. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13410. httplib::Client cli("http://user:pass@localhost:1234");
  13411. ASSERT_FALSE(cli.is_valid());
  13412. EXPECT_FALSE(cli.Get("/"));
  13413. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13414. }
  13415. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13416. httplib::Client cli("http://www.google.com:80abc");
  13417. ASSERT_FALSE(cli.is_valid());
  13418. }
  13419. #ifdef CPPHTTPLIB_SSL_ENABLED
  13420. TEST(HostAndPortPropertiesTest, SSL) {
  13421. httplib::SSLClient cli("www.google.com");
  13422. ASSERT_EQ("www.google.com", cli.host());
  13423. ASSERT_EQ(443, cli.port());
  13424. }
  13425. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13426. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13427. std::string cert;
  13428. read_file(CA_CERT_FILE, cert);
  13429. httplib::SSLClient httplib_client("www.google.com");
  13430. // Load CA store first time
  13431. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13432. // Load CA store second time (update)
  13433. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13434. // Verify client is still valid and can make connections
  13435. httplib_client.enable_server_certificate_verification(true);
  13436. auto res = httplib_client.Get("/");
  13437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13438. // Google may return 200 or 301 depending on various factors
  13439. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13440. res->status == StatusCode::MovedPermanently_301);
  13441. }
  13442. TEST(SSLClientTest, ServerNameIndication_Online) {
  13443. auto host = "httpbingo.org";
  13444. auto path = std::string{"/get"};
  13445. SSLClient cli(host, 443);
  13446. auto res = cli.Get(path);
  13447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13448. ASSERT_EQ(StatusCode::OK_200, res->status);
  13449. }
  13450. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13451. // Use a site that will cause SSL verification failure due to self-signed cert
  13452. SSLClient cli("self-signed.badssl.com", 443);
  13453. cli.enable_server_certificate_verification(true);
  13454. auto res = cli.Get("/");
  13455. ASSERT_TRUE(!res);
  13456. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13457. // Verify backend error is captured for SSLServerVerification
  13458. // This occurs when certificate verification fails
  13459. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13460. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13461. EXPECT_NE(0UL, res.ssl_backend_error());
  13462. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13463. res.ssl_error());
  13464. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13465. #if !defined(_WIN32) || \
  13466. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13467. // On non-Windows or when Windows Schannel is disabled, the error comes
  13468. // from OpenSSL's verification
  13469. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13470. res.ssl_backend_error());
  13471. #endif
  13472. #endif
  13473. }
  13474. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13475. // Use a site where hostname doesn't match the certificate
  13476. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13477. SSLClient cli("wrong.host.badssl.com", 443);
  13478. cli.enable_server_certificate_verification(true);
  13479. cli.enable_server_hostname_verification(true);
  13480. auto res = cli.Get("/");
  13481. ASSERT_TRUE(!res);
  13482. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13483. // Verify backend error is captured for hostname verification failure
  13484. EXPECT_NE(0UL, res.ssl_backend_error());
  13485. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13486. res.ssl_error());
  13487. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13488. #if !defined(_WIN32) || \
  13489. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13490. // On non-Windows or when Windows Schannel is disabled, the error comes
  13491. // from OpenSSL's hostname verification
  13492. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13493. res.ssl_backend_error());
  13494. #endif
  13495. #endif
  13496. }
  13497. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13498. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13499. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13500. SSLClient cli("www.google.com", 443);
  13501. cli.enable_server_certificate_verification(true);
  13502. auto res = cli.Get("/");
  13503. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13504. }
  13505. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13506. SSLClient cli("www.google.com", 443);
  13507. cli.enable_server_certificate_verification(true);
  13508. cli.enable_windows_certificate_verification(false);
  13509. auto res = cli.Get("/");
  13510. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13511. }
  13512. // The server sends an intermediate cross-signed by a root Windows trusts,
  13513. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13514. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13515. SSLClient cli("accounts.spotify.com", 443);
  13516. auto res = cli.Get("/");
  13517. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13518. << " ssl_backend_error=" << res.ssl_backend_error();
  13519. }
  13520. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13521. // policy status, which no backend reports for a self-signed certificate.
  13522. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13523. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13524. ASSERT_TRUE(svr.is_valid());
  13525. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13526. auto se = detail::scope_exit([&] {
  13527. svr.stop();
  13528. t.join();
  13529. ASSERT_FALSE(svr.is_running());
  13530. });
  13531. svr.wait_until_ready();
  13532. SSLClient cli("127.0.0.1", PORT);
  13533. cli.set_connection_timeout(30);
  13534. auto res = cli.Get("/");
  13535. ASSERT_FALSE(res);
  13536. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13537. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13538. }
  13539. #endif
  13540. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13541. Client cli("https://google.com");
  13542. auto res = cli.Get("/");
  13543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13544. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13545. }
  13546. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13547. SSLClient cli("google.com");
  13548. cli.set_ca_cert_path(CA_CERT_FILE);
  13549. auto res = cli.Get("/");
  13550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13551. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13552. }
  13553. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13554. SSLClient cli("google.com");
  13555. cli.enable_server_certificate_verification(true);
  13556. cli.set_ca_cert_path("hello");
  13557. auto res = cli.Get("/");
  13558. ASSERT_TRUE(!res);
  13559. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13560. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13561. // should be set
  13562. EXPECT_EQ(0, res.ssl_error());
  13563. // Verify backend error is captured for SSLLoadingCerts
  13564. // This error occurs when loading CA certificates fails
  13565. EXPECT_NE(0UL, res.ssl_backend_error());
  13566. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13567. // OpenSSL specific error codes:
  13568. // > openssl errstr 0x80000002
  13569. // error:80000002:system library::No such file or directory
  13570. // > openssl errstr 0xA000126
  13571. // error:0A000126:SSL routines::unexpected eof while reading
  13572. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13573. res.ssl_backend_error() == 0xA000126);
  13574. #endif
  13575. }
  13576. TEST(SSLClientTest, ServerCertificateVerification4) {
  13577. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13578. ASSERT_TRUE(svr.is_valid());
  13579. svr.Get("/test", [&](const Request &, Response &res) {
  13580. res.set_content("test", "text/plain");
  13581. svr.stop();
  13582. ASSERT_TRUE(true);
  13583. });
  13584. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13585. auto se = detail::scope_exit([&] {
  13586. t.join();
  13587. ASSERT_FALSE(svr.is_running());
  13588. });
  13589. svr.wait_until_ready();
  13590. SSLClient cli("127.0.0.1", PORT);
  13591. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13592. cli.enable_server_certificate_verification(true);
  13593. cli.set_connection_timeout(30);
  13594. auto res = cli.Get("/test");
  13595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13596. ASSERT_EQ(StatusCode::OK_200, res->status);
  13597. }
  13598. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13599. std::string cert;
  13600. read_file(CA_CERT_FILE, cert);
  13601. SSLClient cli("google.com");
  13602. cli.load_ca_cert_store(cert.data(), cert.size());
  13603. const auto res = cli.Get("/");
  13604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13605. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13606. }
  13607. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13608. // clang-format off
  13609. static constexpr char cert[] =
  13610. "GlobalSign Root CA\n"
  13611. "==================\n"
  13612. "-----BEGIN CERTIFICATE-----\n"
  13613. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13614. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13615. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13616. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13617. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13618. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13619. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13620. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13621. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13622. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13623. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13624. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13625. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13626. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13627. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13628. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13629. "-----END CERTIFICATE-----\n";
  13630. // clang-format on
  13631. SSLClient cli("google.com");
  13632. cli.load_ca_cert_store(cert, sizeof(cert));
  13633. const auto res = cli.Get("/");
  13634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13635. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13636. }
  13637. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13638. SSLClient cli("www.youtube.com");
  13639. cli.set_ca_cert_path(CA_CERT_FILE);
  13640. cli.enable_server_certificate_verification(true);
  13641. cli.set_follow_location(true);
  13642. auto res = cli.Get("/");
  13643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13644. ASSERT_EQ(StatusCode::OK_200, res->status);
  13645. }
  13646. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13647. SSLClient cli("wWw.YouTube.Com");
  13648. cli.set_ca_cert_path(CA_CERT_FILE);
  13649. cli.enable_server_certificate_verification(true);
  13650. cli.enable_server_hostname_verification(true);
  13651. cli.set_follow_location(true);
  13652. auto res = cli.Get("/");
  13653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13654. ASSERT_EQ(StatusCode::OK_200, res->status);
  13655. }
  13656. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13657. SSLClient cli("gOoGlE.COm");
  13658. cli.enable_server_certificate_verification(true);
  13659. cli.enable_server_hostname_verification(true);
  13660. cli.set_follow_location(true);
  13661. auto res = cli.Get("/");
  13662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13663. ASSERT_EQ(StatusCode::OK_200, res->status);
  13664. }
  13665. TEST(SSLClientTest, Issue2004_Online) {
  13666. Client client("https://google.com");
  13667. client.set_follow_location(true);
  13668. auto res = client.Get("/");
  13669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13670. ASSERT_EQ(StatusCode::OK_200, res->status);
  13671. auto body = res->body;
  13672. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13673. }
  13674. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13675. // Create SSLClient with invalid cert/key to make is_valid() return false
  13676. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13677. "nonexistent_key.pem");
  13678. // is_valid() should be false due to cert loading failure
  13679. ASSERT_FALSE(cli.is_valid());
  13680. auto res = cli.Get("/");
  13681. ASSERT_FALSE(res);
  13682. EXPECT_EQ(Error::SSLConnection, res.error());
  13683. }
  13684. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13685. // Test for Issue #2251: SSL error not properly reported when client cert
  13686. // and key paths are swapped or mismatched
  13687. // This simulates the scenario where user accidentally swaps the cert and key
  13688. // files
  13689. // Using client cert file as private key and vice versa (completely wrong)
  13690. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13691. // Should fail validation due to cert/key mismatch
  13692. ASSERT_FALSE(cli.is_valid());
  13693. // Attempt to make a request should fail with proper error
  13694. auto res = cli.Get("/");
  13695. ASSERT_FALSE(res);
  13696. EXPECT_EQ(Error::SSLConnection, res.error());
  13697. // SSL error should be recorded in the Result object (this is the key fix for
  13698. // Issue #2251)
  13699. auto backend_error = res.ssl_backend_error();
  13700. EXPECT_NE(0u, backend_error);
  13701. }
  13702. // Tests cert/key mismatch detection at the TLS context level
  13703. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13704. // Test that using mismatched cert/key causes connection failure.
  13705. // We verify this at the SSLClient level rather than through internal
  13706. // TLS API functions.
  13707. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13708. cli.enable_server_certificate_verification(false);
  13709. cli.set_connection_timeout(2);
  13710. // The mismatch should cause a connection or handshake error
  13711. auto res = cli.Get("/test");
  13712. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13713. // Either way, the request should fail
  13714. EXPECT_FALSE(res);
  13715. }
  13716. #endif
  13717. #if 0
  13718. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13719. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13720. ASSERT_TRUE(cli != nullptr);
  13721. cli->set_address_family(AF_INET6);
  13722. cli->set_interface("en0");
  13723. auto res = cli->Get("/get");
  13724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13725. ASSERT_EQ(StatusCode::OK_200, res->status);
  13726. }
  13727. #endif
  13728. // Client certificate tests - work with all TLS backends
  13729. #ifdef CPPHTTPLIB_SSL_ENABLED
  13730. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13731. void ClientCertPresent(
  13732. const std::string &client_cert_file,
  13733. const std::string &client_private_key_file,
  13734. const std::string &client_encrypted_private_key_pass = std::string(),
  13735. const ClientCertServerSetup &setup = nullptr) {
  13736. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13737. ASSERT_TRUE(svr.is_valid());
  13738. if (setup) { setup(svr); }
  13739. svr.Get("/test", [&](const Request &req, Response &res) {
  13740. res.set_content("test", "text/plain");
  13741. auto cert = req.peer_cert();
  13742. ASSERT_TRUE(static_cast<bool>(cert));
  13743. std::string common_name = cert.subject_cn();
  13744. EXPECT_EQ("Common Name", common_name);
  13745. });
  13746. auto port = svr.bind_to_any_port(HOST);
  13747. ASSERT_LT(0, port);
  13748. thread t = thread([&]() { svr.listen_after_bind(); });
  13749. auto se = detail::scope_exit([&] {
  13750. svr.stop();
  13751. t.join();
  13752. ASSERT_FALSE(svr.is_running());
  13753. });
  13754. svr.wait_until_ready();
  13755. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13756. client_encrypted_private_key_pass);
  13757. cli.enable_server_certificate_verification(false);
  13758. cli.set_connection_timeout(30);
  13759. auto res = cli.Get("/test");
  13760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13761. ASSERT_EQ(StatusCode::OK_200, res->status);
  13762. }
  13763. TEST(SSLClientServerTest, ClientCertPresent) {
  13764. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13765. }
  13766. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13767. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13768. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13769. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13770. }
  13771. // Expects svr, which must require client certificates, to reject a client
  13772. // that has none
  13773. void RejectsClientWithoutCert(SSLServer &svr) {
  13774. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13775. auto port = svr.bind_to_any_port(HOST);
  13776. ASSERT_LT(0, port);
  13777. thread t = thread([&]() { svr.listen_after_bind(); });
  13778. auto se = detail::scope_exit([&] {
  13779. svr.stop();
  13780. t.join();
  13781. ASSERT_FALSE(svr.is_running());
  13782. });
  13783. svr.wait_until_ready();
  13784. SSLClient cli(HOST, port);
  13785. cli.set_connection_timeout(30);
  13786. // Skip the server certificate check, so that the request fails because the
  13787. // client certificate is missing rather than because cert.pem is not trusted
  13788. cli.enable_server_certificate_verification(false);
  13789. auto res = cli.Get("/test");
  13790. ASSERT_FALSE(res);
  13791. // The server rejects the client during the handshake, or on TLS 1.3 right
  13792. // after it, which the client notices on its first write or read
  13793. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13794. res.error() == Error::Write || res.error() == Error::Read)
  13795. << to_string(res.error());
  13796. if (res.error() == Error::SSLConnection) {
  13797. EXPECT_NE(0UL, res.ssl_backend_error());
  13798. }
  13799. // A rejection noticed on the write keeps the TLS error the write hit
  13800. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13801. }
  13802. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13803. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13804. ASSERT_TRUE(svr.is_valid());
  13805. if (setup) { setup(svr); }
  13806. RejectsClientWithoutCert(svr);
  13807. }
  13808. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13809. // A server that requires client certificates must keep requiring them after
  13810. // setup changes it, and keep accepting a client that has one
  13811. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13812. ClientCertMissing(setup);
  13813. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13814. setup);
  13815. }
  13816. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13817. ClientCertStillRequired([](SSLServer &svr) {
  13818. ASSERT_TRUE(tls::set_verify_callback(
  13819. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13820. });
  13821. }
  13822. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13823. ClientCertStillRequired([](SSLServer &svr) {
  13824. ASSERT_TRUE(tls::set_verify_callback(
  13825. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13826. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13827. });
  13828. }
  13829. // The client verifies the server certificate during the handshake, so a
  13830. // server that fails the check never gets the client certificate, even when a
  13831. // verifier of the client's own accepts it
  13832. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13833. struct Case {
  13834. const char *trusted_ca;
  13835. const char *host;
  13836. Error error;
  13837. };
  13838. // cert2.pem names localhost: the first client does not trust it, and the
  13839. // second trusts it but asks for another name
  13840. for (const auto &c :
  13841. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13842. Case{SERVER_CERT2_FILE, "example.com",
  13843. Error::SSLServerHostnameVerification}}) {
  13844. for (auto with_verifier : {false, true}) {
  13845. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13846. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13847. CLIENT_CA_CERT_FILE);
  13848. ASSERT_TRUE(svr.is_valid());
  13849. std::atomic<bool> got_client_cert{false};
  13850. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13851. [&](const tls::VerifyContext &) {
  13852. got_client_cert = true;
  13853. return true;
  13854. }));
  13855. auto port = svr.bind_to_any_port("127.0.0.1");
  13856. ASSERT_LT(0, port);
  13857. thread t = thread([&] { svr.listen_after_bind(); });
  13858. svr.wait_until_ready();
  13859. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13860. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13861. cli.set_ca_cert_path(c.trusted_ca);
  13862. if (with_verifier) {
  13863. cli.set_server_certificate_verifier(
  13864. [](const tls::VerifyContext &) { return true; });
  13865. }
  13866. auto res = cli.Get("/");
  13867. EXPECT_FALSE(res);
  13868. EXPECT_EQ(c.error, res.error());
  13869. svr.stop();
  13870. t.join();
  13871. EXPECT_FALSE(got_client_cert);
  13872. }
  13873. }
  13874. }
  13875. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13876. std::string cert_pem, key_pem, ca_pem;
  13877. read_file(SERVER_CERT_FILE, cert_pem);
  13878. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13879. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13880. ASSERT_TRUE(
  13881. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13882. }
  13883. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13884. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13885. ASSERT_TRUE(svr.is_valid());
  13886. UpdateCertsPemWithClientCA(svr);
  13887. RejectsClientWithoutCert(svr);
  13888. }
  13889. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13890. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13891. }
  13892. // A TLS error from one request must not show up in a later request's Result
  13893. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13894. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13895. ASSERT_TRUE(svr.is_valid());
  13896. svr.Get("/test", [](const Request &, Response &res) {
  13897. res.set_content("test", "text/plain");
  13898. });
  13899. auto port = svr.bind_to_any_port(HOST);
  13900. ASSERT_LT(0, port);
  13901. thread t = thread([&]() { svr.listen_after_bind(); });
  13902. auto se = detail::scope_exit([&] {
  13903. svr.stop();
  13904. t.join();
  13905. ASSERT_FALSE(svr.is_running());
  13906. });
  13907. svr.wait_until_ready();
  13908. SSLClient cli(HOST, port);
  13909. cli.set_connection_timeout(30);
  13910. cli.enable_server_hostname_verification(false);
  13911. // cert.pem is not trusted, so the handshake fails
  13912. ASSERT_FALSE(cli.Get("/test"));
  13913. cli.enable_server_certificate_verification(false);
  13914. auto res = cli.Get("/test");
  13915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13916. EXPECT_EQ(0, res.ssl_error());
  13917. EXPECT_EQ(0UL, res.ssl_backend_error());
  13918. }
  13919. // PEM memory-based constructor tests (works with all TLS backends).
  13920. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13921. // terminator after it.
  13922. void PemMemoryClientCertPresent(
  13923. const std::string &client_cert_file,
  13924. const std::string &client_private_key_file,
  13925. const std::string &client_encrypted_private_key_pass = std::string(),
  13926. bool exact_size = false) {
  13927. // Read PEM files into memory
  13928. std::string server_cert_pem, server_key_pem;
  13929. std::string client_ca_pem;
  13930. std::string client_cert_pem, client_key_pem;
  13931. read_file(SERVER_CERT_FILE, server_cert_pem);
  13932. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13933. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13934. read_file(client_cert_file, client_cert_pem);
  13935. read_file(client_private_key_file, client_key_pem);
  13936. std::list<std::vector<char>> exact_copies;
  13937. auto data = [&](const std::string &pem) -> const char * {
  13938. if (!exact_size) { return pem.c_str(); }
  13939. exact_copies.emplace_back(pem.begin(), pem.end());
  13940. return exact_copies.back().data();
  13941. };
  13942. // Create server with PEM memory
  13943. SSLServer::PemMemory server_pem = {
  13944. data(server_cert_pem),
  13945. server_cert_pem.size(),
  13946. data(server_key_pem),
  13947. server_key_pem.size(),
  13948. data(client_ca_pem),
  13949. client_ca_pem.size(),
  13950. nullptr // no password for server key
  13951. };
  13952. SSLServer svr(server_pem);
  13953. ASSERT_TRUE(svr.is_valid());
  13954. svr.Get("/test", [&](const Request &req, Response &res) {
  13955. res.set_content("test", "text/plain");
  13956. auto cert = req.peer_cert();
  13957. ASSERT_TRUE(static_cast<bool>(cert));
  13958. EXPECT_EQ("Common Name", cert.subject_cn());
  13959. });
  13960. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13961. auto se = detail::scope_exit([&] {
  13962. svr.stop();
  13963. t.join();
  13964. ASSERT_FALSE(svr.is_running());
  13965. });
  13966. svr.wait_until_ready();
  13967. // Create client with PEM memory
  13968. const char *password = client_encrypted_private_key_pass.empty()
  13969. ? nullptr
  13970. : client_encrypted_private_key_pass.c_str();
  13971. SSLClient::PemMemory client_pem = {
  13972. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13973. client_key_pem.size(), password};
  13974. SSLClient cli(HOST, PORT, client_pem);
  13975. cli.enable_server_certificate_verification(false);
  13976. cli.set_connection_timeout(30);
  13977. auto res = cli.Get("/test");
  13978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13979. ASSERT_EQ(StatusCode::OK_200, res->status);
  13980. }
  13981. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13982. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13983. }
  13984. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13985. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13986. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13987. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13988. }
  13989. // A server built from PEM memory with a client CA requires client certificates,
  13990. // also when the CA is a NUL-terminated string passed with a length of 0
  13991. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13992. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13993. read_file(SERVER_CERT_FILE, server_cert_pem);
  13994. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13995. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13996. SSLServer::PemMemory server_pem = {
  13997. server_cert_pem.c_str(),
  13998. server_cert_pem.size(),
  13999. server_key_pem.c_str(),
  14000. server_key_pem.size(),
  14001. client_ca_pem.c_str(),
  14002. client_ca_pem.size(),
  14003. nullptr // no password for server key
  14004. };
  14005. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14006. SCOPED_TRACE(client_ca_pem_len);
  14007. server_pem.client_ca_pem_len = client_ca_pem_len;
  14008. SSLServer svr(server_pem);
  14009. ASSERT_TRUE(svr.is_valid());
  14010. RejectsClientWithoutCert(svr);
  14011. }
  14012. // An empty CA fails to load instead of turning the check off
  14013. server_pem.client_ca_pem = "";
  14014. server_pem.client_ca_pem_len = 0;
  14015. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14016. }
  14017. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14018. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14019. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14020. true);
  14021. }
  14022. // A length shorter than the PEM cuts it short, so it no longer loads
  14023. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14024. std::string cert, key;
  14025. read_file(SERVER_CERT_FILE, cert);
  14026. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14027. for (auto cut_cert : {true, false}) {
  14028. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14029. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14030. SSLServer::PemMemory server_pem = {
  14031. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14032. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14033. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14034. key_len, nullptr};
  14035. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14036. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14037. key.c_str(), key_len, nullptr};
  14038. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14039. }
  14040. }
  14041. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14042. class NoListenSSLServer : public SSLServer {
  14043. public:
  14044. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14045. const char *client_ca_cert_file_path,
  14046. const char *client_ca_cert_dir_path = nullptr)
  14047. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14048. client_ca_cert_dir_path),
  14049. stop_(false) {}
  14050. std::atomic_bool stop_;
  14051. private:
  14052. bool process_and_close_socket(socket_t /*sock*/) override {
  14053. // Don't create SSL context
  14054. while (!stop_.load()) {
  14055. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14056. }
  14057. return true;
  14058. }
  14059. };
  14060. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14061. CLIENT_CA_CERT_FILE);
  14062. ASSERT_TRUE(svr.is_valid());
  14063. svr.Get("/test", [&](const Request &, Response &res) {
  14064. res.set_content("test", "text/plain");
  14065. });
  14066. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14067. auto se = detail::scope_exit([&] {
  14068. svr.stop_ = true;
  14069. svr.stop();
  14070. t.join();
  14071. ASSERT_FALSE(svr.is_running());
  14072. });
  14073. svr.wait_until_ready();
  14074. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14075. cli.enable_server_certificate_verification(false);
  14076. cli.set_connection_timeout(1);
  14077. auto res = cli.Get("/test");
  14078. ASSERT_TRUE(!res);
  14079. EXPECT_EQ(Error::SSLConnection, res.error());
  14080. // Timeout results in WantRead error code (maps to backend-specific value)
  14081. EXPECT_NE(0, res.ssl_error());
  14082. }
  14083. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14084. // Test SSLServer with client certificate verification using the standard
  14085. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14086. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14087. CLIENT_CA_CERT_DIR);
  14088. ASSERT_TRUE(svr.is_valid());
  14089. svr.Get("/test", [&](const Request &req, Response &res) {
  14090. res.set_content("test", "text/plain");
  14091. auto cert = req.peer_cert();
  14092. ASSERT_TRUE(static_cast<bool>(cert));
  14093. auto common_name = cert.subject_cn();
  14094. EXPECT_EQ("Common Name", common_name);
  14095. });
  14096. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14097. auto se = detail::scope_exit([&] {
  14098. svr.stop();
  14099. t.join();
  14100. ASSERT_FALSE(svr.is_running());
  14101. });
  14102. svr.wait_until_ready();
  14103. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14104. cli.enable_server_certificate_verification(false);
  14105. cli.set_connection_timeout(30);
  14106. auto res = cli.Get("/test");
  14107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14108. ASSERT_EQ(StatusCode::OK_200, res->status);
  14109. }
  14110. // Test verify_hostname on every backend: a host is named by a SAN only
  14111. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14112. using namespace httplib::tls;
  14113. // We need a running server to test against
  14114. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14115. ASSERT_TRUE(svr.is_valid());
  14116. svr.Get("/test", [](const Request &, Response &res) {
  14117. res.set_content("ok", "text/plain");
  14118. });
  14119. thread t([&]() { svr.listen(HOST, PORT); });
  14120. auto se = detail::scope_exit([&] {
  14121. svr.stop();
  14122. t.join();
  14123. });
  14124. svr.wait_until_ready();
  14125. bool verify_callback_called = false;
  14126. bool verify_result_wrong = false;
  14127. SSLClient cli(HOST, PORT);
  14128. cli.enable_server_certificate_verification(true);
  14129. cli.set_ca_cert_path(CA_CERT_FILE);
  14130. cli.set_connection_timeout(5);
  14131. // Note: Test certificate has CN="Common Name", not "localhost"
  14132. bool verify_result_cn = false;
  14133. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14134. verify_callback_called = true;
  14135. if (!ctx.cert) return false;
  14136. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14137. verify_result_cn = ctx.check_hostname("Common Name");
  14138. // Test 2: wrong hostname should not match
  14139. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14140. return true; // Accept for the purpose of this test
  14141. });
  14142. auto res = cli.Get("/test");
  14143. // The request may succeed or fail depending on cert configuration
  14144. // but the callback should have been called
  14145. ASSERT_TRUE(verify_callback_called)
  14146. << "Verify callback should have been called";
  14147. EXPECT_FALSE(verify_result_cn)
  14148. << "verify_hostname must not match the certificate CN (no SAN)";
  14149. // Wrong hostname should not match
  14150. EXPECT_FALSE(verify_result_wrong)
  14151. << "verify_hostname should not match 'wronghost.example.com'";
  14152. }
  14153. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14154. // backend verifies it.
  14155. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14156. // Certificate CN is "localhost" and it carries no SAN.
  14157. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14158. ASSERT_TRUE(svr.is_valid());
  14159. svr.Get("/test", [](const Request &, Response &res) {
  14160. res.set_content("ok", "text/plain");
  14161. });
  14162. auto port = svr.bind_to_any_port(HOST);
  14163. thread t([&]() { svr.listen_after_bind(); });
  14164. auto se = detail::scope_exit([&] {
  14165. svr.stop();
  14166. t.join();
  14167. });
  14168. svr.wait_until_ready();
  14169. SSLClient cli("localhost", port);
  14170. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  14171. cli.enable_server_certificate_verification(true);
  14172. cli.set_connection_timeout(5);
  14173. auto res = cli.Get("/test");
  14174. ASSERT_FALSE(res);
  14175. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14176. // The same certificate is accepted once host name verification is off, so the
  14177. // failure above is the host name and not the chain.
  14178. cli.enable_server_hostname_verification(false);
  14179. res = cli.Get("/test");
  14180. ASSERT_TRUE(res) << to_string(res.error());
  14181. EXPECT_EQ(StatusCode::OK_200, res->status);
  14182. }
  14183. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14184. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14185. // X509_check_ip behavior and must hold for every backend.
  14186. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14187. using namespace httplib::tls;
  14188. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14189. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14190. ASSERT_TRUE(svr.is_valid());
  14191. svr.Get("/test", [](const Request &, Response &res) {
  14192. res.set_content("ok", "text/plain");
  14193. });
  14194. thread t([&]() { svr.listen(HOST, PORT); });
  14195. auto se = detail::scope_exit([&] {
  14196. svr.stop();
  14197. t.join();
  14198. });
  14199. svr.wait_until_ready();
  14200. bool verify_callback_called = false;
  14201. bool ip_matched_via_cn = true;
  14202. SSLClient cli(HOST, PORT);
  14203. cli.enable_server_certificate_verification(true);
  14204. cli.set_ca_cert_path(CA_CERT_FILE);
  14205. cli.set_connection_timeout(5);
  14206. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14207. verify_callback_called = true;
  14208. if (!ctx.cert) return false;
  14209. // The IP appears only in the CN, so it must NOT be accepted.
  14210. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14211. return true; // Accept for the purpose of this test
  14212. });
  14213. cli.Get("/test");
  14214. ASSERT_TRUE(verify_callback_called)
  14215. << "Verify callback should have been called";
  14216. EXPECT_FALSE(ip_matched_via_cn)
  14217. << "An IP host must not be authenticated via the certificate CN";
  14218. }
  14219. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14220. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14221. using namespace httplib::tls;
  14222. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14223. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14224. ASSERT_TRUE(svr.is_valid());
  14225. svr.Get("/test", [](const Request &, Response &res) {
  14226. res.set_content("ok", "text/plain");
  14227. });
  14228. thread t([&]() { svr.listen(HOST, PORT); });
  14229. auto se = detail::scope_exit([&] {
  14230. svr.stop();
  14231. t.join();
  14232. });
  14233. svr.wait_until_ready();
  14234. bool verify_callback_called = false;
  14235. bool san_matched = false;
  14236. bool wrong_ipv6_matched = true;
  14237. bool cn_ipv6_matched = true;
  14238. SSLClient cli(HOST, PORT);
  14239. cli.enable_server_certificate_verification(true);
  14240. cli.set_ca_cert_path(CA_CERT_FILE);
  14241. cli.set_connection_timeout(5);
  14242. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14243. verify_callback_called = true;
  14244. if (!ctx.cert) return false;
  14245. // Matches the IPv6 iPAddress SAN.
  14246. san_matched = ctx.check_hostname("2001:db8::1");
  14247. // A different IPv6 address must not match.
  14248. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14249. // "::1" lives only in the CN, so it must not be accepted.
  14250. cn_ipv6_matched = ctx.check_hostname("::1");
  14251. return true; // Accept for the purpose of this test
  14252. });
  14253. cli.Get("/test");
  14254. ASSERT_TRUE(verify_callback_called)
  14255. << "Verify callback should have been called";
  14256. EXPECT_TRUE(san_matched)
  14257. << "verify_hostname should match an IPv6 iPAddress SAN";
  14258. EXPECT_FALSE(wrong_ipv6_matched)
  14259. << "verify_hostname should not match a non-matching IPv6 address";
  14260. EXPECT_FALSE(cn_ipv6_matched)
  14261. << "An IPv6 host must not be authenticated via the certificate CN";
  14262. }
  14263. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14264. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14265. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14266. using namespace httplib::tls;
  14267. // SANs: DNS:a.zz, IP:42.46.122.122
  14268. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14269. ASSERT_TRUE(svr.is_valid());
  14270. svr.Get("/test", [](const Request &, Response &res) {
  14271. res.set_content("ok", "text/plain");
  14272. });
  14273. auto port = svr.bind_to_any_port(HOST);
  14274. thread t([&]() { svr.listen_after_bind(); });
  14275. auto se = detail::scope_exit([&] {
  14276. svr.stop();
  14277. t.join();
  14278. });
  14279. svr.wait_until_ready();
  14280. bool verify_callback_called = false;
  14281. bool dns_san_matched = false;
  14282. bool ip_san_matched = false;
  14283. bool ip_matched_via_dns_san = true;
  14284. bool dns_matched_via_ip_san = true;
  14285. bool cn_matched_next_to_dns_san = true;
  14286. SSLClient cli(HOST, port);
  14287. cli.enable_server_certificate_verification(true);
  14288. cli.set_ca_cert_path(CA_CERT_FILE);
  14289. cli.set_connection_timeout(5);
  14290. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14291. verify_callback_called = true;
  14292. if (!ctx.cert) return false;
  14293. dns_san_matched = ctx.check_hostname("a.zz");
  14294. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14295. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14296. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14297. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14298. return true; // Accept for the purpose of this test
  14299. });
  14300. cli.Get("/test");
  14301. ASSERT_TRUE(verify_callback_called)
  14302. << "Verify callback should have been called";
  14303. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14304. EXPECT_TRUE(ip_san_matched)
  14305. << "verify_hostname should match an iPAddress SAN";
  14306. EXPECT_FALSE(ip_matched_via_dns_san)
  14307. << "An IP host must not be authenticated via a dNSName SAN";
  14308. EXPECT_FALSE(dns_matched_via_ip_san)
  14309. << "A DNS host must not be authenticated via an iPAddress SAN";
  14310. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14311. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14312. }
  14313. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14314. // "www.*.example.test" names one host and not every host under example.test.
  14315. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14316. using namespace httplib::tls;
  14317. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14318. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14319. ASSERT_TRUE(svr.is_valid());
  14320. svr.Get("/test", [](const Request &, Response &res) {
  14321. res.set_content("ok", "text/plain");
  14322. });
  14323. auto port = svr.bind_to_any_port(HOST);
  14324. thread t([&]() { svr.listen_after_bind(); });
  14325. auto se = detail::scope_exit([&] {
  14326. svr.stop();
  14327. t.join();
  14328. });
  14329. svr.wait_until_ready();
  14330. bool verify_callback_called = false;
  14331. bool leftmost_wildcard_matched = false;
  14332. bool wildcard_spanned_labels = true;
  14333. bool inner_wildcard_matched = true;
  14334. SSLClient cli(HOST, port);
  14335. cli.enable_server_certificate_verification(true);
  14336. cli.set_ca_cert_path(CA_CERT_FILE);
  14337. cli.set_connection_timeout(5);
  14338. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14339. verify_callback_called = true;
  14340. if (!ctx.cert) return false;
  14341. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14342. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14343. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14344. return true; // Accept for the purpose of this test
  14345. });
  14346. cli.Get("/test");
  14347. ASSERT_TRUE(verify_callback_called)
  14348. << "Verify callback should have been called";
  14349. EXPECT_TRUE(leftmost_wildcard_matched)
  14350. << "A leftmost wildcard should match a single label";
  14351. EXPECT_FALSE(wildcard_spanned_labels)
  14352. << "A wildcard label must not match more than one label";
  14353. EXPECT_FALSE(inner_wildcard_matched)
  14354. << "A wildcard outside the leftmost label must not be honoured";
  14355. }
  14356. // sans() must report each SAN entry under its own type.
  14357. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14358. using namespace httplib::tls;
  14359. // SANs: DNS:a.zz, IP:42.46.122.122
  14360. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14361. ASSERT_TRUE(svr.is_valid());
  14362. svr.Get("/test", [](const Request &, Response &res) {
  14363. res.set_content("ok", "text/plain");
  14364. });
  14365. auto port = svr.bind_to_any_port(HOST);
  14366. thread t([&]() { svr.listen_after_bind(); });
  14367. auto se = detail::scope_exit([&] {
  14368. svr.stop();
  14369. t.join();
  14370. });
  14371. svr.wait_until_ready();
  14372. bool verify_callback_called = false;
  14373. std::vector<SanEntry> sans;
  14374. SSLClient cli(HOST, port);
  14375. cli.enable_server_certificate_verification(true);
  14376. cli.set_ca_cert_path(CA_CERT_FILE);
  14377. cli.set_connection_timeout(5);
  14378. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14379. verify_callback_called = true;
  14380. if (!ctx.cert) return false;
  14381. sans = ctx.sans();
  14382. return true; // Accept for the purpose of this test
  14383. });
  14384. cli.Get("/test");
  14385. ASSERT_TRUE(verify_callback_called)
  14386. << "Verify callback should have been called";
  14387. auto has_san = [&](SanType type, const std::string &value) {
  14388. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14389. return san.type == type && san.value == value;
  14390. });
  14391. };
  14392. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14393. << "sans() should report the dNSName SAN";
  14394. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14395. << "sans() should report the iPAddress SAN";
  14396. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14397. << "sans() must not report the dNSName SAN as an address";
  14398. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14399. << "sans() must not report the iPAddress SAN as a DNS name";
  14400. }
  14401. #endif
  14402. // mbedTLS-specific callback constructor test
  14403. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14404. #ifdef CPPHTTPLIB_SSL_ENABLED
  14405. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14406. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14407. ASSERT_TRUE(svr.is_valid());
  14408. // Set up a handler to verify client certificate is present
  14409. bool client_cert_verified = false;
  14410. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14411. // Verify that client certificate was provided
  14412. client_cert_verified = true;
  14413. res.set_content("success", "text/plain");
  14414. });
  14415. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14416. auto se = detail::scope_exit([&] {
  14417. svr.stop();
  14418. t.join();
  14419. ASSERT_FALSE(svr.is_running());
  14420. });
  14421. svr.wait_until_ready();
  14422. // Client with certificate
  14423. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14424. cli.enable_server_certificate_verification(false);
  14425. cli.set_connection_timeout(30);
  14426. auto res = cli.Get("/test");
  14427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14428. ASSERT_EQ(StatusCode::OK_200, res->status);
  14429. ASSERT_TRUE(client_cert_verified);
  14430. EXPECT_EQ("success", res->body);
  14431. }
  14432. #endif
  14433. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14434. // backends
  14435. #ifdef CPPHTTPLIB_SSL_ENABLED
  14436. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14437. using namespace httplib::tls;
  14438. // Test that when client CA cert file is provided,
  14439. // the server properly requests and validates client certificates
  14440. // Create a server with client authentication
  14441. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14442. ASSERT_TRUE(svr.is_valid());
  14443. bool handler_called = false;
  14444. svr.Get("/test", [&](const Request &req, Response &res) {
  14445. handler_called = true;
  14446. // Verify that a client certificate was provided
  14447. auto cert = req.peer_cert();
  14448. ASSERT_TRUE(static_cast<bool>(cert));
  14449. // Get the issuer name
  14450. std::string issuer_str = cert.issuer_name();
  14451. ASSERT_FALSE(issuer_str.empty());
  14452. // The client certificate should be issued by our test CA
  14453. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14454. res.set_content("authenticated", "text/plain");
  14455. });
  14456. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14457. auto se = detail::scope_exit([&] {
  14458. svr.stop();
  14459. t.join();
  14460. ASSERT_FALSE(svr.is_running());
  14461. });
  14462. svr.wait_until_ready();
  14463. // Connect with a client certificate issued by the CA
  14464. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14465. cli.enable_server_certificate_verification(false);
  14466. cli.set_connection_timeout(30);
  14467. auto res = cli.Get("/test");
  14468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14469. ASSERT_EQ(StatusCode::OK_200, res->status);
  14470. ASSERT_TRUE(handler_called);
  14471. EXPECT_EQ("authenticated", res->body);
  14472. }
  14473. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14474. using namespace httplib::tls;
  14475. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14476. ASSERT_TRUE(svr.is_valid());
  14477. svr.Get("/test", [](const Request &, Response &res) {
  14478. res.set_content("ok", "text/plain");
  14479. });
  14480. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14481. auto se = detail::scope_exit([&] {
  14482. svr.stop();
  14483. t.join();
  14484. });
  14485. svr.wait_until_ready();
  14486. SSLClient cli(HOST, PORT);
  14487. cli.enable_server_certificate_verification(false);
  14488. cli.set_connection_timeout(30);
  14489. bool cert_checked = false;
  14490. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14491. if (ctx.cert) {
  14492. auto sans = ctx.sans();
  14493. // Test certificate may or may not have SANs - just verify the API
  14494. // works If SANs exist, verify the types are valid
  14495. for (const auto &san : sans) {
  14496. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14497. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14498. san.type == SanType::OTHER);
  14499. EXPECT_FALSE(san.value.empty());
  14500. }
  14501. cert_checked = true;
  14502. }
  14503. return true;
  14504. });
  14505. auto res = cli.Get("/test");
  14506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14507. EXPECT_TRUE(cert_checked);
  14508. }
  14509. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14510. using namespace httplib::tls;
  14511. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14512. ASSERT_TRUE(svr.is_valid());
  14513. svr.Get("/test", [](const Request &, Response &res) {
  14514. res.set_content("ok", "text/plain");
  14515. });
  14516. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14517. auto se = detail::scope_exit([&] {
  14518. svr.stop();
  14519. t.join();
  14520. });
  14521. svr.wait_until_ready();
  14522. SSLClient cli(HOST, PORT);
  14523. cli.enable_server_certificate_verification(false);
  14524. cli.set_connection_timeout(30);
  14525. bool validity_checked = false;
  14526. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14527. if (ctx.cert) {
  14528. time_t not_before = 0, not_after = 0;
  14529. bool result = ctx.validity(not_before, not_after);
  14530. EXPECT_TRUE(result);
  14531. // Verify that not_before < now < not_after for a valid cert
  14532. time_t now = time(nullptr);
  14533. EXPECT_LT(not_before, now);
  14534. EXPECT_GT(not_after, now);
  14535. validity_checked = true;
  14536. }
  14537. return true;
  14538. });
  14539. auto res = cli.Get("/test");
  14540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14541. EXPECT_TRUE(validity_checked);
  14542. }
  14543. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14544. using namespace httplib::tls;
  14545. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14546. ASSERT_TRUE(svr.is_valid());
  14547. svr.Get("/test", [](const Request &, Response &res) {
  14548. res.set_content("ok", "text/plain");
  14549. });
  14550. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14551. auto se = detail::scope_exit([&] {
  14552. svr.stop();
  14553. t.join();
  14554. });
  14555. svr.wait_until_ready();
  14556. SSLClient cli(HOST, PORT);
  14557. cli.enable_server_certificate_verification(false);
  14558. cli.set_connection_timeout(30);
  14559. bool serial_checked = false;
  14560. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14561. if (ctx.cert) {
  14562. std::string serial = ctx.serial();
  14563. EXPECT_FALSE(serial.empty());
  14564. // Serial should be a hex string
  14565. for (char c : serial) {
  14566. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14567. (c >= 'a' && c <= 'f'));
  14568. }
  14569. serial_checked = true;
  14570. }
  14571. return true;
  14572. });
  14573. auto res = cli.Get("/test");
  14574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14575. EXPECT_TRUE(serial_checked);
  14576. }
  14577. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14578. // Test 1: Valid CA file - no error should be recorded
  14579. {
  14580. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14581. CLIENT_CA_CERT_FILE);
  14582. ASSERT_TRUE(svr.is_valid());
  14583. // With valid setup, last_ssl_error should be 0
  14584. EXPECT_EQ(0, svr.ssl_last_error());
  14585. }
  14586. // Test 2: Invalid CA file content
  14587. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14588. {
  14589. // Create a temporary file with completely invalid content
  14590. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14591. {
  14592. std::ofstream ofs(temp_invalid_ca);
  14593. ofs << "This is not a certificate file at all\n";
  14594. ofs << "Just plain text content\n";
  14595. }
  14596. // Create server with invalid CA file
  14597. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14598. // Clean up temporary file
  14599. std::remove(temp_invalid_ca);
  14600. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14601. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14602. // Note: SSL_CTX_load_verify_locations typically fails first,
  14603. // but our error handling code path is still exercised
  14604. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14605. }
  14606. }
  14607. TEST(VerifyCallbackTest, VerifyContextFields) {
  14608. using namespace httplib::tls;
  14609. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14610. ASSERT_TRUE(svr.is_valid());
  14611. svr.Get("/test", [](const Request &, Response &res) {
  14612. res.set_content("ok", "text/plain");
  14613. });
  14614. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14615. auto se = detail::scope_exit([&] {
  14616. svr.stop();
  14617. t.join();
  14618. });
  14619. svr.wait_until_ready();
  14620. SSLClient cli(HOST, PORT);
  14621. cli.enable_server_certificate_verification(false);
  14622. cli.set_connection_timeout(30);
  14623. int callback_count = 0;
  14624. bool saw_leaf_cert = false;
  14625. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14626. if (ctx.cert) {
  14627. callback_count++;
  14628. // We should see at least one certificate (the leaf)
  14629. std::string cn = ctx.subject_cn();
  14630. if (!cn.empty()) { saw_leaf_cert = true; }
  14631. // Verify context fields are populated
  14632. EXPECT_NE(ctx.session, nullptr);
  14633. EXPECT_GE(ctx.depth, 0);
  14634. }
  14635. return true;
  14636. });
  14637. auto res = cli.Get("/test");
  14638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14639. EXPECT_GT(callback_count, 0);
  14640. EXPECT_TRUE(saw_leaf_cert);
  14641. }
  14642. // A verifier that accepts runs alongside the built-in verification, and is the
  14643. // only check once that is turned off.
  14644. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14645. using namespace httplib::tls;
  14646. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14647. ASSERT_TRUE(svr.is_valid());
  14648. svr.Get("/test", [](const Request &, Response &res) {
  14649. res.set_content("ok", "text/plain");
  14650. });
  14651. auto port = svr.bind_to_any_port(HOST);
  14652. thread t([&]() { svr.listen_after_bind(); });
  14653. auto se = detail::scope_exit([&] {
  14654. svr.stop();
  14655. t.join();
  14656. });
  14657. svr.wait_until_ready();
  14658. SSLClient cli(HOST, port);
  14659. cli.enable_server_hostname_verification(false);
  14660. auto calls = 0;
  14661. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14662. calls++;
  14663. return true;
  14664. });
  14665. // cert.pem is not trusted
  14666. auto res = cli.Get("/test");
  14667. ASSERT_FALSE(res);
  14668. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14669. EXPECT_GT(calls, 0);
  14670. cli.enable_server_certificate_verification(false);
  14671. res = cli.Get("/test");
  14672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14673. EXPECT_EQ("ok", res->body);
  14674. }
  14675. // A verifier belongs to the client that set it, not to the thread that set it.
  14676. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14677. using namespace httplib::tls;
  14678. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14679. ASSERT_TRUE(svr.is_valid());
  14680. svr.Get("/test", [](const Request &, Response &res) {
  14681. res.set_content("ok", "text/plain");
  14682. });
  14683. auto port = svr.bind_to_any_port(HOST);
  14684. thread t([&]() { svr.listen_after_bind(); });
  14685. auto se = detail::scope_exit([&] {
  14686. svr.stop();
  14687. t.join();
  14688. });
  14689. svr.wait_until_ready();
  14690. auto rejecting_calls = 0;
  14691. SSLClient rejecting(HOST, port);
  14692. rejecting.enable_server_certificate_verification(false);
  14693. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14694. rejecting_calls++;
  14695. return false;
  14696. });
  14697. auto accepting_calls = 0;
  14698. SSLClient accepting(HOST, port);
  14699. accepting.enable_server_certificate_verification(false);
  14700. // Set on another thread than the requests below.
  14701. thread([&]() {
  14702. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14703. accepting_calls++;
  14704. return true;
  14705. });
  14706. }).join();
  14707. // Requested on another thread than the verifier was set on.
  14708. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14709. EXPECT_GT(rejecting_calls, 0);
  14710. auto res = accepting.Get("/test");
  14711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14712. EXPECT_GT(accepting_calls, 0);
  14713. }
  14714. // A verifier replaced while a handshake runs it lives until it returns.
  14715. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14716. using namespace httplib::tls;
  14717. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14718. ASSERT_TRUE(svr.is_valid());
  14719. svr.Get("/test", [](const Request &, Response &res) {
  14720. res.set_content("ok", "text/plain");
  14721. });
  14722. auto port = svr.bind_to_any_port(HOST);
  14723. thread t([&]() { svr.listen_after_bind(); });
  14724. auto se = detail::scope_exit([&] {
  14725. svr.stop();
  14726. t.join();
  14727. });
  14728. svr.wait_until_ready();
  14729. SSLClient cli(HOST, port);
  14730. cli.enable_server_certificate_verification(false);
  14731. std::promise<void> entered;
  14732. std::promise<void> replaced;
  14733. auto replaced_future = replaced.get_future();
  14734. auto first_call = true;
  14735. // Long enough to live on the heap
  14736. std::string expected(64, 'v');
  14737. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14738. if (first_call) {
  14739. first_call = false;
  14740. entered.set_value();
  14741. replaced_future.wait();
  14742. }
  14743. return expected == std::string(64, 'v');
  14744. });
  14745. thread request([&]() {
  14746. auto res = cli.Get("/test");
  14747. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14748. });
  14749. entered.get_future().wait();
  14750. cli.set_server_certificate_verifier(
  14751. [](const VerifyContext &) { return true; });
  14752. replaced.set_value();
  14753. request.join();
  14754. }
  14755. // VerifyContext::session is the same handle the other tls:: functions take.
  14756. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14757. using namespace httplib::tls;
  14758. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14759. ASSERT_TRUE(svr.is_valid());
  14760. svr.Get("/test", [](const Request &, Response &res) {
  14761. res.set_content("ok", "text/plain");
  14762. });
  14763. auto port = svr.bind_to_any_port(HOST);
  14764. thread t([&]() { svr.listen_after_bind(); });
  14765. auto se = detail::scope_exit([&] {
  14766. svr.stop();
  14767. t.join();
  14768. });
  14769. svr.wait_until_ready();
  14770. SSLClient cli(HOST, port);
  14771. cli.enable_server_certificate_verification(false);
  14772. session_t verifier_session = nullptr;
  14773. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14774. verifier_session = ctx.session;
  14775. return true;
  14776. });
  14777. session_t session_verifier_session = nullptr;
  14778. cli.set_session_verifier([&](session_t session) {
  14779. session_verifier_session = session;
  14780. return SSLVerifierResponse::NoDecisionMade;
  14781. });
  14782. auto res = cli.Get("/test");
  14783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14784. EXPECT_NE(nullptr, verifier_session);
  14785. EXPECT_EQ(session_verifier_session, verifier_session);
  14786. }
  14787. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14788. using httplib::tls::TlsError;
  14789. // Test that verify_error_to_string returns empty for success
  14790. std::string success_str = TlsError::verify_error_to_string(0);
  14791. EXPECT_TRUE(success_str.empty());
  14792. // Test that verify_error_to_string returns non-empty for error codes
  14793. // Using a common error code (certificate expired)
  14794. std::string error_str =
  14795. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14796. EXPECT_FALSE(error_str.empty());
  14797. }
  14798. TEST(SessionVerifierTest, CertificateAccepted) {
  14799. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14800. ASSERT_TRUE(svr.is_valid());
  14801. svr.Get("/test", [](const Request &, Response &res) {
  14802. res.set_content("ok", "text/plain");
  14803. });
  14804. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14805. auto se = detail::scope_exit([&] {
  14806. svr.stop();
  14807. t.join();
  14808. });
  14809. svr.wait_until_ready();
  14810. SSLClient cli(HOST, PORT);
  14811. cli.enable_server_certificate_verification(false);
  14812. cli.set_connection_timeout(30);
  14813. bool callback_called = false;
  14814. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14815. EXPECT_NE(session, nullptr);
  14816. callback_called = true;
  14817. return SSLVerifierResponse::CertificateAccepted;
  14818. });
  14819. auto res = cli.Get("/test");
  14820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14821. EXPECT_EQ(200, res->status);
  14822. EXPECT_TRUE(callback_called);
  14823. }
  14824. TEST(SessionVerifierTest, CertificateRejected) {
  14825. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14826. ASSERT_TRUE(svr.is_valid());
  14827. svr.Get("/test", [](const Request &, Response &res) {
  14828. res.set_content("ok", "text/plain");
  14829. });
  14830. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14831. auto se = detail::scope_exit([&] {
  14832. svr.stop();
  14833. t.join();
  14834. });
  14835. svr.wait_until_ready();
  14836. SSLClient cli(HOST, PORT);
  14837. cli.enable_server_certificate_verification(false);
  14838. cli.set_connection_timeout(30);
  14839. bool callback_called = false;
  14840. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14841. EXPECT_NE(session, nullptr);
  14842. callback_called = true;
  14843. return SSLVerifierResponse::CertificateRejected;
  14844. });
  14845. auto res = cli.Get("/test");
  14846. EXPECT_FALSE(res);
  14847. EXPECT_TRUE(callback_called);
  14848. }
  14849. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14850. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14851. ASSERT_TRUE(svr.is_valid());
  14852. svr.Get("/test", [](const Request &, Response &res) {
  14853. res.set_content("ok", "text/plain");
  14854. });
  14855. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14856. auto se = detail::scope_exit([&] {
  14857. svr.stop();
  14858. t.join();
  14859. });
  14860. svr.wait_until_ready();
  14861. // NoDecisionMade with verification disabled should succeed (no default check)
  14862. SSLClient cli(HOST, PORT);
  14863. cli.enable_server_certificate_verification(false);
  14864. cli.set_connection_timeout(30);
  14865. bool callback_called = false;
  14866. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14867. EXPECT_NE(session, nullptr);
  14868. callback_called = true;
  14869. return SSLVerifierResponse::NoDecisionMade;
  14870. });
  14871. auto res = cli.Get("/test");
  14872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14873. EXPECT_EQ(200, res->status);
  14874. EXPECT_TRUE(callback_called);
  14875. }
  14876. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14877. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14878. ASSERT_TRUE(svr.is_valid());
  14879. svr.Get("/test", [](const Request &, Response &res) {
  14880. res.set_content("ok", "text/plain");
  14881. });
  14882. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14883. auto se = detail::scope_exit([&] {
  14884. svr.stop();
  14885. t.join();
  14886. });
  14887. svr.wait_until_ready();
  14888. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14889. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14890. // so we only check that the request fails, not whether the callback was
  14891. // called.
  14892. SSLClient cli(HOST, PORT);
  14893. cli.enable_server_certificate_verification(true);
  14894. cli.set_connection_timeout(30);
  14895. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14896. EXPECT_NE(session, nullptr);
  14897. return SSLVerifierResponse::NoDecisionMade;
  14898. });
  14899. auto res = cli.Get("/test");
  14900. EXPECT_FALSE(res);
  14901. }
  14902. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14903. // Test SSL server using PemMemory constructor with client CA certificates
  14904. // Read PEM files
  14905. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14906. read_file(SERVER_CERT_FILE, server_cert_pem);
  14907. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14908. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14909. // Create SSLServer with PemMemory constructor including client CA
  14910. SSLServer::PemMemory server_pem = {
  14911. server_cert_pem.c_str(),
  14912. server_cert_pem.size(),
  14913. server_key_pem.c_str(),
  14914. server_key_pem.size(),
  14915. client_ca_pem.c_str(),
  14916. client_ca_pem.size(),
  14917. nullptr // no password for server key
  14918. };
  14919. SSLServer svr(server_pem);
  14920. ASSERT_TRUE(svr.is_valid());
  14921. // No SSL error should be recorded for valid setup
  14922. EXPECT_EQ(0, svr.ssl_last_error());
  14923. // Set up server endpoints
  14924. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14925. res.set_content("ok", "text/plain");
  14926. });
  14927. // Start server in a thread
  14928. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14929. svr.wait_until_ready();
  14930. // Connect with client certificate (using constructor with paths)
  14931. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14932. cli.enable_server_certificate_verification(false);
  14933. auto res = cli.Get("/test-pem-ca");
  14934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14935. EXPECT_EQ(200, res->status);
  14936. EXPECT_EQ("ok", res->body);
  14937. svr.stop();
  14938. server_thread.join();
  14939. }
  14940. #endif
  14941. #ifdef _WIN32
  14942. TEST(CleanupTest, WSACleanup) {
  14943. int ret = WSACleanup();
  14944. ASSERT_EQ(0, ret);
  14945. }
  14946. #endif
  14947. #ifndef CPPHTTPLIB_SSL_ENABLED
  14948. TEST(NoSSLSupport, SimpleInterface) {
  14949. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14950. }
  14951. #endif
  14952. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14953. TEST(InvalidScheme, SimpleInterface) {
  14954. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14955. }
  14956. #endif
  14957. TEST(NoScheme, SimpleInterface) {
  14958. Client cli("yahoo.com:80");
  14959. ASSERT_TRUE(cli.is_valid());
  14960. }
  14961. TEST(SendAPI, SimpleInterface_Online) {
  14962. Client cli("http://yahoo.com");
  14963. Request req;
  14964. req.method = "GET";
  14965. req.path = "/";
  14966. auto res = cli.send(req);
  14967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14968. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14969. }
  14970. TEST(SendAPI, WithParamsInRequest) {
  14971. Server svr;
  14972. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14973. EXPECT_TRUE(req.has_param("test"));
  14974. EXPECT_EQ("test_value", req.get_param_value("test"));
  14975. });
  14976. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14977. auto se = detail::scope_exit([&] {
  14978. svr.stop();
  14979. t.join();
  14980. ASSERT_FALSE(svr.is_running());
  14981. });
  14982. svr.wait_until_ready();
  14983. Client cli(HOST, PORT);
  14984. {
  14985. Request req;
  14986. req.method = "GET";
  14987. req.path = "/";
  14988. req.params.emplace("test", "test_value");
  14989. auto res = cli.send(req);
  14990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14991. }
  14992. {
  14993. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14995. }
  14996. }
  14997. TEST(ClientImplMethods, GetSocketTest) {
  14998. httplib::Server svr;
  14999. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15000. res.status = StatusCode::OK_200;
  15001. });
  15002. auto port = svr.bind_to_any_port("127.0.0.1");
  15003. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15004. auto se = detail::scope_exit([&] {
  15005. svr.stop();
  15006. thread.join();
  15007. ASSERT_FALSE(svr.is_running());
  15008. });
  15009. svr.wait_until_ready();
  15010. {
  15011. httplib::Client cli("127.0.0.1", port);
  15012. cli.set_keep_alive(true);
  15013. // Use the behavior of cpp-httplib of opening the connection
  15014. // only when the first request happens. If that changes,
  15015. // this test would be obsolete.
  15016. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15017. // This also implicitly tests the server. But other tests would fail much
  15018. // earlier than this one to be considered.
  15019. auto res = cli.Get("/");
  15020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15021. EXPECT_EQ(StatusCode::OK_200, res->status);
  15022. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15023. }
  15024. }
  15025. #ifdef CPPHTTPLIB_SSL_ENABLED
  15026. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15027. Client cli("http://yahoo.com");
  15028. auto res = cli.Get("/");
  15029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15030. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15031. cli.set_follow_location(true);
  15032. res = cli.Get("/");
  15033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15034. EXPECT_EQ(StatusCode::OK_200, res->status);
  15035. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15036. }
  15037. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15038. Client cli("https://yahoo.com");
  15039. auto res = cli.Get("/");
  15040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15041. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15042. cli.set_follow_location(true);
  15043. res = cli.Get("/");
  15044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15045. EXPECT_EQ(StatusCode::OK_200, res->status);
  15046. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15047. }
  15048. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15049. Client cli("https://yahoo.com");
  15050. auto res = cli.Get("/");
  15051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15052. ASSERT_FALSE(!res);
  15053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15054. ASSERT_FALSE(res == nullptr);
  15055. ASSERT_TRUE(res != nullptr);
  15056. EXPECT_EQ(Error::Success, res.error());
  15057. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15058. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15059. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15060. cli.set_follow_location(true);
  15061. res = cli.Get("/");
  15062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15063. EXPECT_EQ(Error::Success, res.error());
  15064. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15065. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15066. EXPECT_EQ(StatusCode::OK_200, res->status);
  15067. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15068. }
  15069. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15070. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15071. Client cli("https://cdnjs.cloudflare.com");
  15072. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15073. Headers{{"Accept-Encoding", "br"}});
  15074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15075. EXPECT_EQ(StatusCode::OK_200, res->status);
  15076. EXPECT_EQ(287630U, res->body.size());
  15077. EXPECT_EQ("application/javascript; charset=utf-8",
  15078. res->get_header_value("Content-Type"));
  15079. }
  15080. #endif
  15081. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15082. #undef REDIR_HOST // Silence compiler warning
  15083. #define REDIR_HOST "https://httpbingo.org"
  15084. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15085. Client cli(REDIR_HOST);
  15086. cli.set_follow_location(true);
  15087. auto res =
  15088. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15090. EXPECT_EQ(StatusCode::OK_200, res->status);
  15091. }
  15092. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15093. Client cli(REDIR_HOST);
  15094. cli.set_follow_location(true);
  15095. Params params;
  15096. params.emplace("url", "http://example.com");
  15097. params.emplace("status_code", "302");
  15098. auto res = cli.Get(REDIR_PATH, params, Headers{});
  15099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15100. EXPECT_EQ(StatusCode::OK_200, res->status);
  15101. }
  15102. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15103. Client cli(REDIR_HOST);
  15104. cli.set_follow_location(true);
  15105. Params params;
  15106. params.emplace("url", "http://example.com");
  15107. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15109. EXPECT_EQ(StatusCode::OK_200, res->status);
  15110. }
  15111. TEST(HttpToHttpsRedirectTest, CertFile) {
  15112. auto ssl_port = PORT + 1;
  15113. Server svr;
  15114. ASSERT_TRUE(svr.is_valid());
  15115. svr.Get("/index", [&](const Request &, Response &res) {
  15116. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15117. "/index");
  15118. svr.stop();
  15119. });
  15120. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15121. ASSERT_TRUE(ssl_svr.is_valid());
  15122. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15123. res.set_content("test", "text/plain");
  15124. ssl_svr.stop();
  15125. });
  15126. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15127. thread t2 =
  15128. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15129. auto se = detail::scope_exit([&] {
  15130. t2.join();
  15131. t.join();
  15132. ASSERT_FALSE(svr.is_running());
  15133. });
  15134. svr.wait_until_ready();
  15135. ssl_svr.wait_until_ready();
  15136. Client cli("127.0.0.1", PORT);
  15137. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15138. cli.enable_server_certificate_verification(true);
  15139. cli.set_follow_location(true);
  15140. cli.set_connection_timeout(30);
  15141. auto res = cli.Get("/index");
  15142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15143. ASSERT_EQ(StatusCode::OK_200, res->status);
  15144. }
  15145. TEST(SSLClientRedirectTest, CertFile) {
  15146. auto ssl_port = PORT + 1;
  15147. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15148. ASSERT_TRUE(ssl_svr1.is_valid());
  15149. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15150. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15151. "/index");
  15152. ssl_svr1.stop();
  15153. });
  15154. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15155. ASSERT_TRUE(ssl_svr2.is_valid());
  15156. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15157. res.set_content("test", "text/plain");
  15158. ssl_svr2.stop();
  15159. });
  15160. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15161. thread t2 =
  15162. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15163. auto se = detail::scope_exit([&] {
  15164. t2.join();
  15165. t.join();
  15166. ASSERT_FALSE(ssl_svr1.is_running());
  15167. });
  15168. ssl_svr1.wait_until_ready();
  15169. ssl_svr2.wait_until_ready();
  15170. SSLClient cli("127.0.0.1", PORT);
  15171. std::string cert;
  15172. read_file(SERVER_CERT2_FILE, cert);
  15173. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15174. cli.enable_server_certificate_verification(true);
  15175. cli.set_follow_location(true);
  15176. cli.set_connection_timeout(30);
  15177. auto res = cli.Get("/index");
  15178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15179. ASSERT_EQ(StatusCode::OK_200, res->status);
  15180. }
  15181. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15182. // another port, so the client follows it with a new client.
  15183. static Result GetThroughTlsRedirectToDifferentPort(
  15184. const std::function<void(SSLClient &)> &setup,
  15185. const char *target_cert = SERVER_CERT2_FILE,
  15186. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15187. auto ssl_port = PORT + 1;
  15188. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15189. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15190. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15191. "/index");
  15192. });
  15193. SSLServer ssl_svr2(target_cert, target_key);
  15194. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15195. res.set_content("test", "text/plain");
  15196. });
  15197. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15198. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15199. auto se = detail::scope_exit([&] {
  15200. ssl_svr2.stop();
  15201. ssl_svr1.stop();
  15202. t2.join();
  15203. t.join();
  15204. });
  15205. ssl_svr1.wait_until_ready();
  15206. ssl_svr2.wait_until_ready();
  15207. SSLClient cli("127.0.0.1", PORT);
  15208. cli.set_follow_location(true);
  15209. cli.set_connection_timeout(30);
  15210. setup(cli);
  15211. return cli.Get("/index");
  15212. }
  15213. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15214. auto calls = 0;
  15215. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15216. cli.enable_server_certificate_verification(false);
  15217. // Accept the first server only.
  15218. cli.set_session_verifier([&](tls::session_t) {
  15219. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15220. : SSLVerifierResponse::CertificateRejected;
  15221. });
  15222. });
  15223. ASSERT_FALSE(res);
  15224. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15225. EXPECT_EQ(2, calls);
  15226. }
  15227. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15228. std::string pinned;
  15229. auto res = GetThroughTlsRedirectToDifferentPort(
  15230. [&](SSLClient &cli) {
  15231. cli.enable_server_certificate_verification(false);
  15232. // Pin the first certificate seen.
  15233. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15234. if (pinned.empty()) { pinned = ctx.serial(); }
  15235. return ctx.serial() == pinned;
  15236. });
  15237. },
  15238. // A certificate other than the first server's.
  15239. SERVER_CERT_FILE);
  15240. EXPECT_FALSE(res);
  15241. EXPECT_FALSE(pinned.empty());
  15242. }
  15243. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15244. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15245. std::string cert;
  15246. read_file(SERVER_CERT2_FILE, cert);
  15247. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15248. });
  15249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15250. EXPECT_EQ(StatusCode::OK_200, res->status);
  15251. }
  15252. // The target's certificate is signed by the root CA, which the first server's
  15253. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15254. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15255. auto res = GetThroughTlsRedirectToDifferentPort(
  15256. [](SSLClient &cli) {
  15257. std::string root_ca, cert;
  15258. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15259. read_file(SERVER_CERT2_FILE, cert);
  15260. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15261. cli.load_ca_cert_store(cert.data(), cert.size());
  15262. cli.enable_server_hostname_verification(false);
  15263. },
  15264. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15266. EXPECT_EQ(StatusCode::OK_200, res->status);
  15267. }
  15268. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15269. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15270. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15271. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15272. auto res = GetThroughTlsRedirectToDifferentPort(
  15273. [](SSLClient &cli) {
  15274. std::string root_ca, cert;
  15275. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15276. read_file(SERVER_CERT2_FILE, cert);
  15277. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15278. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15279. cli.enable_server_hostname_verification(false);
  15280. },
  15281. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15282. ASSERT_FALSE(res);
  15283. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15284. }
  15285. #endif
  15286. #endif
  15287. #ifdef CPPHTTPLIB_SSL_ENABLED
  15288. // Test that set_ca_cert_store() skips system certs (consistent with
  15289. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15290. // should be trusted - system certs should NOT be loaded.
  15291. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15292. // Load a specific cert that is NOT a system CA cert
  15293. std::string cert;
  15294. read_file(SERVER_CERT2_FILE, cert);
  15295. SSLClient cli("google.com");
  15296. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15297. cli.enable_server_certificate_verification(true);
  15298. // This should FAIL because:
  15299. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15300. // 2. System certs should NOT be loaded when custom store is set
  15301. // If system certs WERE loaded, this would succeed
  15302. auto res = cli.Get("/");
  15303. ASSERT_FALSE(res);
  15304. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15305. }
  15306. // Same as above, but through the native store handle path. Regression test:
  15307. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15308. // merged system certs into the user-provided store.
  15309. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15310. std::string cert;
  15311. read_file(SERVER_CERT2_FILE, cert);
  15312. SSLClient cli("google.com");
  15313. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15314. cli.enable_server_certificate_verification(true);
  15315. auto res = cli.Get("/");
  15316. ASSERT_FALSE(res);
  15317. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15318. }
  15319. // A custom store set via the native handle must still verify a server whose
  15320. // cert it does contain.
  15321. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15322. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15323. ASSERT_TRUE(svr.is_valid());
  15324. svr.Get("/test", [&](const Request &, Response &res) {
  15325. res.set_content("test", "text/plain");
  15326. });
  15327. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15328. auto se = detail::scope_exit([&] {
  15329. svr.stop();
  15330. t.join();
  15331. ASSERT_FALSE(svr.is_running());
  15332. });
  15333. svr.wait_until_ready();
  15334. SSLClient cli("127.0.0.1", PORT);
  15335. std::string cert;
  15336. read_file(SERVER_CERT2_FILE, cert);
  15337. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15338. cli.enable_server_certificate_verification(true);
  15339. cli.set_connection_timeout(30);
  15340. auto res = cli.Get("/test");
  15341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15342. ASSERT_EQ(StatusCode::OK_200, res->status);
  15343. }
  15344. // CA certs loaded through the universal Client must be transferred to the
  15345. // client created internally for following an HTTPS redirect. Regression test:
  15346. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15347. // the CA data for redirect transfer.
  15348. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15349. auto ssl_port = PORT + 1;
  15350. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15351. ASSERT_TRUE(ssl_svr1.is_valid());
  15352. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15353. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15354. "/index");
  15355. });
  15356. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15357. ASSERT_TRUE(ssl_svr2.is_valid());
  15358. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15359. res.set_content("test", "text/plain");
  15360. });
  15361. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15362. thread t2 =
  15363. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15364. auto se = detail::scope_exit([&] {
  15365. ssl_svr2.stop();
  15366. ssl_svr1.stop();
  15367. t2.join();
  15368. t.join();
  15369. ASSERT_FALSE(ssl_svr1.is_running());
  15370. });
  15371. ssl_svr1.wait_until_ready();
  15372. ssl_svr2.wait_until_ready();
  15373. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15374. std::string cert;
  15375. read_file(SERVER_CERT2_FILE, cert);
  15376. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15377. cli.enable_server_certificate_verification(true);
  15378. cli.set_follow_location(true);
  15379. cli.set_connection_timeout(30);
  15380. auto res = cli.Get("/index");
  15381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15382. ASSERT_EQ(StatusCode::OK_200, res->status);
  15383. }
  15384. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15385. // so a host signed by a system CA verifies even though a custom CA is set
  15386. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15387. std::string cert;
  15388. read_file(SERVER_CERT2_FILE, cert);
  15389. SSLClient cli("google.com");
  15390. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15391. cli.enable_system_ca(true);
  15392. cli.enable_server_certificate_verification(true);
  15393. auto res = cli.Get("/");
  15394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15395. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15396. }
  15397. // The custom CA remains effective when combined with the system CA
  15398. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15399. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15400. ASSERT_TRUE(svr.is_valid());
  15401. svr.Get("/test", [&](const Request &, Response &res) {
  15402. res.set_content("test", "text/plain");
  15403. });
  15404. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15405. auto se = detail::scope_exit([&] {
  15406. svr.stop();
  15407. t.join();
  15408. ASSERT_FALSE(svr.is_running());
  15409. });
  15410. svr.wait_until_ready();
  15411. SSLClient cli("127.0.0.1", PORT);
  15412. std::string cert;
  15413. read_file(SERVER_CERT2_FILE, cert);
  15414. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15415. cli.enable_system_ca(true);
  15416. cli.enable_server_certificate_verification(true);
  15417. cli.set_connection_timeout(30);
  15418. auto res = cli.Get("/test");
  15419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15420. ASSERT_EQ(StatusCode::OK_200, res->status);
  15421. }
  15422. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  15423. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  15424. // the keys SecTrustSettingsCopyTrustSettings() returns.
  15425. static CFDictionaryRef
  15426. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  15427. const SecTrustSettingsResult *result) {
  15428. auto constraint =
  15429. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  15430. &kCFTypeDictionaryValueCallBacks);
  15431. if (policy) {
  15432. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  15433. }
  15434. if (policy_string) {
  15435. auto str = CFStringCreateWithCString(nullptr, policy_string,
  15436. kCFStringEncodingUTF8);
  15437. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  15438. CFRelease(str);
  15439. }
  15440. if (result) {
  15441. auto number_value = static_cast<SInt32>(*result);
  15442. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  15443. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  15444. CFRelease(number);
  15445. }
  15446. return constraint;
  15447. }
  15448. static SecTrustSettingsResult
  15449. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  15450. auto trust_settings =
  15451. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  15452. for (auto constraint : constraints) {
  15453. CFArrayAppendValue(trust_settings, constraint);
  15454. CFRelease(constraint);
  15455. }
  15456. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  15457. CFRelease(trust_settings);
  15458. return result;
  15459. }
  15460. // The system CA loader takes a Keychain certificate as a trusted root only
  15461. // when its Trust Settings say so for SSL, not merely because it has some.
  15462. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  15463. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  15464. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  15465. const auto deny = kSecTrustSettingsResultDeny;
  15466. const auto unspecified = kSecTrustSettingsResultUnspecified;
  15467. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  15468. auto x509_policy = SecPolicyCreateBasicX509();
  15469. // "Always Trust", which stores no constraint at all
  15470. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  15471. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15472. ssl_trust_settings_result(
  15473. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  15474. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  15475. ssl_trust_settings_result(
  15476. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  15477. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  15478. ssl_trust_settings_result(
  15479. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  15480. // "Never Trust", for everything or for SSL
  15481. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15482. ssl_trust_settings_result(
  15483. {make_usage_constraint(nullptr, nullptr, &deny)}));
  15484. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15485. ssl_trust_settings_result(
  15486. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  15487. // Trusted for another policy, for one host, or not at all
  15488. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15489. ssl_trust_settings_result(
  15490. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  15491. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15492. ssl_trust_settings_result({make_usage_constraint(
  15493. ssl_policy, "www.example.com", &trust_root)}));
  15494. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  15495. ssl_trust_settings_result(
  15496. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  15497. // The first constraint that applies to SSL decides
  15498. EXPECT_EQ(kSecTrustSettingsResultDeny,
  15499. ssl_trust_settings_result(
  15500. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  15501. make_usage_constraint(nullptr, nullptr, &deny)}));
  15502. CFRelease(x509_policy);
  15503. CFRelease(ssl_policy);
  15504. }
  15505. #endif
  15506. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15507. // skip chain verification entirely (only the certificate identity was
  15508. // checked), so a server presenting an untrusted certificate with a matching
  15509. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15510. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15511. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15512. ASSERT_TRUE(svr.is_valid());
  15513. svr.Get("/test", [&](const Request &, Response &res) {
  15514. res.set_content("test", "text/plain");
  15515. });
  15516. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15517. auto se = detail::scope_exit([&] {
  15518. svr.stop();
  15519. t.join();
  15520. ASSERT_FALSE(svr.is_running());
  15521. });
  15522. svr.wait_until_ready();
  15523. SSLClient cli("127.0.0.1", PORT);
  15524. std::string cert;
  15525. // A trusted CA that did not sign the server certificate. The server cert
  15526. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15527. // this connection.
  15528. read_file(CLIENT_CA_CERT_FILE, cert);
  15529. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15530. cli.enable_server_certificate_verification(true);
  15531. cli.set_connection_timeout(30);
  15532. auto res = cli.Get("/test");
  15533. ASSERT_FALSE(res);
  15534. }
  15535. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15536. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15537. // CA that failed to come through fails verification instead of trusting them.
  15538. // (wolfSSL does not list the system CAs it loaded.)
  15539. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15540. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15541. ASSERT_TRUE(svr.is_valid());
  15542. auto port = svr.bind_to_any_port("127.0.0.1");
  15543. ASSERT_LT(0, port);
  15544. thread t = thread([&] { svr.listen_after_bind(); });
  15545. auto se = detail::scope_exit([&] {
  15546. svr.stop();
  15547. t.join();
  15548. ASSERT_FALSE(svr.is_running());
  15549. });
  15550. svr.wait_until_ready();
  15551. // The CAs a client trusts once its first request has loaded them
  15552. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15553. Client cli("https://127.0.0.1:" + std::to_string(port));
  15554. setup(cli);
  15555. cli.Get("/");
  15556. return tls::get_ca_names(cli.tls_context()).size();
  15557. };
  15558. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15559. EXPECT_EQ(0u,
  15560. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15561. }
  15562. #endif
  15563. // A TLS setting changed between requests applies to the next one, not just to
  15564. // the next connection
  15565. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15566. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15567. ASSERT_TRUE(svr.is_valid());
  15568. svr.Get("/", [](const Request &req, Response &res) {
  15569. res.set_content(std::to_string(req.remote_port), "text/plain");
  15570. });
  15571. auto port = svr.bind_to_any_port("127.0.0.1");
  15572. ASSERT_LT(0, port);
  15573. thread t = thread([&] { svr.listen_after_bind(); });
  15574. auto se = detail::scope_exit([&] {
  15575. svr.stop();
  15576. t.join();
  15577. ASSERT_FALSE(svr.is_running());
  15578. });
  15579. svr.wait_until_ready();
  15580. SSLClient cli("127.0.0.1", port);
  15581. cli.set_keep_alive(true);
  15582. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15583. cli.enable_server_certificate_verification(false);
  15584. // The port the request went out from, so a new one means a new connection
  15585. auto client_port = [&] {
  15586. auto res = cli.Get("/");
  15587. return res ? res->body : std::string();
  15588. };
  15589. auto last = client_port();
  15590. ASSERT_FALSE(last.empty());
  15591. // Setting a value it already has keeps the connection
  15592. cli.enable_server_certificate_verification(false);
  15593. cli.enable_server_hostname_verification(true);
  15594. EXPECT_EQ(last, client_port());
  15595. cli.enable_server_certificate_verification(true);
  15596. auto res = cli.Get("/");
  15597. EXPECT_FALSE(res);
  15598. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15599. std::string ca;
  15600. read_file(SERVER_CERT2_FILE, ca);
  15601. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15602. last = client_port();
  15603. ASSERT_FALSE(last.empty());
  15604. std::vector<std::function<void()>> setters = {
  15605. [&] { cli.enable_server_hostname_verification(false); },
  15606. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15607. [&] {
  15608. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15609. },
  15610. [&] {
  15611. cli.set_server_certificate_verifier(
  15612. [](const tls::VerifyContext &) { return true; });
  15613. },
  15614. [&] {
  15615. cli.set_session_verifier(
  15616. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15617. },
  15618. };
  15619. for (const auto &setter : setters) {
  15620. setter();
  15621. auto next = client_port();
  15622. ASSERT_FALSE(next.empty());
  15623. EXPECT_NE(last, next);
  15624. last = next;
  15625. }
  15626. cli.set_session_verifier(
  15627. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15628. auto handle = cli.open_stream("GET", "/");
  15629. EXPECT_FALSE(handle.is_valid());
  15630. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15631. }
  15632. // A PEM given to create_ca_store() needs no NUL after it
  15633. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15634. std::string pem;
  15635. read_file(SERVER_CERT2_FILE, pem);
  15636. auto buf = pem + "X";
  15637. auto store = tls::create_ca_store(buf.data(), pem.size());
  15638. EXPECT_TRUE(store != nullptr);
  15639. SSLClient cli("localhost");
  15640. cli.set_ca_cert_store(store);
  15641. }
  15642. // enable_system_ca(false) prevents system CA loading entirely
  15643. TEST(SSLClientTest, DisableSystemCa_Online) {
  15644. SSLClient cli("google.com");
  15645. cli.enable_system_ca(false);
  15646. cli.enable_server_certificate_verification(true);
  15647. auto res = cli.Get("/");
  15648. ASSERT_FALSE(res);
  15649. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15650. // itself when the CA chain is empty
  15651. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15652. res.error() == Error::SSLConnection);
  15653. }
  15654. // The universal Client forwards enable_system_ca()
  15655. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15656. std::string cert;
  15657. read_file(SERVER_CERT2_FILE, cert);
  15658. Client cli("https://google.com");
  15659. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15660. cli.enable_system_ca(true);
  15661. cli.enable_server_certificate_verification(true);
  15662. auto res = cli.Get("/");
  15663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15664. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15665. }
  15666. // The system CA policy must carry over to the client created internally for
  15667. // following a cross-host HTTPS redirect
  15668. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15669. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15670. ASSERT_TRUE(svr.is_valid());
  15671. svr.Get("/index", [&](const Request &, Response &res) {
  15672. res.set_redirect("https://www.google.com/");
  15673. });
  15674. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15675. auto se = detail::scope_exit([&] {
  15676. svr.stop();
  15677. t.join();
  15678. ASSERT_FALSE(svr.is_running());
  15679. });
  15680. svr.wait_until_ready();
  15681. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15682. std::string cert;
  15683. read_file(SERVER_CERT2_FILE, cert);
  15684. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15685. cli.enable_system_ca(true);
  15686. cli.enable_server_certificate_verification(true);
  15687. cli.set_follow_location(true);
  15688. cli.set_connection_timeout(30);
  15689. // Receiving any response proves the redirect client completed the TLS
  15690. // handshake with a system-CA-signed host
  15691. auto res = cli.Get("/index");
  15692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15693. }
  15694. TEST(MultipartFormDataTest, LargeData) {
  15695. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15696. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15697. const ContentReader &content_reader) {
  15698. if (req.is_multipart_form_data()) {
  15699. std::vector<FormData> items;
  15700. content_reader(
  15701. [&](const FormData &file) {
  15702. items.push_back(file);
  15703. return true;
  15704. },
  15705. [&](const char *data, size_t data_length) {
  15706. items.back().content.append(data, data_length);
  15707. return true;
  15708. });
  15709. EXPECT_TRUE(std::string(items[0].name) == "document");
  15710. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15711. EXPECT_TRUE(items[0].filename == "2MB_data");
  15712. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15713. EXPECT_TRUE(items[1].name == "hello");
  15714. EXPECT_TRUE(items[1].content == "world");
  15715. EXPECT_TRUE(items[1].filename == "");
  15716. EXPECT_TRUE(items[1].content_type == "");
  15717. } else {
  15718. std::string body;
  15719. content_reader([&](const char *data, size_t data_length) {
  15720. body.append(data, data_length);
  15721. return true;
  15722. });
  15723. }
  15724. });
  15725. auto port = svr.bind_to_any_port(HOST);
  15726. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15727. auto se = detail::scope_exit([&] {
  15728. svr.stop();
  15729. t.join();
  15730. ASSERT_FALSE(svr.is_running());
  15731. });
  15732. svr.wait_until_ready();
  15733. {
  15734. std::string data(1024 * 1024 * 2, '.');
  15735. std::stringstream buffer;
  15736. buffer << data;
  15737. SSLClient cli(HOST, port);
  15738. cli.enable_server_certificate_verification(false);
  15739. UploadFormDataItems items{
  15740. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15741. {"hello", "world", "", ""},
  15742. };
  15743. auto res = cli.Post("/post", items);
  15744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15745. ASSERT_EQ(StatusCode::OK_200, res->status);
  15746. }
  15747. }
  15748. TEST(MultipartFormDataTest, DataProviderItems) {
  15749. std::random_device seed_gen;
  15750. std::mt19937 random(seed_gen());
  15751. std::string rand1;
  15752. rand1.resize(1000);
  15753. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15754. std::string rand2;
  15755. rand2.resize(3000);
  15756. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15757. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15758. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15759. const ContentReader &content_reader) {
  15760. ASSERT_FALSE(req.is_multipart_form_data());
  15761. std::string body;
  15762. content_reader([&](const char *data, size_t data_length) {
  15763. body.append(data, data_length);
  15764. return true;
  15765. });
  15766. EXPECT_EQ(body, "");
  15767. });
  15768. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15769. const ContentReader &content_reader) {
  15770. ASSERT_TRUE(req.is_multipart_form_data());
  15771. std::vector<FormData> items;
  15772. content_reader(
  15773. [&](const FormData &file) {
  15774. items.push_back(file);
  15775. return true;
  15776. },
  15777. [&](const char *data, size_t data_length) {
  15778. items.back().content.append(data, data_length);
  15779. return true;
  15780. });
  15781. ASSERT_TRUE(items.size() == 2);
  15782. EXPECT_EQ(std::string(items[0].name), "name1");
  15783. EXPECT_EQ(items[0].content, "Testing123");
  15784. EXPECT_EQ(items[0].filename, "filename1");
  15785. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15786. EXPECT_EQ(items[1].name, "name2");
  15787. EXPECT_EQ(items[1].content, "Testing456");
  15788. EXPECT_EQ(items[1].filename, "");
  15789. EXPECT_EQ(items[1].content_type, "");
  15790. });
  15791. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15792. const ContentReader &content_reader) {
  15793. ASSERT_TRUE(req.is_multipart_form_data());
  15794. std::vector<FormData> items;
  15795. content_reader(
  15796. [&](const FormData &file) {
  15797. items.push_back(file);
  15798. return true;
  15799. },
  15800. [&](const char *data, size_t data_length) {
  15801. items.back().content.append(data, data_length);
  15802. return true;
  15803. });
  15804. ASSERT_TRUE(items.size() == 2);
  15805. EXPECT_EQ(items[0].name, "name3");
  15806. EXPECT_EQ(items[0].content, rand1);
  15807. EXPECT_EQ(items[0].filename, "filename3");
  15808. EXPECT_EQ(items[0].content_type, "");
  15809. EXPECT_EQ(items[1].name, "name4");
  15810. EXPECT_EQ(items[1].content, rand2);
  15811. EXPECT_EQ(items[1].filename, "filename4");
  15812. EXPECT_EQ(items[1].content_type, "");
  15813. });
  15814. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15815. const ContentReader &content_reader) {
  15816. ASSERT_TRUE(req.is_multipart_form_data());
  15817. std::vector<FormData> items;
  15818. content_reader(
  15819. [&](const FormData &file) {
  15820. items.push_back(file);
  15821. return true;
  15822. },
  15823. [&](const char *data, size_t data_length) {
  15824. items.back().content.append(data, data_length);
  15825. return true;
  15826. });
  15827. ASSERT_TRUE(items.size() == 4);
  15828. EXPECT_EQ(std::string(items[0].name), "name1");
  15829. EXPECT_EQ(items[0].content, "Testing123");
  15830. EXPECT_EQ(items[0].filename, "filename1");
  15831. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15832. EXPECT_EQ(items[1].name, "name2");
  15833. EXPECT_EQ(items[1].content, "Testing456");
  15834. EXPECT_EQ(items[1].filename, "");
  15835. EXPECT_EQ(items[1].content_type, "");
  15836. EXPECT_EQ(items[2].name, "name3");
  15837. EXPECT_EQ(items[2].content, rand1);
  15838. EXPECT_EQ(items[2].filename, "filename3");
  15839. EXPECT_EQ(items[2].content_type, "");
  15840. EXPECT_EQ(items[3].name, "name4");
  15841. EXPECT_EQ(items[3].content, rand2);
  15842. EXPECT_EQ(items[3].filename, "filename4");
  15843. EXPECT_EQ(items[3].content_type, "");
  15844. });
  15845. auto port = svr.bind_to_any_port("localhost");
  15846. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15847. auto se = detail::scope_exit([&] {
  15848. svr.stop();
  15849. t.join();
  15850. ASSERT_FALSE(svr.is_running());
  15851. });
  15852. svr.wait_until_ready();
  15853. {
  15854. SSLClient cli("localhost", port);
  15855. cli.enable_server_certificate_verification(false);
  15856. UploadFormDataItems items{
  15857. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15858. {"name2", "Testing456", "", ""}, // not a file
  15859. };
  15860. {
  15861. auto res = cli.Post("/post-none", {}, {}, {});
  15862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15863. ASSERT_EQ(StatusCode::OK_200, res->status);
  15864. }
  15865. FormDataProviderItems providers;
  15866. {
  15867. auto res =
  15868. cli.Post("/post-items", {}, items, providers); // empty providers
  15869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15870. ASSERT_EQ(StatusCode::OK_200, res->status);
  15871. }
  15872. providers.push_back({"name3",
  15873. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15874. // test the offset is given correctly at each step
  15875. if (!offset)
  15876. sink.os.write(rand1.data(), 30);
  15877. else if (offset == 30)
  15878. sink.os.write(rand1.data() + 30, 300);
  15879. else if (offset == 330)
  15880. sink.os.write(rand1.data() + 330, 670);
  15881. else if (offset == rand1.size())
  15882. sink.done();
  15883. return true;
  15884. },
  15885. "filename3",
  15886. {}});
  15887. providers.push_back({"name4",
  15888. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15889. // test the offset is given correctly at each step
  15890. if (!offset)
  15891. sink.os.write(rand2.data(), 2000);
  15892. else if (offset == 2000)
  15893. sink.os.write(rand2.data() + 2000, 1);
  15894. else if (offset == 2001)
  15895. sink.os.write(rand2.data() + 2001, 999);
  15896. else if (offset == rand2.size())
  15897. sink.done();
  15898. return true;
  15899. },
  15900. "filename4",
  15901. {}});
  15902. {
  15903. auto res = cli.Post("/post-providers", {}, {}, providers);
  15904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15905. ASSERT_EQ(StatusCode::OK_200, res->status);
  15906. }
  15907. {
  15908. auto res = cli.Post("/post-both", {}, items, providers);
  15909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15910. ASSERT_EQ(StatusCode::OK_200, res->status);
  15911. }
  15912. }
  15913. }
  15914. TEST(MultipartFormDataTest, BadHeader) {
  15915. Server svr;
  15916. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15917. res.set_content("ok", "text/plain");
  15918. });
  15919. thread t = thread([&] { svr.listen(HOST, PORT); });
  15920. auto se = detail::scope_exit([&] {
  15921. svr.stop();
  15922. t.join();
  15923. ASSERT_FALSE(svr.is_running());
  15924. });
  15925. svr.wait_until_ready();
  15926. const std::string body =
  15927. "This is the preamble. It is to be ignored, though it\r\n"
  15928. "is a handy place for composition agents to include an\r\n"
  15929. "explanatory note to non-MIME conformant readers.\r\n"
  15930. "\r\n"
  15931. "\r\n"
  15932. "--simple boundary\r\n"
  15933. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15934. ": BAD...\r\n"
  15935. "\r\n"
  15936. "value1\r\n"
  15937. "--simple boundary\r\n"
  15938. "Content-Disposition: form-data; name=\"field2\"; "
  15939. "filename=\"example.txt\"\r\n"
  15940. "\r\n"
  15941. "value2\r\n"
  15942. "--simple boundary--\r\n"
  15943. "This is the epilogue. It is also to be ignored.\r\n";
  15944. std::string content_type =
  15945. R"(multipart/form-data; boundary="simple boundary")";
  15946. Client cli(HOST, PORT);
  15947. auto res = cli.Post("/post", body, content_type.c_str());
  15948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15949. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15950. }
  15951. TEST(MultipartFormDataTest, WithPreamble) {
  15952. Server svr;
  15953. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15954. res.set_content("ok", "text/plain");
  15955. });
  15956. thread t = thread([&] { svr.listen(HOST, PORT); });
  15957. auto se = detail::scope_exit([&] {
  15958. svr.stop();
  15959. t.join();
  15960. ASSERT_FALSE(svr.is_running());
  15961. });
  15962. svr.wait_until_ready();
  15963. const std::string body =
  15964. "This is the preamble. It is to be ignored, though it\r\n"
  15965. "is a handy place for composition agents to include an\r\n"
  15966. "explanatory note to non-MIME conformant readers.\r\n"
  15967. "\r\n"
  15968. "\r\n"
  15969. "--simple boundary\r\n"
  15970. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15971. "\r\n"
  15972. "value1\r\n"
  15973. "--simple boundary\r\n"
  15974. "Content-Disposition: form-data; name=\"field2\"; "
  15975. "filename=\"example.txt\"\r\n"
  15976. "\r\n"
  15977. "value2\r\n"
  15978. "--simple boundary--\r\n"
  15979. "This is the epilogue. It is also to be ignored.\r\n";
  15980. std::string content_type =
  15981. R"(multipart/form-data; boundary="simple boundary")";
  15982. Client cli(HOST, PORT);
  15983. auto res = cli.Post("/post", body, content_type.c_str());
  15984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15985. EXPECT_EQ(StatusCode::OK_200, res->status);
  15986. }
  15987. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15988. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15989. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15990. const ContentReader &content_reader) {
  15991. if (req.is_multipart_form_data()) {
  15992. std::vector<FormData> items;
  15993. content_reader(
  15994. [&](const FormData &file) {
  15995. items.push_back(file);
  15996. return true;
  15997. },
  15998. [&](const char *data, size_t data_length) {
  15999. items.back().content.append(data, data_length);
  16000. return true;
  16001. });
  16002. EXPECT_TRUE(std::string(items[0].name) == "document");
  16003. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16004. EXPECT_TRUE(items[0].filename == "2MB_data");
  16005. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16006. EXPECT_TRUE(items[1].name == "hello");
  16007. EXPECT_TRUE(items[1].content == "world");
  16008. EXPECT_TRUE(items[1].filename == "");
  16009. EXPECT_TRUE(items[1].content_type == "");
  16010. } else {
  16011. std::string body;
  16012. content_reader([&](const char *data, size_t data_length) {
  16013. body.append(data, data_length);
  16014. return true;
  16015. });
  16016. }
  16017. });
  16018. auto port = svr.bind_to_any_port("localhost");
  16019. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16020. auto se = detail::scope_exit([&] {
  16021. svr.stop();
  16022. t.join();
  16023. ASSERT_FALSE(svr.is_running());
  16024. });
  16025. svr.wait_until_ready();
  16026. {
  16027. std::string data(1024 * 1024 * 2, '.');
  16028. std::stringstream buffer;
  16029. buffer << data;
  16030. SSLClient cli("localhost", port);
  16031. cli.enable_server_certificate_verification(false);
  16032. UploadFormDataItems items{
  16033. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16034. {"hello", "world", "", ""},
  16035. };
  16036. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16038. ASSERT_EQ(StatusCode::OK_200, res->status);
  16039. }
  16040. }
  16041. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16042. std::string data(1024 * 1024 * 2, '&');
  16043. std::stringstream buffer;
  16044. buffer << data;
  16045. Client cli("https://localhost:8080");
  16046. UploadFormDataItems items{
  16047. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16048. {"hello", "world", "", ""},
  16049. };
  16050. for (const char &c : " \t\r\n") {
  16051. auto res =
  16052. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16053. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16054. ASSERT_FALSE(res);
  16055. }
  16056. }
  16057. TEST(MultipartFormDataTest, PutFormData) {
  16058. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16059. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16060. const ContentReader &content_reader) {
  16061. if (req.is_multipart_form_data()) {
  16062. std::vector<FormData> items;
  16063. content_reader(
  16064. [&](const FormData &file) {
  16065. items.push_back(file);
  16066. return true;
  16067. },
  16068. [&](const char *data, size_t data_length) {
  16069. items.back().content.append(data, data_length);
  16070. return true;
  16071. });
  16072. EXPECT_TRUE(std::string(items[0].name) == "document");
  16073. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16074. EXPECT_TRUE(items[0].filename == "2MB_data");
  16075. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16076. EXPECT_TRUE(items[1].name == "hello");
  16077. EXPECT_TRUE(items[1].content == "world");
  16078. EXPECT_TRUE(items[1].filename == "");
  16079. EXPECT_TRUE(items[1].content_type == "");
  16080. } else {
  16081. std::string body;
  16082. content_reader([&](const char *data, size_t data_length) {
  16083. body.append(data, data_length);
  16084. return true;
  16085. });
  16086. }
  16087. });
  16088. auto port = svr.bind_to_any_port("localhost");
  16089. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16090. auto se = detail::scope_exit([&] {
  16091. svr.stop();
  16092. t.join();
  16093. ASSERT_FALSE(svr.is_running());
  16094. });
  16095. svr.wait_until_ready();
  16096. {
  16097. std::string data(1024 * 1024 * 2, '&');
  16098. std::stringstream buffer;
  16099. buffer << data;
  16100. SSLClient cli("localhost", port);
  16101. cli.enable_server_certificate_verification(false);
  16102. UploadFormDataItems items{
  16103. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16104. {"hello", "world", "", ""},
  16105. };
  16106. auto res = cli.Put("/put", items);
  16107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16108. ASSERT_EQ(StatusCode::OK_200, res->status);
  16109. }
  16110. }
  16111. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16113. svr.Put("/put_customboundary",
  16114. [&](const Request &req, const Response & /*res*/,
  16115. const ContentReader &content_reader) {
  16116. if (req.is_multipart_form_data()) {
  16117. std::vector<FormData> items;
  16118. content_reader(
  16119. [&](const FormData &file) {
  16120. items.push_back(file);
  16121. return true;
  16122. },
  16123. [&](const char *data, size_t data_length) {
  16124. items.back().content.append(data, data_length);
  16125. return true;
  16126. });
  16127. EXPECT_TRUE(std::string(items[0].name) == "document");
  16128. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16129. EXPECT_TRUE(items[0].filename == "2MB_data");
  16130. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16131. EXPECT_TRUE(items[1].name == "hello");
  16132. EXPECT_TRUE(items[1].content == "world");
  16133. EXPECT_TRUE(items[1].filename == "");
  16134. EXPECT_TRUE(items[1].content_type == "");
  16135. } else {
  16136. std::string body;
  16137. content_reader([&](const char *data, size_t data_length) {
  16138. body.append(data, data_length);
  16139. return true;
  16140. });
  16141. }
  16142. });
  16143. auto port = svr.bind_to_any_port("localhost");
  16144. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16145. auto se = detail::scope_exit([&] {
  16146. svr.stop();
  16147. t.join();
  16148. ASSERT_FALSE(svr.is_running());
  16149. });
  16150. svr.wait_until_ready();
  16151. {
  16152. std::string data(1024 * 1024 * 2, '&');
  16153. std::stringstream buffer;
  16154. buffer << data;
  16155. SSLClient cli("localhost", port);
  16156. cli.enable_server_certificate_verification(false);
  16157. UploadFormDataItems items{
  16158. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16159. {"hello", "world", "", ""},
  16160. };
  16161. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  16162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16163. ASSERT_EQ(StatusCode::OK_200, res->status);
  16164. }
  16165. }
  16166. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  16167. std::string data(1024 * 1024 * 2, '&');
  16168. std::stringstream buffer;
  16169. buffer << data;
  16170. Client cli("https://localhost:8080");
  16171. cli.enable_server_certificate_verification(false);
  16172. UploadFormDataItems items{
  16173. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16174. {"hello", "world", "", ""},
  16175. };
  16176. for (const char &c : " \t\r\n") {
  16177. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  16178. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16179. ASSERT_FALSE(res);
  16180. }
  16181. }
  16182. TEST(MultipartFormDataTest, AlternateFilename) {
  16183. auto handled = false;
  16184. Server svr;
  16185. svr.Post("/test", [&](const Request &req, Response &res) {
  16186. ASSERT_EQ(2u, req.form.files.size());
  16187. ASSERT_EQ(1u, req.form.fields.size());
  16188. // Test files
  16189. const auto &file1 = req.form.get_file("file1");
  16190. ASSERT_EQ("file1", file1.name);
  16191. ASSERT_EQ("A.txt", file1.filename);
  16192. ASSERT_EQ("text/plain", file1.content_type);
  16193. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  16194. const auto &file2 = req.form.get_file("file2");
  16195. ASSERT_EQ("file2", file2.name);
  16196. ASSERT_EQ("a.html", file2.filename);
  16197. ASSERT_EQ("text/html", file2.content_type);
  16198. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  16199. file2.content);
  16200. // Test text field
  16201. const auto &text = req.form.get_field("text");
  16202. ASSERT_EQ("text default", text);
  16203. res.set_content("ok", "text/plain");
  16204. handled = true;
  16205. });
  16206. thread t = thread([&] { svr.listen(HOST, PORT); });
  16207. auto se = detail::scope_exit([&] {
  16208. svr.stop();
  16209. t.join();
  16210. ASSERT_FALSE(svr.is_running());
  16211. ASSERT_TRUE(handled);
  16212. });
  16213. svr.wait_until_ready();
  16214. auto req = "POST /test HTTP/1.1\r\n"
  16215. "Host: localhost\r\n"
  16216. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16217. "Content-Length: 399\r\n"
  16218. "\r\n"
  16219. "----------\r\n"
  16220. "Content-Disposition: form-data; name=\"text\"\r\n"
  16221. "\r\n"
  16222. "text default\r\n"
  16223. "----------\r\n"
  16224. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16225. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16226. "Content-Type: text/plain\r\n"
  16227. "\r\n"
  16228. "Content of a.txt.\r\n"
  16229. "\r\n"
  16230. "----------\r\n"
  16231. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16232. "\"a.html\"\r\n"
  16233. "Content-Type: text/html\r\n"
  16234. "\r\n"
  16235. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16236. "\r\n"
  16237. "------------\r\n";
  16238. ASSERT_TRUE(send_request(1, req));
  16239. }
  16240. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16241. auto handled = false;
  16242. Server svr;
  16243. svr.Post("/test", [&](const Request &req, Response &res) {
  16244. // Case-insensitive "utf-8''" prefix with a long value
  16245. const auto &file = req.form.get_file("file1");
  16246. ASSERT_EQ("file1", file.name);
  16247. // 8000 chars exercises both the Content-Disposition parser and the
  16248. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16249. // Prior to the fix, std::regex_match on this header would cause O(N)
  16250. // stack recursion in libstdc++, leading to SIGSEGV.
  16251. std::string expected_filename(8000, 'A');
  16252. ASSERT_EQ(expected_filename, file.filename);
  16253. res.set_content("ok", "text/plain");
  16254. handled = true;
  16255. });
  16256. thread t = thread([&] { svr.listen(HOST, PORT); });
  16257. auto se = detail::scope_exit([&] {
  16258. svr.stop();
  16259. t.join();
  16260. ASSERT_FALSE(svr.is_running());
  16261. ASSERT_TRUE(handled);
  16262. });
  16263. svr.wait_until_ready();
  16264. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16265. // Regression test for GHSA-qq6v-r583-3h69
  16266. std::string long_filename(8000, 'A');
  16267. std::string body = "----------\r\n"
  16268. "Content-Disposition: form-data; name=\"file1\"; "
  16269. "filename*=\"Utf-8''" +
  16270. long_filename +
  16271. "\"\r\n"
  16272. "\r\n"
  16273. "hello\r\n"
  16274. "------------\r\n";
  16275. auto req = "POST /test HTTP/1.1\r\n"
  16276. "Host: localhost\r\n"
  16277. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16278. "Content-Length: " +
  16279. std::to_string(body.size()) + "\r\n\r\n" + body;
  16280. ASSERT_TRUE(send_request(1, req));
  16281. }
  16282. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16283. auto handled = false;
  16284. Server svr;
  16285. svr.Post("/test", [&](const Request &req, Response &) {
  16286. ASSERT_EQ(2u, req.form.fields.size());
  16287. const auto &text1 = req.form.get_field("text1");
  16288. ASSERT_EQ("text1", text1);
  16289. const auto &text2 = req.form.get_field("text2");
  16290. ASSERT_EQ("text2", text2);
  16291. handled = true;
  16292. });
  16293. thread t = thread([&] { svr.listen(HOST, PORT); });
  16294. auto se = detail::scope_exit([&] {
  16295. svr.stop();
  16296. t.join();
  16297. ASSERT_FALSE(svr.is_running());
  16298. ASSERT_TRUE(handled);
  16299. });
  16300. svr.wait_until_ready();
  16301. auto req = "POST /test HTTP/1.1\r\n"
  16302. "Host: localhost\r\n"
  16303. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16304. "Content-Length: 146\r\n"
  16305. "\r\n----------\r\n"
  16306. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16307. "\r\n"
  16308. "text1"
  16309. "\r\n----------\r\n"
  16310. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16311. "\r\n"
  16312. "text2"
  16313. "\r\n------------";
  16314. std::string response;
  16315. ASSERT_TRUE(send_request(1, req, &response));
  16316. ASSERT_EQ("200", response.substr(9, 3));
  16317. }
  16318. TEST(MultipartFormDataTest, ContentLength) {
  16319. auto handled = false;
  16320. Server svr;
  16321. svr.Post("/test", [&](const Request &req, Response &) {
  16322. ASSERT_EQ(2u, req.form.fields.size());
  16323. const auto &text1 = req.form.get_field("text1");
  16324. ASSERT_EQ("text1", text1);
  16325. const auto &text2 = req.form.get_field("text2");
  16326. ASSERT_EQ("text2", text2);
  16327. handled = true;
  16328. });
  16329. thread t = thread([&] { svr.listen(HOST, PORT); });
  16330. auto se = detail::scope_exit([&] {
  16331. svr.stop();
  16332. t.join();
  16333. ASSERT_FALSE(svr.is_running());
  16334. ASSERT_TRUE(handled);
  16335. });
  16336. svr.wait_until_ready();
  16337. auto req = "POST /test HTTP/1.1\r\n"
  16338. "Host: localhost\r\n"
  16339. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16340. "Content-Length: 167\r\n"
  16341. "\r\n----------\r\n"
  16342. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16343. "Content-Length: 5\r\n"
  16344. "\r\n"
  16345. "text1"
  16346. "\r\n----------\r\n"
  16347. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16348. "\r\n"
  16349. "text2"
  16350. "\r\n------------\r\n";
  16351. std::string response;
  16352. ASSERT_TRUE(send_request(1, req, &response));
  16353. ASSERT_EQ("200", response.substr(9, 3));
  16354. }
  16355. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16356. auto handled = false;
  16357. Server svr;
  16358. svr.Post("/test", [&](const Request &req, Response &) {
  16359. ASSERT_EQ(2u, req.form.fields.size());
  16360. const auto &text1 = req.form.get_field("text1");
  16361. ASSERT_EQ("text1", text1);
  16362. // TODO: Add header access for text fields if needed
  16363. const auto &text2 = req.form.get_field("text2");
  16364. ASSERT_EQ("text2", text2);
  16365. // TODO: Header access for text fields needs to be implemented
  16366. // auto &headers = it->second.headers;
  16367. // ASSERT_EQ(3U, headers.size());
  16368. // auto custom_header = headers.find("x-whatever");
  16369. // ASSERT_TRUE(custom_header != headers.end());
  16370. // ASSERT_NE("customvalue", custom_header->second);
  16371. // ASSERT_EQ("CustomValue", custom_header->second);
  16372. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16373. handled = true;
  16374. });
  16375. thread t = thread([&] { svr.listen(HOST, PORT); });
  16376. auto se = detail::scope_exit([&] {
  16377. svr.stop();
  16378. t.join();
  16379. ASSERT_FALSE(svr.is_running());
  16380. ASSERT_TRUE(handled);
  16381. });
  16382. svr.wait_until_ready();
  16383. auto req = "POST /test HTTP/1.1\r\n"
  16384. "Host: localhost\r\n"
  16385. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16386. "Content-Length: 232\r\n"
  16387. "\r\n----------\r\n"
  16388. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16389. "Content-Length: 5\r\n"
  16390. "X-Test: 1\r\n"
  16391. "\r\n"
  16392. "text1"
  16393. "\r\n----------\r\n"
  16394. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16395. "Content-Type: text/plain\r\n"
  16396. "X-Whatever: CustomValue\r\n"
  16397. "\r\n"
  16398. "text2"
  16399. "\r\n------------\r\n"
  16400. "That should be disregarded. Not even read";
  16401. std::string response;
  16402. ASSERT_TRUE(send_request(1, req, &response));
  16403. ASSERT_EQ("200", response.substr(9, 3));
  16404. }
  16405. TEST(MultipartFormDataTest, LargeHeader) {
  16406. auto handled = false;
  16407. Server svr;
  16408. svr.Post("/test", [&](const Request &req, Response &) {
  16409. ASSERT_EQ(1u, req.form.fields.size());
  16410. const auto &text = req.form.get_field("name1");
  16411. ASSERT_EQ("text1", text);
  16412. handled = true;
  16413. });
  16414. thread t = thread([&] { svr.listen(HOST, PORT); });
  16415. auto se = detail::scope_exit([&] {
  16416. svr.stop();
  16417. t.join();
  16418. ASSERT_FALSE(svr.is_running());
  16419. ASSERT_TRUE(handled);
  16420. });
  16421. svr.wait_until_ready();
  16422. auto boundary = std::string("cpp-httplib-multipart-data");
  16423. std::string content = "--" + boundary +
  16424. "\r\n"
  16425. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16426. "\r\n"
  16427. "text1\r\n"
  16428. "--" +
  16429. boundary + "--\r\n";
  16430. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16431. "Host: localhost\r\n"
  16432. "Content-Type: multipart/form-data;boundary=" +
  16433. boundary +
  16434. "\r\n"
  16435. "Content-Length: " +
  16436. std::to_string(content.size()) +
  16437. "\r\n"
  16438. "Dummy-Header: ";
  16439. std::string header_suffix = "\r\n"
  16440. "\r\n";
  16441. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16442. size_t header_dummy_size =
  16443. read_buff_size -
  16444. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16445. auto header_dummy = std::string(header_dummy_size, '@');
  16446. auto req = header_prefix + header_dummy + header_suffix + content;
  16447. std::string response;
  16448. ASSERT_TRUE(send_request(1, req, &response));
  16449. ASSERT_EQ("200", response.substr(9, 3));
  16450. }
  16451. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16452. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16453. // (not chunked Transfer-Encoding) after the streaming refactor.
  16454. auto handled = false;
  16455. Server svr;
  16456. svr.Post("/upload", [&](const Request &req, Response &res) {
  16457. auto cl_it = req.headers.find("Content-Length");
  16458. EXPECT_TRUE(cl_it != req.headers.end());
  16459. auto te_it = req.headers.find("Transfer-Encoding");
  16460. EXPECT_TRUE(te_it == req.headers.end());
  16461. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16462. res.set_content("ok", "text/plain");
  16463. handled = true;
  16464. });
  16465. auto port = svr.bind_to_any_port(HOST);
  16466. auto t = thread([&] { svr.listen_after_bind(); });
  16467. auto se = detail::scope_exit([&] {
  16468. svr.stop();
  16469. t.join();
  16470. ASSERT_FALSE(svr.is_running());
  16471. ASSERT_TRUE(handled);
  16472. });
  16473. svr.wait_until_ready();
  16474. UploadFormDataItems items = {
  16475. {"field1", "hello", "", "text/plain"},
  16476. {"file1", "world", "test.txt", "application/octet-stream"},
  16477. };
  16478. Client cli(HOST, port);
  16479. auto res = cli.Post("/upload", {}, items);
  16480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16481. EXPECT_EQ(StatusCode::OK_200, res->status);
  16482. }
  16483. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16484. // Verify that make_multipart_content_provider coalesces many small segments
  16485. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16486. constexpr size_t kItemCount = 1000;
  16487. UploadFormDataItems items;
  16488. items.reserve(kItemCount);
  16489. for (size_t i = 0; i < kItemCount; i++) {
  16490. items.push_back(
  16491. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16492. }
  16493. const std::string boundary = "----test-boundary";
  16494. auto content_length = detail::get_multipart_content_length(items, boundary);
  16495. auto provider = detail::make_multipart_content_provider(items, boundary);
  16496. // Drive the provider the same way write_content_with_progress does
  16497. size_t write_count = 0;
  16498. size_t total_bytes = 0;
  16499. DataSink sink;
  16500. size_t offset = 0;
  16501. sink.write = [&](const char *d, size_t l) -> bool {
  16502. (void)d;
  16503. write_count++;
  16504. total_bytes += l;
  16505. offset += l;
  16506. return true;
  16507. };
  16508. sink.is_writable = []() -> bool { return true; };
  16509. while (offset < content_length) {
  16510. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16511. }
  16512. EXPECT_EQ(content_length, total_bytes);
  16513. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16514. // With buffering into 64KB blocks, write_count should be much smaller.
  16515. auto segment_count = 3 * kItemCount + 1;
  16516. EXPECT_LT(write_count, segment_count / 10);
  16517. }
  16518. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16519. // Integration test: send many UploadFormDataItems and verify the server
  16520. // receives all of them correctly (#2410).
  16521. constexpr size_t kItemCount = 500;
  16522. auto handled = false;
  16523. Server svr;
  16524. svr.Post("/upload", [&](const Request &req, Response &res) {
  16525. EXPECT_EQ(kItemCount, req.form.fields.size());
  16526. for (size_t i = 0; i < kItemCount; i++) {
  16527. auto key = "field" + std::to_string(i);
  16528. auto val = "value" + std::to_string(i);
  16529. auto it = req.form.fields.find(key);
  16530. if (it != req.form.fields.end()) {
  16531. EXPECT_EQ(val, it->second.content);
  16532. } else {
  16533. ADD_FAILURE() << "Missing field: " << key;
  16534. }
  16535. }
  16536. res.set_content("ok", "text/plain");
  16537. handled = true;
  16538. });
  16539. auto port = svr.bind_to_any_port(HOST);
  16540. auto t = thread([&] { svr.listen_after_bind(); });
  16541. auto se = detail::scope_exit([&] {
  16542. svr.stop();
  16543. t.join();
  16544. ASSERT_FALSE(svr.is_running());
  16545. ASSERT_TRUE(handled);
  16546. });
  16547. svr.wait_until_ready();
  16548. UploadFormDataItems items;
  16549. items.reserve(kItemCount);
  16550. for (size_t i = 0; i < kItemCount; i++) {
  16551. items.push_back(
  16552. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16553. }
  16554. Client cli(HOST, port);
  16555. auto res = cli.Post("/upload", items);
  16556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16557. EXPECT_EQ(StatusCode::OK_200, res->status);
  16558. }
  16559. TEST(MultipartFormDataTest, MakeFileProvider) {
  16560. // Verify make_file_provider sends a file's contents correctly.
  16561. const std::string file_content(4096, 'Z');
  16562. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16563. {
  16564. std::ofstream ofs(tmp_path, std::ios::binary);
  16565. ofs.write(file_content.data(),
  16566. static_cast<std::streamsize>(file_content.size()));
  16567. }
  16568. auto handled = false;
  16569. Server svr;
  16570. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16571. const ContentReader &content_reader) {
  16572. ASSERT_TRUE(req.is_multipart_form_data());
  16573. std::vector<FormData> items;
  16574. content_reader(
  16575. [&](const FormData &file) {
  16576. items.push_back(file);
  16577. return true;
  16578. },
  16579. [&](const char *data, size_t data_length) {
  16580. items.back().content.append(data, data_length);
  16581. return true;
  16582. });
  16583. ASSERT_EQ(1u, items.size());
  16584. EXPECT_EQ("myfile", items[0].name);
  16585. EXPECT_EQ("data.bin", items[0].filename);
  16586. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16587. EXPECT_EQ(file_content, items[0].content);
  16588. handled = true;
  16589. });
  16590. auto port = svr.bind_to_any_port(HOST);
  16591. auto t = thread([&] { svr.listen_after_bind(); });
  16592. auto se = detail::scope_exit([&] {
  16593. svr.stop();
  16594. t.join();
  16595. ASSERT_FALSE(svr.is_running());
  16596. ASSERT_TRUE(handled);
  16597. std::remove(tmp_path.c_str());
  16598. });
  16599. svr.wait_until_ready();
  16600. FormDataProviderItems providers;
  16601. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16602. "application/octet-stream"));
  16603. Client cli(HOST, port);
  16604. auto res = cli.Post("/upload", {}, {}, providers);
  16605. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16606. EXPECT_EQ(StatusCode::OK_200, res->status);
  16607. }
  16608. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16609. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16610. // (100) headers is rejected with a 400 Bad Request response.
  16611. Server svr;
  16612. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16613. res.set_content("ok", "text/plain");
  16614. });
  16615. thread t = thread([&] { svr.listen(HOST, PORT); });
  16616. auto se = detail::scope_exit([&] {
  16617. svr.stop();
  16618. t.join();
  16619. ASSERT_FALSE(svr.is_running());
  16620. });
  16621. svr.wait_until_ready();
  16622. // Build a multipart part with 101 custom headers (exceeding
  16623. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16624. std::stringstream body;
  16625. body << "--simpleboundary\r\n"
  16626. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16627. for (int i = 0; i < 101; i++) {
  16628. body << "X-Custom-Header-" << i << ": value\r\n";
  16629. }
  16630. body << "\r\n"
  16631. << "value1\r\n"
  16632. << "--simpleboundary--\r\n";
  16633. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16634. Client cli(HOST, PORT);
  16635. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16637. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16638. }
  16639. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16640. // A body that never contains the declared boundary must not be accumulated
  16641. // while the parser waits for it. Buffering it would also make every read
  16642. // rescan everything seen so far, which is quadratic in the body size.
  16643. Server svr;
  16644. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16645. res.set_content("ok", "text/plain");
  16646. });
  16647. auto port = svr.bind_to_any_port(HOST);
  16648. thread t = thread([&] { svr.listen_after_bind(); });
  16649. auto se = detail::scope_exit([&] {
  16650. svr.stop();
  16651. t.join();
  16652. ASSERT_FALSE(svr.is_running());
  16653. });
  16654. svr.wait_until_ready();
  16655. Client cli(HOST, port);
  16656. cli.set_read_timeout(60, 0);
  16657. cli.set_write_timeout(60, 0);
  16658. // '-' is the worst case: it matches the first character of the boundary, so
  16659. // every position has to be checked against it.
  16660. auto post_dashes = [&](size_t size) {
  16661. const std::string body(size, '-');
  16662. auto start = std::chrono::steady_clock::now();
  16663. auto res =
  16664. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16665. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16666. std::chrono::steady_clock::now() - start)
  16667. .count();
  16668. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16669. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16670. return ms;
  16671. };
  16672. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16673. // Windows.
  16674. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16675. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16676. // Comparing the two sizes rather than checking an absolute duration keeps
  16677. // this meaningful across build types and CI load, both of which move the
  16678. // absolute numbers by more than an order of magnitude. Four times the bytes
  16679. // costs about four times the time when parsing is linear, and about sixteen
  16680. // times when the body is buffered and rescanned.
  16681. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16682. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16683. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16684. << "ms, which suggests the body is being buffered and rescanned";
  16685. }
  16686. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16687. // A boundary can only be followed by CRLF or by "--", so anything else is
  16688. // malformed no matter what comes next. The parser must say so right away
  16689. // instead of buffering the rest of the declared body.
  16690. Server svr;
  16691. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16692. res.set_content("ok", "text/plain");
  16693. });
  16694. auto port = svr.bind_to_any_port(HOST);
  16695. thread t = thread([&] { svr.listen_after_bind(); });
  16696. auto se = detail::scope_exit([&] {
  16697. svr.stop();
  16698. t.join();
  16699. ASSERT_FALSE(svr.is_running());
  16700. });
  16701. svr.wait_until_ready();
  16702. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16703. // buffers instead of failing would still be waiting for the remaining bytes.
  16704. const std::string body = "--zzzz\r\n"
  16705. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16706. "\r\n"
  16707. "text1"
  16708. "\r\n--zzzzXX";
  16709. const std::string req = "POST /post HTTP/1.1\r\n"
  16710. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16711. "Content-Length: 1048576\r\n"
  16712. "\r\n" +
  16713. body;
  16714. std::string response;
  16715. ASSERT_TRUE(send_request(3, req, &response, port));
  16716. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16717. EXPECT_EQ("400", response.substr(9, 3));
  16718. }
  16719. // Posts a multipart body split into two writes, so that the server sees the
  16720. // split at whatever offset the caller chose, and expects the single "text1"
  16721. // field to come through.
  16722. static void expect_split_multipart_ok(const std::string &body1,
  16723. const std::string &body2) {
  16724. auto handled = false;
  16725. Server svr;
  16726. svr.Post("/post", [&](const Request &req, Response &) {
  16727. EXPECT_EQ(1u, req.form.fields.size());
  16728. EXPECT_EQ("text1", req.form.get_field("text1"));
  16729. handled = true;
  16730. });
  16731. auto port = svr.bind_to_any_port(HOST);
  16732. thread t = thread([&] { svr.listen_after_bind(); });
  16733. auto se = detail::scope_exit([&] {
  16734. svr.stop();
  16735. t.join();
  16736. ASSERT_FALSE(svr.is_running());
  16737. ASSERT_TRUE(handled);
  16738. });
  16739. svr.wait_until_ready();
  16740. // "Connection: close" makes the server close once it has answered, so the
  16741. // response drain ends immediately instead of idling until the read timeout.
  16742. const std::string head =
  16743. "POST /post HTTP/1.1\r\n"
  16744. "Host: localhost\r\n"
  16745. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16746. "Connection: close\r\n"
  16747. "Content-Length: " +
  16748. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16749. std::string response;
  16750. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16751. ASSERT_GE(response.size(), 12u) << "no response";
  16752. EXPECT_EQ("200", response.substr(9, 3));
  16753. }
  16754. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16755. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16756. // ignored, including when it does not arrive in the same read as the
  16757. // close-delimiter itself.
  16758. expect_split_multipart_ok("--zzzz\r\n"
  16759. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16760. "\r\n"
  16761. "text1"
  16762. "\r\n--zzzz--",
  16763. "\r\nthis epilogue must be ignored\r\n");
  16764. }
  16765. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16766. // The initial boundary may be preceded by a preamble of any length and may
  16767. // straddle a read boundary. Discarding data while waiting for it must not
  16768. // throw away a partial boundary sitting at the end of the buffer.
  16769. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16770. "zz\r\n"
  16771. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16772. "\r\n"
  16773. "text1"
  16774. "\r\n--zzzz--\r\n");
  16775. }
  16776. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16777. // The received boundary was only checked for being non-empty, so it could be
  16778. // as long as a header is allowed to be. The parser scans the body for
  16779. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16780. // costs a nearly full comparison at nearly every position, making the
  16781. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16782. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16783. Server svr;
  16784. svr.Post("/post", [](const Request &req, Response &res) {
  16785. EXPECT_EQ(1u, req.form.fields.size());
  16786. EXPECT_EQ("text1", req.form.get_field("text1"));
  16787. res.set_content("ok", "text/plain");
  16788. });
  16789. auto port = svr.bind_to_any_port(HOST);
  16790. thread t = thread([&] { svr.listen_after_bind(); });
  16791. auto se = detail::scope_exit([&] {
  16792. svr.stop();
  16793. t.join();
  16794. ASSERT_FALSE(svr.is_running());
  16795. });
  16796. svr.wait_until_ready();
  16797. Client cli(HOST, port);
  16798. auto post_with_boundary_of_length = [&](size_t len) {
  16799. const std::string boundary(len, 'a');
  16800. const std::string body =
  16801. "--" + boundary +
  16802. "\r\n"
  16803. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16804. "\r\n"
  16805. "text1"
  16806. "\r\n--" +
  16807. boundary + "--\r\n";
  16808. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16809. };
  16810. auto res = post_with_boundary_of_length(70);
  16811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16812. EXPECT_EQ(StatusCode::OK_200, res->status);
  16813. res = post_with_boundary_of_length(71);
  16814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16815. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16816. }
  16817. TEST(MakeFileBodyTest, Basic) {
  16818. const std::string file_content(4096, 'Z');
  16819. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16820. {
  16821. std::ofstream ofs(tmp_path, std::ios::binary);
  16822. ofs.write(file_content.data(),
  16823. static_cast<std::streamsize>(file_content.size()));
  16824. }
  16825. auto handled = false;
  16826. Server svr;
  16827. svr.Post("/upload", [&](const Request &req, Response &res) {
  16828. EXPECT_EQ(file_content, req.body);
  16829. handled = true;
  16830. res.status = StatusCode::OK_200;
  16831. });
  16832. auto port = svr.bind_to_any_port(HOST);
  16833. auto t = thread([&] { svr.listen_after_bind(); });
  16834. auto se = detail::scope_exit([&] {
  16835. svr.stop();
  16836. t.join();
  16837. ASSERT_FALSE(svr.is_running());
  16838. ASSERT_TRUE(handled);
  16839. std::remove(tmp_path.c_str());
  16840. });
  16841. svr.wait_until_ready();
  16842. auto fb = make_file_body(tmp_path);
  16843. ASSERT_GT(fb.first, 0u);
  16844. Client cli(HOST, port);
  16845. auto res =
  16846. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16848. EXPECT_EQ(StatusCode::OK_200, res->status);
  16849. }
  16850. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16851. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16852. {
  16853. std::ofstream ofs(path, std::ios::binary);
  16854. const std::string content(100, 'A');
  16855. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16856. }
  16857. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16858. auto body = make_file_body(path);
  16859. ASSERT_EQ(100u, body.first);
  16860. ASSERT_TRUE(static_cast<bool>(body.second));
  16861. // Rewritten shorter after its length was measured - and, on a server, after
  16862. // that length has already gone out as Content-Length.
  16863. {
  16864. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16865. const std::string content(10, 'A');
  16866. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16867. }
  16868. std::string written;
  16869. DataSink sink;
  16870. sink.write = [&](const char *d, size_t l) {
  16871. written.append(d, l);
  16872. return true;
  16873. };
  16874. // The provider has to report failure. write_content_with_progress() advances
  16875. // its offset only by what was written, so a provider that returns true
  16876. // without completing the length it promised is called again straight away,
  16877. // and again.
  16878. EXPECT_FALSE(body.second(0, body.first, sink));
  16879. EXPECT_EQ(std::string(10, 'A'), written);
  16880. }
  16881. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16882. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16883. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16884. {
  16885. std::ofstream ofs(path, std::ios::binary);
  16886. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16887. }
  16888. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16889. auto body = make_file_body(path);
  16890. ASSERT_EQ(content.size(), body.first);
  16891. ASSERT_TRUE(static_cast<bool>(body.second));
  16892. std::string written;
  16893. DataSink sink;
  16894. sink.write = [&](const char *d, size_t l) {
  16895. written.append(d, l);
  16896. return true;
  16897. };
  16898. EXPECT_TRUE(body.second(0, body.first, sink));
  16899. EXPECT_EQ(content, written);
  16900. }
  16901. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16902. static constexpr unsigned int number_of_tasks{1000000};
  16903. std::atomic_uint count{0};
  16904. std::unique_ptr<TaskQueue> task_queue{
  16905. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16906. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16907. auto queued = task_queue->enqueue(
  16908. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16909. EXPECT_TRUE(queued);
  16910. }
  16911. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16912. task_queue->shutdown();
  16913. #else
  16914. EXPECT_NO_THROW(task_queue->shutdown());
  16915. #endif
  16916. EXPECT_EQ(number_of_tasks, count.load());
  16917. }
  16918. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16919. static constexpr unsigned int number_of_tasks{1000000};
  16920. static constexpr unsigned int qlimit{2};
  16921. unsigned int queued_count{0};
  16922. std::atomic_uint count{0};
  16923. std::unique_ptr<TaskQueue> task_queue{
  16924. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16925. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16926. if (task_queue->enqueue(
  16927. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16928. queued_count++;
  16929. }
  16930. }
  16931. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16932. task_queue->shutdown();
  16933. #else
  16934. EXPECT_NO_THROW(task_queue->shutdown());
  16935. #endif
  16936. EXPECT_EQ(queued_count, count.load());
  16937. EXPECT_TRUE(queued_count <= number_of_tasks);
  16938. EXPECT_TRUE(queued_count >= qlimit);
  16939. }
  16940. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16941. // Use a short idle timeout so a dynamic thread spawns, times out and
  16942. // exits during the test, and the pool keeps working afterwards.
  16943. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16944. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16945. /*idle_timeout_sec=*/1}};
  16946. std::atomic_uint count{0};
  16947. std::condition_variable cv;
  16948. std::mutex mtx;
  16949. bool release = false;
  16950. // Block the base thread so the second task spawns a dynamic thread.
  16951. EXPECT_TRUE(task_queue->enqueue([&] {
  16952. std::unique_lock<std::mutex> lock(mtx);
  16953. while (!release) {
  16954. cv.wait(lock);
  16955. }
  16956. count++;
  16957. }));
  16958. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16959. // Let the dynamic thread finish its task and exceed the idle timeout.
  16960. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16961. {
  16962. std::unique_lock<std::mutex> lock(mtx);
  16963. release = true;
  16964. }
  16965. cv.notify_all();
  16966. // The pool must still accept and run tasks after the dynamic thread exited.
  16967. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16968. task_queue->shutdown();
  16969. EXPECT_EQ(3u, count.load());
  16970. }
  16971. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16972. static constexpr size_t number_of_tasks{32};
  16973. std::unique_ptr<TaskQueue> task_queue{
  16974. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16975. // Let the base threads go idle so the burst below finds them waiting.
  16976. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16977. std::mutex mtx;
  16978. std::condition_variable cv;
  16979. size_t running = 0;
  16980. bool release = false;
  16981. for (size_t i = 0; i < number_of_tasks; i++) {
  16982. EXPECT_TRUE(task_queue->enqueue([&] {
  16983. std::unique_lock<std::mutex> lock(mtx);
  16984. running++;
  16985. cv.notify_all();
  16986. cv.wait(lock, [&] { return release; });
  16987. }));
  16988. }
  16989. {
  16990. std::unique_lock<std::mutex> lock(mtx);
  16991. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16992. [&] { return running == number_of_tasks; }));
  16993. release = true;
  16994. }
  16995. cv.notify_all();
  16996. task_queue->shutdown();
  16997. }
  16998. TEST(TaskQueueTest, MaxQueuedRequests) {
  16999. static constexpr unsigned int qlimit{3};
  17000. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17001. std::condition_variable sem_cv;
  17002. std::mutex sem_mtx;
  17003. int credits = 0;
  17004. bool queued;
  17005. /* Fill up the queue with tasks that will block until we give them credits to
  17006. * complete. */
  17007. for (unsigned int n = 0; n <= qlimit;) {
  17008. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17009. std::unique_lock<std::mutex> lock(sem_mtx);
  17010. while (credits <= 0) {
  17011. sem_cv.wait(lock);
  17012. }
  17013. /* Consume the credit and signal the test code if they are all gone. */
  17014. if (--credits == 0) { sem_cv.notify_one(); }
  17015. });
  17016. if (n < qlimit) {
  17017. /* The first qlimit enqueues must succeed. */
  17018. EXPECT_TRUE(queued);
  17019. } else {
  17020. /* The last one will succeed only when the worker thread
  17021. * starts and dequeues the first blocking task. Although
  17022. * not necessary for the correctness of this test, we sleep for
  17023. * a short while to avoid busy waiting. */
  17024. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17025. }
  17026. if (queued) { n++; }
  17027. }
  17028. /* Further enqueues must fail since the queue is full. */
  17029. for (auto i = 0; i < 4; i++) {
  17030. queued = task_queue->enqueue([] {});
  17031. EXPECT_FALSE(queued);
  17032. }
  17033. /* Give the credits to allow the previous tasks to complete. */
  17034. {
  17035. std::unique_lock<std::mutex> lock(sem_mtx);
  17036. credits += qlimit + 1;
  17037. }
  17038. sem_cv.notify_all();
  17039. /* Wait for all the credits to be consumed. */
  17040. {
  17041. std::unique_lock<std::mutex> lock(sem_mtx);
  17042. while (credits > 0) {
  17043. sem_cv.wait(lock);
  17044. }
  17045. }
  17046. /* Check that we are able again to enqueue at least qlimit tasks. */
  17047. for (unsigned int i = 0; i < qlimit; i++) {
  17048. queued = task_queue->enqueue([] {});
  17049. EXPECT_TRUE(queued);
  17050. }
  17051. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17052. task_queue->shutdown();
  17053. #else
  17054. EXPECT_NO_THROW(task_queue->shutdown());
  17055. #endif
  17056. }
  17057. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17058. Server svr;
  17059. std::string method;
  17060. std::string body;
  17061. auto has_content_length = false;
  17062. auto has_transfer_encoding = false;
  17063. std::atomic<int> bad_requests{0};
  17064. // Leftover body bytes get parsed as a malformed request and answered with
  17065. // 400
  17066. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17067. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17068. });
  17069. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17070. res.set_redirect("/down", StatusCode::SeeOther_303);
  17071. });
  17072. svr.Get("/down", [&](const Request &req, Response &res) {
  17073. method = req.method;
  17074. body = req.body;
  17075. has_content_length = req.has_header("Content-Length");
  17076. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17077. res.set_content("ok", "text/plain");
  17078. });
  17079. auto port = svr.bind_to_any_port(HOST);
  17080. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17081. auto se = detail::scope_exit([&] {
  17082. svr.stop();
  17083. thread.join();
  17084. ASSERT_FALSE(svr.is_running());
  17085. });
  17086. svr.wait_until_ready();
  17087. const std::string payload = "SECRET-BODY";
  17088. auto check = [&](Client &cli, const Result &res) {
  17089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17090. EXPECT_EQ(StatusCode::OK_200, res->status);
  17091. EXPECT_EQ("ok", res->body);
  17092. EXPECT_EQ("GET", method);
  17093. EXPECT_TRUE(body.empty());
  17094. EXPECT_FALSE(has_content_length);
  17095. EXPECT_FALSE(has_transfer_encoding);
  17096. // Nothing of the original body may be left on the connection
  17097. auto res2 = cli.Get("/down");
  17098. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17099. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17100. EXPECT_EQ("ok", res2->body);
  17101. EXPECT_EQ(0, bad_requests);
  17102. };
  17103. // With content length
  17104. {
  17105. Client cli(HOST, port);
  17106. cli.set_keep_alive(true);
  17107. cli.set_follow_location(true);
  17108. auto res = cli.Post(
  17109. "/up", payload.size(),
  17110. [&](size_t offset, size_t length, DataSink &sink) {
  17111. return sink.write(payload.data() + offset, length);
  17112. },
  17113. "text/plain");
  17114. check(cli, res);
  17115. }
  17116. // Without content length (chunked)
  17117. {
  17118. Client cli(HOST, port);
  17119. cli.set_keep_alive(true);
  17120. cli.set_follow_location(true);
  17121. auto res = cli.Post(
  17122. "/up",
  17123. [&](size_t /*offset*/, DataSink &sink) {
  17124. sink.write(payload.data(), payload.size());
  17125. sink.done();
  17126. return true;
  17127. },
  17128. "text/plain");
  17129. check(cli, res);
  17130. }
  17131. }
  17132. TEST(RedirectTest, LocationPathIsNotDecoded) {
  17133. Server svr;
  17134. std::string target;
  17135. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  17136. // Echo the still-encoded name back in the Location
  17137. const std::string prefix = "/start/";
  17138. res.status = StatusCode::Found_302;
  17139. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  17140. });
  17141. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  17142. target = req.target;
  17143. res.set_content("ok", "text/plain");
  17144. });
  17145. auto port = svr.bind_to_any_port(HOST);
  17146. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17147. auto se = detail::scope_exit([&] {
  17148. svr.stop();
  17149. thread.join();
  17150. ASSERT_FALSE(svr.is_running());
  17151. });
  17152. svr.wait_until_ready();
  17153. // Decoding the Location path would turn the first four into a path
  17154. // separator, a query delimiter, a fragment delimiter and a different
  17155. // percent-encoded octet. The rest must keep reaching the server as they are.
  17156. const std::vector<std::string> names = {
  17157. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  17158. };
  17159. for (auto path_encode : {true, false}) {
  17160. Client cli(HOST, port);
  17161. cli.set_follow_location(true);
  17162. cli.set_path_encode(path_encode);
  17163. for (const auto &name : names) {
  17164. target.clear();
  17165. auto res = cli.Get("/start/" + name);
  17166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17167. EXPECT_EQ(StatusCode::OK_200, res->status);
  17168. EXPECT_EQ("/dest/" + name, target);
  17169. }
  17170. }
  17171. }
  17172. TEST(RedirectTest, NotModifiedIsReturned) {
  17173. Server svr;
  17174. svr.Get("/cached", [](const Request &, Response &res) {
  17175. res.status = StatusCode::NotModified_304;
  17176. });
  17177. auto port = svr.bind_to_any_port(HOST);
  17178. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17179. auto se = detail::scope_exit([&] {
  17180. svr.stop();
  17181. thread.join();
  17182. ASSERT_FALSE(svr.is_running());
  17183. });
  17184. svr.wait_until_ready();
  17185. Client cli(HOST, port);
  17186. cli.set_follow_location(true);
  17187. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  17188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17189. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  17190. }
  17191. TEST(RedirectTest, NoLocationIsReturned) {
  17192. Server svr;
  17193. svr.Get("/no-location", [](const Request &, Response &res) {
  17194. res.status = StatusCode::Found_302;
  17195. res.set_content("no location", "text/plain");
  17196. });
  17197. auto port = svr.bind_to_any_port(HOST);
  17198. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17199. auto se = detail::scope_exit([&] {
  17200. svr.stop();
  17201. thread.join();
  17202. ASSERT_FALSE(svr.is_running());
  17203. });
  17204. svr.wait_until_ready();
  17205. Client cli(HOST, port);
  17206. cli.set_follow_location(true);
  17207. auto res = cli.Get("/no-location");
  17208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17209. EXPECT_EQ(StatusCode::Found_302, res->status);
  17210. EXPECT_EQ("no location", res->body);
  17211. // The callbacks see the body of the response that is returned
  17212. auto handler_called = false;
  17213. auto progress_called = false;
  17214. std::string body;
  17215. auto res2 = cli.Get(
  17216. "/no-location",
  17217. [&](const Response &) {
  17218. handler_called = true;
  17219. return true;
  17220. },
  17221. [&](const char *data, size_t data_length) {
  17222. body.append(data, data_length);
  17223. return true;
  17224. },
  17225. [&](size_t, size_t) {
  17226. progress_called = true;
  17227. return true;
  17228. });
  17229. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17230. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17231. EXPECT_TRUE(handler_called);
  17232. EXPECT_TRUE(progress_called);
  17233. EXPECT_EQ("no location", body);
  17234. }
  17235. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17236. Server svr;
  17237. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17238. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17239. });
  17240. svr.Get("/hello", [](const Request &req, Response &res) {
  17241. res.set_content(req.get_param_value("key"), "text/plain");
  17242. });
  17243. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17244. auto se = detail::scope_exit([&] {
  17245. svr.stop();
  17246. thread.join();
  17247. ASSERT_FALSE(svr.is_running());
  17248. });
  17249. svr.wait_until_ready();
  17250. {
  17251. Client cli(HOST, PORT);
  17252. cli.set_follow_location(true);
  17253. auto res = cli.Get("/");
  17254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17255. EXPECT_EQ(StatusCode::OK_200, res->status);
  17256. EXPECT_EQ("val&key2=val2", res->body);
  17257. }
  17258. }
  17259. #endif
  17260. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17261. Server svr;
  17262. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17263. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17264. });
  17265. svr.Get("/hello", [](const Request &req, Response &res) {
  17266. res.set_content(req.get_param_value("key"), "text/plain");
  17267. });
  17268. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17269. auto se = detail::scope_exit([&] {
  17270. svr.stop();
  17271. thread.join();
  17272. ASSERT_FALSE(svr.is_running());
  17273. });
  17274. svr.wait_until_ready();
  17275. {
  17276. Client cli(HOST, PORT);
  17277. cli.set_follow_location(true);
  17278. auto res = cli.Get("/");
  17279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17280. EXPECT_EQ(StatusCode::OK_200, res->status);
  17281. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17282. }
  17283. }
  17284. TEST(RedirectTest, RedirectWithPlusInPath) {
  17285. Server svr;
  17286. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17287. res.set_redirect("/a+b");
  17288. });
  17289. // Route pattern uses regex; escape + as \\+
  17290. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17291. res.set_content(req.path, "text/plain");
  17292. });
  17293. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17294. auto se = detail::scope_exit([&] {
  17295. svr.stop();
  17296. thread.join();
  17297. ASSERT_FALSE(svr.is_running());
  17298. });
  17299. svr.wait_until_ready();
  17300. {
  17301. Client cli(HOST, PORT);
  17302. cli.set_follow_location(true);
  17303. auto res = cli.Get("/");
  17304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17305. EXPECT_EQ(StatusCode::OK_200, res->status);
  17306. EXPECT_EQ("/a+b", res->body);
  17307. }
  17308. }
  17309. TEST(RedirectTest, ResolveRelativeLocation) {
  17310. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17311. const std::vector<std::pair<std::string, std::string>> cases = {
  17312. {"g", "/b/c/g"},
  17313. {"./g", "/b/c/g"},
  17314. {"g/", "/b/c/g/"},
  17315. {"?y", "/b/c/d;p?y"},
  17316. {"g?y", "/b/c/g?y"},
  17317. {"#s", "/b/c/d;p?q#s"},
  17318. {"g#s", "/b/c/g#s"},
  17319. {"g?y#s", "/b/c/g?y#s"},
  17320. {";x", "/b/c/;x"},
  17321. {"g;x", "/b/c/g;x"},
  17322. {".", "/b/c/"},
  17323. {"./", "/b/c/"},
  17324. {"..", "/b/"},
  17325. {"../", "/b/"},
  17326. {"../g", "/b/g"},
  17327. {"../..", "/"},
  17328. {"../../", "/"},
  17329. {"../../g", "/g"},
  17330. {"../../../g", "/g"},
  17331. {"g.", "/b/c/g."},
  17332. {".g", "/b/c/.g"},
  17333. {"g..", "/b/c/g.."},
  17334. {"..g", "/b/c/..g"},
  17335. {"./../g", "/b/g"},
  17336. {"./g/.", "/b/c/g/"},
  17337. {"g/./h", "/b/c/g/h"},
  17338. {"g/../h", "/b/c/h"},
  17339. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17340. {"g;x=1/../y", "/b/c/y"},
  17341. {"g?y/./x", "/b/c/g?y/./x"},
  17342. {"g#s/../x", "/b/c/g#s/../x"},
  17343. // Not relative-path references, so left for parse_url.
  17344. {"/g", "/g"},
  17345. {"//g", "//g"},
  17346. {"http://g/x", "http://g/x"},
  17347. {"g:h", "g:h"},
  17348. };
  17349. for (const auto &c : cases) {
  17350. EXPECT_EQ(c.second,
  17351. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17352. << c.first;
  17353. }
  17354. }
  17355. TEST(RedirectTest, RemoveDotSegments) {
  17356. // RFC 3986 section 5.2.4
  17357. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  17358. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  17359. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  17360. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  17361. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  17362. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  17363. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  17364. }
  17365. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  17366. Server svr;
  17367. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  17368. res.set_redirect("/dir/../target?x=1");
  17369. });
  17370. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  17371. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  17372. "/dir/./../target");
  17373. });
  17374. svr.Get("/target", [](const Request &req, Response &res) {
  17375. res.set_content(req.path, "text/plain");
  17376. });
  17377. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  17378. auto se = detail::scope_exit([&] {
  17379. svr.stop();
  17380. th.join();
  17381. ASSERT_FALSE(svr.is_running());
  17382. });
  17383. svr.wait_until_ready();
  17384. Client cli("localhost", PORT);
  17385. cli.set_follow_location(true);
  17386. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  17387. auto res = cli.Get(path);
  17388. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  17389. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  17390. EXPECT_EQ("/target", res->body) << path;
  17391. }
  17392. }
  17393. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17394. Server svr;
  17395. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17396. res.set_redirect(req.get_param_value("to"));
  17397. });
  17398. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17399. res.set_content(req.target, "text/plain");
  17400. });
  17401. svr.Get("/other", [](const Request &req, Response &res) {
  17402. res.set_content(req.target, "text/plain");
  17403. });
  17404. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17405. auto se = detail::scope_exit([&] {
  17406. svr.stop();
  17407. thread.join();
  17408. ASSERT_FALSE(svr.is_running());
  17409. });
  17410. svr.wait_until_ready();
  17411. const std::vector<std::pair<std::string, std::string>> cases = {
  17412. {"next", "/dir/next"},
  17413. {"./next?x=1", "/dir/next?x=1"},
  17414. {"../other", "/other"},
  17415. };
  17416. for (const auto &c : cases) {
  17417. Client cli(HOST, PORT);
  17418. cli.set_follow_location(true);
  17419. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17420. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17421. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17422. EXPECT_EQ(c.second, res->body) << c.first;
  17423. }
  17424. }
  17425. #ifdef CPPHTTPLIB_SSL_ENABLED
  17426. TEST(RedirectTest, Issue2185_Online) {
  17427. SSLClient client("github.com");
  17428. client.set_follow_location(true);
  17429. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17430. "Coollab-Windows.zip");
  17431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17432. EXPECT_EQ(StatusCode::OK_200, res->status);
  17433. EXPECT_EQ(9920427U, res->body.size());
  17434. }
  17435. #endif
  17436. TEST(VulnerabilityTest, CRLFInjection) {
  17437. Server svr;
  17438. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17439. res.set_content("Hello 1", "text/plain");
  17440. });
  17441. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17442. res.set_content("Hello 2", "text/plain");
  17443. });
  17444. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17445. res.set_content("Hello 3", "text/plain");
  17446. });
  17447. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17448. res.set_content("Hello 4", "text/plain");
  17449. });
  17450. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17451. for (const auto &x : req.headers) {
  17452. auto key = x.first;
  17453. EXPECT_STRNE("evil", key.c_str());
  17454. }
  17455. });
  17456. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17457. auto se = detail::scope_exit([&] {
  17458. svr.stop();
  17459. thread.join();
  17460. ASSERT_FALSE(svr.is_running());
  17461. });
  17462. svr.wait_until_ready();
  17463. {
  17464. Client cli(HOST, PORT);
  17465. cli.Post("/test1", "A=B",
  17466. "application/x-www-form-urlencoded\r\nevil: hello1");
  17467. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17468. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17469. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17470. }
  17471. }
  17472. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17473. auto server_thread = std::thread([] {
  17474. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17475. default_socket_options(srv);
  17476. sockaddr_in addr{};
  17477. addr.sin_family = AF_INET;
  17478. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17479. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17480. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17481. ::listen(srv, 1);
  17482. sockaddr_in cli_addr{};
  17483. socklen_t cli_len = sizeof(cli_addr);
  17484. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17485. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17486. std::string buf_all;
  17487. char buf[2048];
  17488. ssize_t n;
  17489. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17490. buf_all.append(buf, static_cast<size_t>(n));
  17491. size_t pos;
  17492. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17493. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17494. auto e = request_block.find("\r\n");
  17495. if (e != std::string::npos) {
  17496. auto request_line = request_block.substr(0, e);
  17497. std::string msg =
  17498. "CRLF injection detected in request line: '" + request_line + "'";
  17499. EXPECT_FALSE(true) << msg;
  17500. }
  17501. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17502. ::send(cli,
  17503. #ifdef _WIN32
  17504. static_cast<const char *>(resp.c_str()),
  17505. static_cast<int>(resp.size()),
  17506. #else
  17507. resp.c_str(), resp.size(),
  17508. #endif
  17509. 0);
  17510. buf_all.erase(0, pos + 4);
  17511. }
  17512. }
  17513. detail::close_socket(cli);
  17514. detail::close_socket(srv);
  17515. });
  17516. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17517. auto cli = Client("127.0.0.1", PORT + 1);
  17518. auto headers = Headers{
  17519. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17520. {"Connection", "keep-alive"}};
  17521. auto res = cli.Get("/hi", headers);
  17522. EXPECT_FALSE(res);
  17523. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17524. server_thread.join();
  17525. }
  17526. // A request rejected before any byte reaches the socket must fail right away
  17527. // instead of waiting for a response the server will never send.
  17528. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17529. // The kernel completes the TCP handshake from the listen backlog, so the
  17530. // client connects, but nothing ever reads, responds or closes.
  17531. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17532. default_socket_options(srv);
  17533. sockaddr_in addr{};
  17534. addr.sin_family = AF_INET;
  17535. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17536. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17537. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17538. ASSERT_EQ(0, ::listen(srv, 8));
  17539. auto cli = Client("127.0.0.1", PORT + 1);
  17540. cli.set_read_timeout(10, 0);
  17541. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17542. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17543. std::chrono::steady_clock::now() - start)
  17544. .count();
  17545. };
  17546. {
  17547. Request req;
  17548. req.method = "GE T";
  17549. req.path = "/";
  17550. auto start = std::chrono::steady_clock::now();
  17551. auto res = cli.send(req);
  17552. EXPECT_FALSE(res);
  17553. EXPECT_EQ(Error::Write, res.error());
  17554. EXPECT_LT(elapsed_ms(start), 1000);
  17555. }
  17556. {
  17557. auto start = std::chrono::steady_clock::now();
  17558. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17559. EXPECT_FALSE(res);
  17560. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17561. EXPECT_LT(elapsed_ms(start), 1000);
  17562. }
  17563. EXPECT_FALSE(cli.is_socket_open());
  17564. detail::close_socket(srv);
  17565. }
  17566. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17567. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17568. default_socket_options(srv);
  17569. sockaddr_in addr{};
  17570. addr.sin_family = AF_INET;
  17571. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17572. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17573. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17574. ASSERT_EQ(0, ::listen(srv, 1));
  17575. std::string received;
  17576. auto server_thread = std::thread([&] {
  17577. auto sock = ::accept(srv, nullptr, nullptr);
  17578. if (sock == INVALID_SOCKET) { return; }
  17579. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17580. char buf[2048];
  17581. ssize_t n;
  17582. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17583. received.append(buf, static_cast<size_t>(n));
  17584. }
  17585. detail::close_socket(sock);
  17586. });
  17587. {
  17588. auto cli = Client("127.0.0.1", PORT + 1);
  17589. // "Z" sorts after the default headers, so writing straight to the socket
  17590. // would have sent the request line and those headers before the rejection.
  17591. auto handle =
  17592. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17593. EXPECT_FALSE(handle.is_valid());
  17594. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17595. }
  17596. server_thread.join();
  17597. detail::close_socket(srv);
  17598. EXPECT_TRUE(received.empty()) << received;
  17599. }
  17600. TEST(PathParamsTest, StaticMatch) {
  17601. const auto pattern = "/users/all";
  17602. detail::PathParamsMatcher matcher(pattern);
  17603. Request request;
  17604. request.path = "/users/all";
  17605. ASSERT_TRUE(matcher.match(request));
  17606. std::unordered_map<std::string, std::string> expected_params = {};
  17607. EXPECT_EQ(request.path_params, expected_params);
  17608. }
  17609. TEST(PathParamsTest, StaticMismatch) {
  17610. const auto pattern = "/users/all";
  17611. detail::PathParamsMatcher matcher(pattern);
  17612. Request request;
  17613. request.path = "/users/1";
  17614. ASSERT_FALSE(matcher.match(request));
  17615. }
  17616. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17617. const auto pattern = "/users/:id/subscriptions";
  17618. detail::PathParamsMatcher matcher(pattern);
  17619. Request request;
  17620. request.path = "/users/42/subscriptions";
  17621. ASSERT_TRUE(matcher.match(request));
  17622. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17623. EXPECT_EQ(request.path_params, expected_params);
  17624. }
  17625. TEST(PathParamsTest, SingleParamInTheEnd) {
  17626. const auto pattern = "/users/:id";
  17627. detail::PathParamsMatcher matcher(pattern);
  17628. Request request;
  17629. request.path = "/users/24";
  17630. ASSERT_TRUE(matcher.match(request));
  17631. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17632. EXPECT_EQ(request.path_params, expected_params);
  17633. }
  17634. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17635. const auto pattern = "/users/:id/";
  17636. detail::PathParamsMatcher matcher(pattern);
  17637. Request request;
  17638. request.path = "/users/42/";
  17639. ASSERT_TRUE(matcher.match(request));
  17640. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17641. EXPECT_EQ(request.path_params, expected_params);
  17642. }
  17643. TEST(PathParamsTest, EmptyParam) {
  17644. const auto pattern = "/users/:id/";
  17645. detail::PathParamsMatcher matcher(pattern);
  17646. Request request;
  17647. request.path = "/users//";
  17648. ASSERT_TRUE(matcher.match(request));
  17649. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17650. EXPECT_EQ(request.path_params, expected_params);
  17651. }
  17652. TEST(PathParamsTest, FragmentMismatch) {
  17653. const auto pattern = "/users/:id/";
  17654. detail::PathParamsMatcher matcher(pattern);
  17655. Request request;
  17656. request.path = "/admins/24/";
  17657. ASSERT_FALSE(matcher.match(request));
  17658. }
  17659. TEST(PathParamsTest, ExtraFragments) {
  17660. const auto pattern = "/users/:id";
  17661. detail::PathParamsMatcher matcher(pattern);
  17662. Request request;
  17663. request.path = "/users/42/subscriptions";
  17664. ASSERT_FALSE(matcher.match(request));
  17665. }
  17666. TEST(PathParamsTest, MissingTrailingParam) {
  17667. const auto pattern = "/users/:id";
  17668. detail::PathParamsMatcher matcher(pattern);
  17669. Request request;
  17670. request.path = "/users";
  17671. ASSERT_FALSE(matcher.match(request));
  17672. }
  17673. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17674. const auto pattern = "/users/:id/subscriptions";
  17675. detail::PathParamsMatcher matcher(pattern);
  17676. Request request;
  17677. request.path = "/users/subscriptions";
  17678. ASSERT_FALSE(matcher.match(request));
  17679. }
  17680. TEST(PathParamsTest, MultipleParams) {
  17681. const auto pattern = "/users/:userid/subscriptions/:subid";
  17682. detail::PathParamsMatcher matcher(pattern);
  17683. Request request;
  17684. request.path = "/users/42/subscriptions/2";
  17685. ASSERT_TRUE(matcher.match(request));
  17686. std::unordered_map<std::string, std::string> expected_params = {
  17687. {"userid", "42"}, {"subid", "2"}};
  17688. EXPECT_EQ(request.path_params, expected_params);
  17689. }
  17690. TEST(PathParamsTest, SequenceOfParams) {
  17691. const auto pattern = "/values/:x/:y/:z";
  17692. detail::PathParamsMatcher matcher(pattern);
  17693. Request request;
  17694. request.path = "/values/1/2/3";
  17695. ASSERT_TRUE(matcher.match(request));
  17696. std::unordered_map<std::string, std::string> expected_params = {
  17697. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17698. EXPECT_EQ(request.path_params, expected_params);
  17699. }
  17700. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17701. const auto pattern = "/prefix:suffix";
  17702. detail::PathParamsMatcher matcher(pattern);
  17703. Request request;
  17704. request.path = "/prefix:suffix";
  17705. ASSERT_TRUE(matcher.match(request));
  17706. const std::unordered_map<std::string, std::string> expected_params = {};
  17707. EXPECT_EQ(request.path_params, expected_params);
  17708. }
  17709. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17710. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17711. // calling thread's stack on a long enough path for a quantified pattern;
  17712. // RegexMatcher must refuse to run regex matching on paths beyond
  17713. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17714. detail::RegexMatcher matcher("/files/(.*)");
  17715. Request within_limit;
  17716. within_limit.path = "/files/" + std::string(10, 'A');
  17717. EXPECT_TRUE(matcher.match(within_limit));
  17718. Request over_limit;
  17719. over_limit.path =
  17720. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17721. EXPECT_FALSE(matcher.match(over_limit));
  17722. }
  17723. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17724. Server svr;
  17725. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17726. res.set_content("ok", "text/plain");
  17727. });
  17728. auto port = svr.bind_to_any_port(HOST);
  17729. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17730. auto se = detail::scope_exit([&] {
  17731. svr.stop();
  17732. thread.join();
  17733. ASSERT_FALSE(svr.is_running());
  17734. });
  17735. svr.wait_until_ready();
  17736. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17737. // request URI limit; this used to be able to crash the process.
  17738. std::string path =
  17739. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17740. std::string req = "GET " + path +
  17741. " HTTP/1.1\r\n"
  17742. "Host: " +
  17743. std::string(HOST) + ":" + std::to_string(port) +
  17744. "\r\n"
  17745. "Connection: close\r\n"
  17746. "\r\n";
  17747. std::string response;
  17748. ASSERT_TRUE(send_request(5, req, &response, port));
  17749. EXPECT_NE(std::string::npos, response.find("404"));
  17750. }
  17751. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17752. Server svr;
  17753. auto handler = [](const Request & /*req*/, Response &res) {
  17754. res.set_content("hit", "text/plain");
  17755. };
  17756. // No regex metacharacter, so this one is compared literally
  17757. svr.Get("/literal/route", handler);
  17758. // '.' is a regex metacharacter, so this one must keep regex semantics
  17759. svr.Get("/a.c", handler);
  17760. auto port = svr.bind_to_any_port(HOST);
  17761. std::thread t([&]() { svr.listen_after_bind(); });
  17762. auto se = detail::scope_exit([&] {
  17763. svr.stop();
  17764. t.join();
  17765. ASSERT_FALSE(svr.is_running());
  17766. });
  17767. svr.wait_until_ready();
  17768. Client cli(HOST, port);
  17769. struct {
  17770. const char *path;
  17771. int status;
  17772. } cases[] = {
  17773. {"/literal/route", StatusCode::OK_200},
  17774. {"/literal/routes", StatusCode::NotFound_404},
  17775. {"/literal/rout", StatusCode::NotFound_404},
  17776. {"/abc", StatusCode::OK_200},
  17777. {"/a.c", StatusCode::OK_200},
  17778. };
  17779. for (const auto &x : cases) {
  17780. auto res = cli.Get(x.path);
  17781. ASSERT_TRUE(res) << x.path;
  17782. EXPECT_EQ(x.status, res->status) << x.path;
  17783. }
  17784. }
  17785. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17786. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17787. // from exhausting the stack, so it must only constrain routes that actually
  17788. // run a regular expression. A literal route is matched by comparison and
  17789. // stays usable at any length.
  17790. Server svr;
  17791. const std::string pattern =
  17792. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17793. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17794. res.set_content("hit", "text/plain");
  17795. });
  17796. auto port = svr.bind_to_any_port(HOST);
  17797. std::thread t([&]() { svr.listen_after_bind(); });
  17798. auto se = detail::scope_exit([&] {
  17799. svr.stop();
  17800. t.join();
  17801. ASSERT_FALSE(svr.is_running());
  17802. });
  17803. svr.wait_until_ready();
  17804. Client cli(HOST, port);
  17805. auto res = cli.Get(pattern);
  17806. ASSERT_TRUE(res);
  17807. EXPECT_EQ(StatusCode::OK_200, res->status);
  17808. }
  17809. TEST(ParseUrlTest, VariousPatterns) {
  17810. {
  17811. detail::UrlComponents uc;
  17812. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17813. EXPECT_EQ("http", uc.scheme);
  17814. EXPECT_EQ("example.com", uc.host);
  17815. EXPECT_EQ("8080", uc.port);
  17816. EXPECT_EQ("/path", uc.path);
  17817. EXPECT_EQ("?q=1", uc.query);
  17818. }
  17819. {
  17820. detail::UrlComponents uc;
  17821. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17822. EXPECT_EQ("https", uc.scheme);
  17823. EXPECT_EQ("example.com", uc.host);
  17824. EXPECT_TRUE(uc.port.empty());
  17825. EXPECT_EQ("/path", uc.path);
  17826. }
  17827. {
  17828. detail::UrlComponents uc;
  17829. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17830. EXPECT_EQ("::1", uc.host);
  17831. EXPECT_EQ("8080", uc.port);
  17832. EXPECT_EQ("/path", uc.path);
  17833. }
  17834. {
  17835. detail::UrlComponents uc;
  17836. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17837. }
  17838. {
  17839. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17840. // the path while the connection still targets the bracketed host.
  17841. detail::UrlComponents uc;
  17842. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17843. }
  17844. {
  17845. detail::UrlComponents uc;
  17846. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17847. }
  17848. {
  17849. detail::UrlComponents uc;
  17850. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17851. EXPECT_EQ("::1", uc.host);
  17852. EXPECT_TRUE(uc.port.empty());
  17853. EXPECT_EQ("/path", uc.path);
  17854. }
  17855. {
  17856. detail::UrlComponents uc;
  17857. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17858. EXPECT_TRUE(uc.scheme.empty());
  17859. EXPECT_EQ("example.com", uc.host);
  17860. EXPECT_EQ("/path", uc.path);
  17861. EXPECT_EQ("?q=1", uc.query);
  17862. }
  17863. {
  17864. detail::UrlComponents uc;
  17865. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17866. EXPECT_TRUE(uc.host.empty());
  17867. EXPECT_EQ("/path", uc.path);
  17868. EXPECT_EQ("?q=1", uc.query);
  17869. }
  17870. {
  17871. detail::UrlComponents uc;
  17872. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17873. EXPECT_EQ("example.com", uc.host);
  17874. EXPECT_EQ("8080", uc.port);
  17875. }
  17876. {
  17877. // Unix socket path — must not be parsed as host
  17878. detail::UrlComponents uc;
  17879. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17880. EXPECT_TRUE(uc.host.empty());
  17881. }
  17882. {
  17883. detail::UrlComponents uc;
  17884. ASSERT_TRUE(detail::parse_url("", uc));
  17885. EXPECT_TRUE(uc.host.empty());
  17886. EXPECT_TRUE(uc.path.empty());
  17887. }
  17888. {
  17889. detail::UrlComponents uc;
  17890. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17891. }
  17892. {
  17893. detail::UrlComponents uc;
  17894. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17895. }
  17896. {
  17897. // Accepted by parse_url; callers restrict to http/https
  17898. detail::UrlComponents uc;
  17899. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17900. EXPECT_EQ("ftp", uc.scheme);
  17901. }
  17902. {
  17903. detail::UrlComponents uc;
  17904. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17905. }
  17906. {
  17907. detail::UrlComponents uc;
  17908. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17909. }
  17910. }
  17911. TEST(ParseUrlTest, FragmentHandling) {
  17912. {
  17913. detail::UrlComponents uc;
  17914. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17915. EXPECT_EQ("/path", uc.path);
  17916. EXPECT_TRUE(uc.query.empty());
  17917. }
  17918. {
  17919. detail::UrlComponents uc;
  17920. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17921. EXPECT_TRUE(uc.path.empty());
  17922. EXPECT_TRUE(uc.query.empty());
  17923. }
  17924. }
  17925. TEST(ParseUrlTest, UserinfoHandling) {
  17926. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17927. // parsers would see evil.com as the host.
  17928. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17929. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17930. for (auto url : urls) {
  17931. detail::UrlComponents uc;
  17932. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17933. }
  17934. }
  17935. TEST(ParseUrlTest, IPv6EdgeCases) {
  17936. {
  17937. detail::UrlComponents uc;
  17938. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17939. EXPECT_TRUE(uc.scheme.empty());
  17940. EXPECT_EQ("::1", uc.host);
  17941. EXPECT_EQ("8080", uc.port);
  17942. }
  17943. {
  17944. // Zone ID '%25' is not in [a-fA-F0-9:]
  17945. detail::UrlComponents uc;
  17946. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17947. }
  17948. }
  17949. TEST(ParseUrlTest, SchemeEdgeCases) {
  17950. {
  17951. detail::UrlComponents uc;
  17952. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17953. }
  17954. {
  17955. detail::UrlComponents uc;
  17956. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17957. }
  17958. {
  17959. detail::UrlComponents uc;
  17960. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17961. }
  17962. }
  17963. TEST(ParseUrlTest, PortEdgeCases) {
  17964. {
  17965. detail::UrlComponents uc;
  17966. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17967. EXPECT_TRUE(uc.port.empty());
  17968. EXPECT_EQ("/path", uc.path);
  17969. }
  17970. {
  17971. // parse_url accepts any port string; validation is done by parse_port
  17972. detail::UrlComponents uc;
  17973. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17974. EXPECT_EQ("abc", uc.port);
  17975. }
  17976. }
  17977. TEST(ParseUrlTest, WebSocketPatterns) {
  17978. {
  17979. detail::UrlComponents uc;
  17980. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17981. EXPECT_EQ("ws", uc.scheme);
  17982. EXPECT_EQ("echo.example.com", uc.host);
  17983. EXPECT_EQ("8080", uc.port);
  17984. EXPECT_EQ("/ws", uc.path);
  17985. }
  17986. {
  17987. detail::UrlComponents uc;
  17988. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17989. EXPECT_EQ("wss", uc.scheme);
  17990. EXPECT_EQ("echo.example.com", uc.host);
  17991. EXPECT_TRUE(uc.port.empty());
  17992. EXPECT_EQ("/ws", uc.path);
  17993. }
  17994. }
  17995. TEST(ParseUrlTest, QueryOnly) {
  17996. detail::UrlComponents uc;
  17997. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17998. EXPECT_TRUE(uc.host.empty());
  17999. EXPECT_TRUE(uc.path.empty());
  18000. EXPECT_EQ("?q=1&r=2", uc.query);
  18001. }
  18002. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18003. detail::UrlComponents uc;
  18004. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18005. EXPECT_TRUE(uc.scheme.empty());
  18006. EXPECT_EQ("example.com", uc.host);
  18007. EXPECT_EQ("443", uc.port);
  18008. EXPECT_EQ("/path", uc.path);
  18009. }
  18010. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18011. // If ipv6 regex working, regex match codepath is taken.
  18012. // else port will default to 80 in Client impl
  18013. int clientImplMagicPort = 80;
  18014. int port = 4321;
  18015. // above ports must be different to avoid false negative
  18016. EXPECT_NE(clientImplMagicPort, port);
  18017. std::string ipV6TestURL = "http://[ff06::c3]";
  18018. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18019. CLIENT_PRIVATE_KEY_FILE);
  18020. EXPECT_EQ(cli.port(), port);
  18021. }
  18022. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18023. auto file_path = "./www/dir/index.html";
  18024. auto dir_path = "./www/dir";
  18025. detail::FileStat stat_file(file_path);
  18026. EXPECT_TRUE(stat_file.is_file());
  18027. EXPECT_FALSE(stat_file.is_dir());
  18028. detail::FileStat stat_dir(dir_path);
  18029. EXPECT_FALSE(stat_dir.is_file());
  18030. EXPECT_TRUE(stat_dir.is_dir());
  18031. }
  18032. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18033. // IPv4 with default HTTP port (80)
  18034. EXPECT_EQ("example.com",
  18035. detail::make_host_and_port_string("example.com", 80, false));
  18036. // IPv4 with default HTTPS port (443)
  18037. EXPECT_EQ("example.com",
  18038. detail::make_host_and_port_string("example.com", 443, true));
  18039. // IPv4 with non-default HTTP port
  18040. EXPECT_EQ("example.com:8080",
  18041. detail::make_host_and_port_string("example.com", 8080, false));
  18042. // IPv4 with non-default HTTPS port
  18043. EXPECT_EQ("example.com:8443",
  18044. detail::make_host_and_port_string("example.com", 8443, true));
  18045. // IPv6 with default HTTP port (80)
  18046. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18047. // IPv6 with default HTTPS port (443)
  18048. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18049. // IPv6 with non-default HTTP port
  18050. EXPECT_EQ("[::1]:8080",
  18051. detail::make_host_and_port_string("::1", 8080, false));
  18052. // IPv6 with non-default HTTPS port
  18053. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18054. // IPv6 full address with default port
  18055. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  18056. detail::make_host_and_port_string(
  18057. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  18058. // IPv6 full address with non-default port
  18059. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  18060. detail::make_host_and_port_string(
  18061. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  18062. // IPv6 localhost with non-default port
  18063. EXPECT_EQ("[::1]:3000",
  18064. detail::make_host_and_port_string("::1", 3000, false));
  18065. // IPv6 with zone ID (link-local address) with default port
  18066. EXPECT_EQ("[fe80::1%eth0]",
  18067. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  18068. // IPv6 with zone ID (link-local address) with non-default port
  18069. EXPECT_EQ("[fe80::1%eth0]:8080",
  18070. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  18071. // Edge case: Port 443 with is_ssl=false (should add port)
  18072. EXPECT_EQ("example.com:443",
  18073. detail::make_host_and_port_string("example.com", 443, false));
  18074. // Edge case: Port 80 with is_ssl=true (should add port)
  18075. EXPECT_EQ("example.com:80",
  18076. detail::make_host_and_port_string("example.com", 80, true));
  18077. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  18078. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  18079. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  18080. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  18081. // Security fix: Already bracketed IPv6 should not get double brackets
  18082. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  18083. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  18084. EXPECT_EQ("[::1]:8080",
  18085. detail::make_host_and_port_string("[::1]", 8080, false));
  18086. EXPECT_EQ("[2001:db8::1]:8080",
  18087. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  18088. EXPECT_EQ("[fe80::1%eth0]",
  18089. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  18090. EXPECT_EQ("[fe80::1%eth0]:8080",
  18091. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  18092. // Edge case: Empty host (should return as-is)
  18093. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  18094. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  18095. // This is a known limitation but shouldn't crash
  18096. EXPECT_EQ("[host:name]",
  18097. detail::make_host_and_port_string("host:name", 80, false));
  18098. // Port number edge cases (no validation, but should not crash)
  18099. EXPECT_EQ("example.com:0",
  18100. detail::make_host_and_port_string("example.com", 0, false));
  18101. EXPECT_EQ("example.com:-1",
  18102. detail::make_host_and_port_string("example.com", -1, false));
  18103. EXPECT_EQ("example.com:65535",
  18104. detail::make_host_and_port_string("example.com", 65535, false));
  18105. EXPECT_EQ("example.com:65536",
  18106. detail::make_host_and_port_string("example.com", 65536, false));
  18107. }
  18108. #ifdef CPPHTTPLIB_SSL_ENABLED
  18109. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  18110. httplib::SSLClient cli("roblox.com", 443);
  18111. cli.set_follow_location(true);
  18112. auto res = cli.Get("/");
  18113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18114. EXPECT_EQ(StatusCode::OK_200, res->status);
  18115. }
  18116. #endif
  18117. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  18118. Server svr;
  18119. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  18120. EXPECT_EQ(res.status, 400);
  18121. });
  18122. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18123. auto se = detail::scope_exit([&] {
  18124. svr.stop();
  18125. thread.join();
  18126. ASSERT_FALSE(svr.is_running());
  18127. });
  18128. svr.wait_until_ready();
  18129. Client cli(HOST, PORT);
  18130. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  18131. }
  18132. TEST(InvalidHeaderCharsTest, is_field_name) {
  18133. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  18134. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  18135. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  18136. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  18137. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  18138. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  18139. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  18140. EXPECT_FALSE(detail::fields::is_field_name(""));
  18141. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  18142. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  18143. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  18144. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  18145. }
  18146. TEST(InvalidHeaderCharsTest, is_field_value) {
  18147. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  18148. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  18149. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  18150. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  18151. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  18152. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  18153. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  18154. EXPECT_TRUE(detail::fields::is_field_value(""));
  18155. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  18156. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  18157. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  18158. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  18159. EXPECT_TRUE(detail::fields::is_field_value("0"));
  18160. }
  18161. TEST(InvalidHeaderCharsTest, OnServer) {
  18162. Server svr;
  18163. svr.Get("/test_name", [&](const Request &req, Response &res) {
  18164. std::string header = "Not Set";
  18165. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18166. res.set_header(header, "value");
  18167. res.set_content("Page Content Page Content", "text/plain");
  18168. });
  18169. svr.Get("/test_value", [&](const Request &req, Response &res) {
  18170. std::string header = "Not Set";
  18171. if (req.has_param("header")) { header = req.get_param_value("header"); }
  18172. res.set_header("X-Test", header);
  18173. res.set_content("Page Content Page Content", "text/plain");
  18174. });
  18175. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18176. auto se = detail::scope_exit([&] {
  18177. svr.stop();
  18178. thread.join();
  18179. ASSERT_FALSE(svr.is_running());
  18180. });
  18181. svr.wait_until_ready();
  18182. Client cli(HOST, PORT);
  18183. {
  18184. auto res = cli.Get(
  18185. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18187. EXPECT_EQ("Page Content Page Content", res->body);
  18188. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18189. }
  18190. {
  18191. auto res = cli.Get(
  18192. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  18193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18194. EXPECT_EQ("Page Content Page Content", res->body);
  18195. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  18196. }
  18197. }
  18198. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  18199. auto handled = false;
  18200. Server svr;
  18201. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18202. thread t = thread([&] { svr.listen(HOST, PORT); });
  18203. auto se = detail::scope_exit([&] {
  18204. svr.stop();
  18205. t.join();
  18206. ASSERT_FALSE(svr.is_running());
  18207. ASSERT_FALSE(handled);
  18208. });
  18209. svr.wait_until_ready();
  18210. auto req = "POST /test HTTP/1.1\r\n"
  18211. "Content-Length: x\r\n"
  18212. "\r\n";
  18213. std::string response;
  18214. ASSERT_TRUE(send_request(1, req, &response));
  18215. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18216. response.substr(0, response.find("\r\n")));
  18217. }
  18218. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  18219. // case-insensitive, and a server that receives a 100-continue expectation in
  18220. // an HTTP/1.0 request MUST ignore it.
  18221. static void probe_expect(int port, const std::string &req, bool *got_100) {
  18222. std::string response;
  18223. ASSERT_TRUE(send_request(1, req, &response, port));
  18224. *got_100 = response.find("100 Continue") != std::string::npos;
  18225. }
  18226. class ExpectTokenTest : public ::testing::Test {
  18227. protected:
  18228. void SetUp() override {
  18229. svr_.Post("/p", [](const Request &, Response &res) {
  18230. res.set_content("ok", "text/plain");
  18231. });
  18232. port_ = svr_.bind_to_any_port(HOST);
  18233. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18234. svr_.wait_until_ready();
  18235. }
  18236. void TearDown() override {
  18237. svr_.stop();
  18238. if (thread_.joinable()) { thread_.join(); }
  18239. }
  18240. std::string request(const char *version, const char *expect_value) const {
  18241. return std::string("POST /p ") + version +
  18242. "\r\n"
  18243. "Host: localhost\r\n"
  18244. "Content-Length: 2\r\n"
  18245. "Connection: close\r\n"
  18246. "Expect: " +
  18247. expect_value +
  18248. "\r\n"
  18249. "\r\n"
  18250. "hi";
  18251. }
  18252. Server svr_;
  18253. int port_ = 0;
  18254. thread thread_;
  18255. };
  18256. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18257. bool got_100 = false;
  18258. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18259. EXPECT_TRUE(got_100);
  18260. }
  18261. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18262. bool got_100 = true;
  18263. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18264. EXPECT_FALSE(got_100);
  18265. }
  18266. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18267. bool got_100 = false;
  18268. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18269. EXPECT_TRUE(got_100);
  18270. }
  18271. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18272. bool got_100 = false;
  18273. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18274. EXPECT_TRUE(got_100);
  18275. }
  18276. // `100 Continue` is sent only when the server starts reading the body, so a
  18277. // request rejected before that never invites the client to send it. The
  18278. // requests below carry the expectation but withhold the body, as a client
  18279. // waiting for `100 Continue` would.
  18280. // A POST that expects `100 Continue` and withholds its two-byte body.
  18281. static std::string expect_headers_only(const std::string &path) {
  18282. return "POST " + path +
  18283. " HTTP/1.1\r\n"
  18284. "Host: localhost\r\n"
  18285. "Content-Length: 2\r\n"
  18286. "Expect: 100-continue\r\n"
  18287. "\r\n";
  18288. }
  18289. class ExpectLazyContinueTest : public ::testing::Test {
  18290. protected:
  18291. void SetUp() override {
  18292. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18293. if (req.path == "/pre-routing") {
  18294. res.status = StatusCode::Unauthorized_401;
  18295. return Server::HandlerResponse::Handled;
  18296. }
  18297. return Server::HandlerResponse::Unhandled;
  18298. });
  18299. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18300. if (req.matched_route == "/pre-request") {
  18301. res.status = StatusCode::Forbidden_403;
  18302. return Server::HandlerResponse::Handled;
  18303. }
  18304. return Server::HandlerResponse::Unhandled;
  18305. });
  18306. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18307. res.set_content("ok", "text/plain");
  18308. });
  18309. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18310. res.set_content("ok", "text/plain");
  18311. });
  18312. svr_.Post("/reader-used", [](const Request &, Response &res,
  18313. const ContentReader &content_reader) {
  18314. std::string body;
  18315. content_reader([&](const char *data, size_t len) {
  18316. body.append(data, len);
  18317. return true;
  18318. });
  18319. res.set_content(body, "text/plain");
  18320. });
  18321. svr_.Post("/reader-unused",
  18322. [](const Request &, Response &res, const ContentReader &) {
  18323. res.set_content("ignored", "text/plain");
  18324. });
  18325. port_ = svr_.bind_to_any_port(HOST);
  18326. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18327. svr_.wait_until_ready();
  18328. }
  18329. void TearDown() override {
  18330. svr_.stop();
  18331. if (thread_.joinable()) { thread_.join(); }
  18332. }
  18333. // Sends `req` and reads until the server closes the connection. Returns
  18334. // false if the read had to wait for the client-side timeout instead.
  18335. bool send_until_closed(const std::string &req, std::string *resp) const {
  18336. auto start = std::chrono::steady_clock::now();
  18337. if (!send_request(3, req, resp, port_)) { return false; }
  18338. auto elapsed = std::chrono::steady_clock::now() - start;
  18339. return elapsed < std::chrono::seconds(2);
  18340. }
  18341. // The final response comes without `100 Continue`, and the server closes
  18342. // the connection since the body may or may not follow.
  18343. void expect_final_without_interim(const std::string &path,
  18344. const char *status_line) const {
  18345. std::string resp;
  18346. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18347. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18348. EXPECT_EQ(0u, resp.find(status_line));
  18349. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18350. }
  18351. Server svr_;
  18352. int port_ = 0;
  18353. thread thread_;
  18354. };
  18355. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18356. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18357. }
  18358. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18359. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18360. }
  18361. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18362. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18363. }
  18364. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18365. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18366. }
  18367. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18368. // The body follows once `100 Continue` has had time to arrive.
  18369. auto req = expect_headers_only("/reader-used");
  18370. req.insert(req.size() - 2, "Connection: close\r\n");
  18371. std::string resp;
  18372. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18373. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18374. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18375. EXPECT_NE(std::string::npos, resp.find("hi"));
  18376. }
  18377. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18378. // Large enough for the client to add `Expect: 100-continue` itself.
  18379. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18380. std::atomic<bool> body_sent{false};
  18381. Client cli(HOST, port_);
  18382. auto res = cli.Post(
  18383. "/pre-request", length,
  18384. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18385. body_sent = true;
  18386. std::string chunk(len, 'x');
  18387. sink.write(chunk.data(), chunk.size());
  18388. return true;
  18389. },
  18390. "application/octet-stream");
  18391. ASSERT_TRUE(res);
  18392. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18393. EXPECT_FALSE(body_sent);
  18394. }
  18395. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18396. Server svr;
  18397. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18398. return StatusCode::ExpectationFailed_417;
  18399. });
  18400. svr.Post("/p", [](const Request &, Response &res) {
  18401. res.set_content("ok", "text/plain");
  18402. });
  18403. auto port = svr.bind_to_any_port(HOST);
  18404. thread t = thread([&] { svr.listen_after_bind(); });
  18405. auto se = detail::scope_exit([&] {
  18406. svr.stop();
  18407. t.join();
  18408. });
  18409. svr.wait_until_ready();
  18410. std::string resp;
  18411. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18412. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18413. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18414. // Exactly one response: the route handler must not run after the 417.
  18415. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18416. }
  18417. #ifndef _WIN32
  18418. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18419. static constexpr char reject[] = "Unauthorized";
  18420. static constexpr char accept[] = "Upload accepted";
  18421. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18422. Server svr;
  18423. svr.set_expect_100_continue_handler(
  18424. [](const Request & /*req*/, Response &res) {
  18425. res.status = StatusCode::Unauthorized_401;
  18426. res.set_content(reject, "text/plain");
  18427. return res.status;
  18428. });
  18429. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18430. res.set_content(accept, "text/plain");
  18431. });
  18432. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18433. auto se = detail::scope_exit([&] {
  18434. svr.stop();
  18435. thread.join();
  18436. ASSERT_FALSE(svr.is_running());
  18437. });
  18438. svr.wait_until_ready();
  18439. {
  18440. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18441. curl_easy_init(), &curl_easy_cleanup};
  18442. ASSERT_NE(curl, nullptr);
  18443. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18444. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18445. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18446. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18447. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18448. &curl_slist_free_all};
  18449. ASSERT_NE(list, nullptr);
  18450. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18451. struct read_data {
  18452. uint64_t read_size;
  18453. uint64_t total_size;
  18454. } data = {0, total_size};
  18455. using read_callback_t =
  18456. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18457. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18458. void *userdata) -> size_t {
  18459. read_data *d = (read_data *)userdata;
  18460. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18461. std::fill_n(ptr, size * nmemb, 'A');
  18462. d->read_size += size * nmemb;
  18463. return size * nmemb;
  18464. };
  18465. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18466. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18467. std::vector<char> buffer;
  18468. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18469. using write_callback_t =
  18470. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18471. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18472. void *userdata) -> size_t {
  18473. std::vector<char> *buf = (std::vector<char> *)userdata;
  18474. buf->reserve(buf->size() + size * nmemb + 1);
  18475. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18476. return size * nmemb;
  18477. };
  18478. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18479. {
  18480. const auto res = curl_easy_perform(curl.get());
  18481. ASSERT_EQ(res, CURLE_OK);
  18482. }
  18483. {
  18484. auto response_code = long{};
  18485. const auto res =
  18486. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18487. ASSERT_EQ(res, CURLE_OK);
  18488. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18489. }
  18490. {
  18491. auto dl = curl_off_t{};
  18492. const auto res =
  18493. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18494. ASSERT_EQ(res, CURLE_OK);
  18495. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18496. }
  18497. {
  18498. buffer.push_back('\0');
  18499. ASSERT_STRCASEEQ(buffer.data(), reject);
  18500. }
  18501. }
  18502. }
  18503. #endif
  18504. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18505. // Regression test for #2458.
  18506. //
  18507. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18508. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18509. // ticket can make the client socket spuriously readable during the
  18510. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18511. // the client withholds the body and then blocks reading a response that never
  18512. // comes, failing with `Failed to read connection`.
  18513. //
  18514. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18515. // within the timeout. This raw OpenSSL server deliberately never sends
  18516. // `100 Continue`; the client must still deliver the body and receive 200.
  18517. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18518. signal(SIGPIPE, SIG_IGN);
  18519. const auto port = PORT + 4;
  18520. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18521. ASSERT_NE(srv, INVALID_SOCKET);
  18522. int opt = 1;
  18523. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18524. sockaddr_in addr{};
  18525. addr.sin_family = AF_INET;
  18526. addr.sin_port = htons(static_cast<uint16_t>(port));
  18527. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18528. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18529. ASSERT_EQ(0, ::listen(srv, 1));
  18530. std::atomic<size_t> server_body_bytes{0};
  18531. auto server_thread = std::thread([&] {
  18532. sockaddr_in cli_addr{};
  18533. socklen_t cli_len = sizeof(cli_addr);
  18534. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18535. if (cli == INVALID_SOCKET) { return; }
  18536. // Bound the lifetime of the server side so a buggy client (which never
  18537. // sends the body) cannot make this thread block forever on join.
  18538. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18539. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18540. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18541. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18542. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18543. SSL *ssl = SSL_new(ctx);
  18544. SSL_set_fd(ssl, static_cast<int>(cli));
  18545. if (SSL_accept(ssl) > 0) {
  18546. // Read the request headers. Reading here also flushes the TLS 1.3
  18547. // session tickets to the client. Deliberately do NOT send
  18548. // `100 Continue`.
  18549. std::string buf;
  18550. char tmp[1024];
  18551. while (buf.find("\r\n\r\n") == std::string::npos) {
  18552. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18553. if (n <= 0) { break; }
  18554. buf.append(tmp, static_cast<size_t>(n));
  18555. }
  18556. // A correct client sends the body now; count what arrives.
  18557. auto pos = buf.find("\r\n\r\n");
  18558. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18559. while (body < 4096) {
  18560. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18561. if (n <= 0) { break; }
  18562. body += static_cast<size_t>(n);
  18563. }
  18564. server_body_bytes = body;
  18565. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18566. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18567. SSL_shutdown(ssl);
  18568. }
  18569. SSL_free(ssl);
  18570. detail::close_socket(cli);
  18571. SSL_CTX_free(ctx);
  18572. });
  18573. auto se = detail::scope_exit([&] {
  18574. server_thread.join();
  18575. detail::close_socket(srv);
  18576. });
  18577. SSLClient cli("127.0.0.1", port);
  18578. cli.enable_server_certificate_verification(false);
  18579. cli.set_connection_timeout(5, 0);
  18580. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18581. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18582. std::string body(4096, 'A');
  18583. auto res = cli.Put("/api/test", body, "application/json");
  18584. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18585. EXPECT_EQ(StatusCode::OK_200, res->status);
  18586. EXPECT_EQ(body.size(), server_body_bytes.load());
  18587. }
  18588. #endif
  18589. template <typename S, typename C>
  18590. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18591. svr.Get("/stream", [&](const Request &, Response &res) {
  18592. auto data = new std::string("01234567890123456789");
  18593. res.set_content_provider(
  18594. data->size(), "text/plain",
  18595. [&, data](size_t offset, size_t length, DataSink &sink) {
  18596. const size_t DATA_CHUNK_SIZE = 4;
  18597. const auto &d = *data;
  18598. std::this_thread::sleep_for(std::chrono::seconds(1));
  18599. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18600. return true;
  18601. },
  18602. [data](bool success) {
  18603. EXPECT_FALSE(success);
  18604. delete data;
  18605. });
  18606. });
  18607. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18608. auto i = new size_t(0);
  18609. res.set_content_provider(
  18610. "text/plain",
  18611. [i](size_t, DataSink &sink) {
  18612. if (*i < 5) {
  18613. std::this_thread::sleep_for(std::chrono::seconds(1));
  18614. sink.write("abcd", 4);
  18615. (*i)++;
  18616. } else {
  18617. sink.done();
  18618. }
  18619. return true;
  18620. },
  18621. [i](bool success) {
  18622. EXPECT_FALSE(success);
  18623. delete i;
  18624. });
  18625. });
  18626. svr.Get("/chunked", [&](const Request &, Response &res) {
  18627. auto i = new size_t(0);
  18628. res.set_chunked_content_provider(
  18629. "text/plain",
  18630. [i](size_t, DataSink &sink) {
  18631. if (*i < 5) {
  18632. std::this_thread::sleep_for(std::chrono::seconds(1));
  18633. sink.os << "abcd";
  18634. (*i)++;
  18635. } else {
  18636. sink.done();
  18637. }
  18638. return true;
  18639. },
  18640. [i](bool success) {
  18641. EXPECT_FALSE(success);
  18642. delete i;
  18643. });
  18644. });
  18645. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18646. auto se = detail::scope_exit([&] {
  18647. svr.stop();
  18648. listen_thread.join();
  18649. ASSERT_FALSE(svr.is_running());
  18650. });
  18651. svr.wait_until_ready();
  18652. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18653. {
  18654. auto start = std::chrono::steady_clock::now();
  18655. auto res = cli.Get("/stream");
  18656. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18657. std::chrono::steady_clock::now() - start)
  18658. .count();
  18659. ASSERT_FALSE(res);
  18660. EXPECT_EQ(Error::Read, res.error());
  18661. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18662. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18663. }
  18664. {
  18665. auto start = std::chrono::steady_clock::now();
  18666. auto res = cli.Get("/stream_without_length");
  18667. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18668. std::chrono::steady_clock::now() - start)
  18669. .count();
  18670. ASSERT_FALSE(res);
  18671. EXPECT_EQ(Error::Read, res.error());
  18672. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18673. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18674. }
  18675. {
  18676. auto start = std::chrono::steady_clock::now();
  18677. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18678. EXPECT_EQ("abcd", string(data, data_length));
  18679. return true;
  18680. });
  18681. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18682. std::chrono::steady_clock::now() - start)
  18683. .count();
  18684. ASSERT_FALSE(res);
  18685. EXPECT_EQ(Error::Read, res.error());
  18686. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18687. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18688. }
  18689. }
  18690. TEST(MaxTimeoutTest, ContentStream) {
  18691. time_t timeout = 2000;
  18692. time_t threshold = 200;
  18693. Server svr;
  18694. Client cli("localhost", PORT);
  18695. max_timeout_test(svr, cli, timeout, threshold);
  18696. }
  18697. #ifdef CPPHTTPLIB_SSL_ENABLED
  18698. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18699. time_t timeout = 2000;
  18700. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18702. SSLClient cli("localhost", PORT);
  18703. cli.enable_server_certificate_verification(false);
  18704. max_timeout_test(svr, cli, timeout, threshold);
  18705. }
  18706. #endif
  18707. class EventDispatcher {
  18708. public:
  18709. EventDispatcher() {}
  18710. bool wait_event(DataSink *sink) {
  18711. unique_lock<mutex> lk(m_);
  18712. int id = id_;
  18713. // Wait with timeout to prevent hanging if client disconnects
  18714. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18715. [&] { return cid_ == id; })) {
  18716. return false; // Timeout occurred
  18717. }
  18718. sink->write(message_.data(), message_.size());
  18719. return true;
  18720. }
  18721. void send_event(const string &message) {
  18722. lock_guard<mutex> lk(m_);
  18723. cid_ = id_++;
  18724. message_ = message;
  18725. cv_.notify_all();
  18726. }
  18727. private:
  18728. mutex m_;
  18729. condition_variable cv_;
  18730. atomic_int id_{0};
  18731. atomic_int cid_{-1};
  18732. string message_;
  18733. };
  18734. TEST(ClientInThreadTest, Issue2068) {
  18735. EventDispatcher ed;
  18736. Server svr;
  18737. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18738. res.set_chunked_content_provider("text/event-stream",
  18739. [&](size_t /*offset*/, DataSink &sink) {
  18740. return ed.wait_event(&sink);
  18741. });
  18742. });
  18743. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18744. svr.wait_until_ready();
  18745. thread event_thread([&] {
  18746. int id = 0;
  18747. while (svr.is_running()) {
  18748. this_thread::sleep_for(chrono::milliseconds(500));
  18749. std::stringstream ss;
  18750. ss << "data: " << id << "\n\n";
  18751. ed.send_event(ss.str());
  18752. id++;
  18753. }
  18754. });
  18755. auto se = detail::scope_exit([&] {
  18756. svr.stop();
  18757. listen_thread.join();
  18758. event_thread.join();
  18759. ASSERT_FALSE(svr.is_running());
  18760. });
  18761. {
  18762. auto client = detail::make_unique<Client>(HOST, PORT);
  18763. client->set_read_timeout(std::chrono::minutes(10));
  18764. std::atomic<bool> stop{false};
  18765. std::thread t([&] {
  18766. client->Get("/event1",
  18767. [&](const char *, size_t) -> bool { return !stop; });
  18768. });
  18769. std::this_thread::sleep_for(std::chrono::seconds(2));
  18770. stop = true;
  18771. client->stop();
  18772. t.join();
  18773. // Reset client after thread has finished
  18774. client.reset();
  18775. }
  18776. }
  18777. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18778. auto handled = false;
  18779. Server svr;
  18780. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18781. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18782. auto se = detail::scope_exit([&] {
  18783. svr.stop();
  18784. t.join();
  18785. ASSERT_FALSE(svr.is_running());
  18786. ASSERT_FALSE(handled);
  18787. });
  18788. svr.wait_until_ready();
  18789. // Two Content-Length headers with different values — must be rejected
  18790. auto req = "POST /test HTTP/1.1\r\n"
  18791. "Content-Length: 5\r\n"
  18792. "Content-Length: 10\r\n"
  18793. "\r\n"
  18794. "hello";
  18795. std::string response;
  18796. ASSERT_TRUE(send_request(1, req, &response));
  18797. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18798. response.substr(0, response.find("\r\n")));
  18799. }
  18800. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18801. auto handled = false;
  18802. Server svr;
  18803. svr.Post("/test", [&](const Request &, Response &res) {
  18804. handled = true;
  18805. res.set_content("ok", "text/plain");
  18806. });
  18807. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18808. auto se = detail::scope_exit([&] {
  18809. svr.stop();
  18810. t.join();
  18811. ASSERT_FALSE(svr.is_running());
  18812. ASSERT_TRUE(handled);
  18813. });
  18814. svr.wait_until_ready();
  18815. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18816. auto req = "POST /test HTTP/1.1\r\n"
  18817. "Host: localhost\r\n"
  18818. "Content-Length: 5\r\n"
  18819. "Content-Length: 5\r\n"
  18820. "\r\n"
  18821. "hello";
  18822. std::string response;
  18823. ASSERT_TRUE(send_request(1, req, &response));
  18824. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18825. }
  18826. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18827. Server svr;
  18828. svr.Get("/test", [](const Request &, Response &res) {
  18829. res.set_content("ok", "text/plain");
  18830. });
  18831. auto port = svr.bind_to_any_port(HOST);
  18832. thread t = thread([&] { svr.listen_after_bind(); });
  18833. auto se = detail::scope_exit([&] {
  18834. svr.stop();
  18835. t.join();
  18836. ASSERT_FALSE(svr.is_running());
  18837. });
  18838. svr.wait_until_ready();
  18839. auto status_line = [&](const std::string &host_lines) {
  18840. std::string res;
  18841. send_request(
  18842. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18843. &res, port);
  18844. return res.substr(0, res.find("\r\n"));
  18845. };
  18846. const char *accepted[] = {
  18847. "Host: localhost\r\n",
  18848. "Host: a.example:8080\r\n",
  18849. "Host: my_service\r\n",
  18850. "Host: [::1]:8080\r\n",
  18851. "Host: [fe80::1%25eth0]\r\n",
  18852. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18853. };
  18854. for (auto host_lines : accepted) {
  18855. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18856. }
  18857. const char *rejected[] = {
  18858. "Host: a.example\r\nHost: b.example\r\n",
  18859. "Host: a.example\r\nHost: a.example\r\n",
  18860. "Host: a@b.example\r\n",
  18861. "Host: a.example/b\r\n",
  18862. "Host: a.example\\b\r\n",
  18863. "Host: a.example?b\r\n",
  18864. "Host: a.example#b\r\n",
  18865. "Host: a.example b.example\r\n",
  18866. };
  18867. for (auto host_lines : rejected) {
  18868. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18869. << host_lines;
  18870. }
  18871. }
  18872. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18873. Server svr;
  18874. svr.Get("/", [](const Request &req, Response &res) {
  18875. EXPECT_EQ(2U, req.trailers.size());
  18876. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18877. // Denied
  18878. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18879. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18880. // Accepted
  18881. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18882. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18883. EXPECT_TRUE(req.has_trailer("X-World"));
  18884. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18885. res.set_content("ok", "text/plain");
  18886. });
  18887. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18888. auto se = detail::scope_exit([&] {
  18889. svr.stop();
  18890. t.join();
  18891. ASSERT_FALSE(svr.is_running());
  18892. });
  18893. svr.wait_until_ready();
  18894. const std::string req = "GET / HTTP/1.1\r\n"
  18895. "Transfer-Encoding: chunked\r\n"
  18896. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18897. "\r\n"
  18898. "0\r\n"
  18899. "Content-Length: 10\r\n"
  18900. "Host: internal.local\r\n"
  18901. "Content-Type: malicious/content\r\n"
  18902. "Cookie: any\r\n"
  18903. "Set-Cookie: any\r\n"
  18904. "X-Forwarded-For: attacker.com\r\n"
  18905. "X-Real-Ip: 1.1.1.1\r\n"
  18906. "X-Hello: hello\r\n"
  18907. "X-World: world\r\n"
  18908. "\r\n";
  18909. std::string res;
  18910. ASSERT_TRUE(send_request(1, req, &res));
  18911. }
  18912. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18913. // several field lines, and the combined value is what has to be parsed. A
  18914. // Trailer field split across lines therefore declares every name it lists;
  18915. // reading only the first line silently drops the trailers the later lines
  18916. // declare. The prohibited-trailer filter still applies to every line.
  18917. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18918. Server svr;
  18919. size_t observed_trailer_count = 0;
  18920. std::string observed_hello;
  18921. std::string observed_world;
  18922. bool observed_content_length = true;
  18923. svr.Get("/", [&](const Request &req, Response &res) {
  18924. observed_trailer_count = req.trailers.size();
  18925. observed_hello = req.get_trailer_value("X-Hello");
  18926. observed_world = req.get_trailer_value("X-World");
  18927. observed_content_length = req.has_trailer("Content-Length");
  18928. res.set_content("ok", "text/plain");
  18929. });
  18930. auto port = svr.bind_to_any_port(HOST);
  18931. thread t = thread([&]() { svr.listen_after_bind(); });
  18932. auto se = detail::scope_exit([&] {
  18933. svr.stop();
  18934. t.join();
  18935. ASSERT_FALSE(svr.is_running());
  18936. });
  18937. svr.wait_until_ready();
  18938. const std::string req = "GET / HTTP/1.1\r\n"
  18939. "Host: localhost\r\n"
  18940. "Transfer-Encoding: chunked\r\n"
  18941. "Trailer: X-Hello\r\n"
  18942. "Trailer: X-World, Content-Length\r\n"
  18943. "\r\n"
  18944. "0\r\n"
  18945. "X-Hello: hello\r\n"
  18946. "X-World: world\r\n"
  18947. "Content-Length: 10\r\n"
  18948. "\r\n";
  18949. std::string res;
  18950. ASSERT_TRUE(send_request(1, req, &res, port));
  18951. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18952. // Accepted: both field lines contribute to the declared set
  18953. EXPECT_EQ(2U, observed_trailer_count);
  18954. EXPECT_EQ(observed_hello, "hello");
  18955. EXPECT_EQ(observed_world, "world");
  18956. // Denied: a prohibited name stays prohibited on a later field line
  18957. EXPECT_FALSE(observed_content_length);
  18958. }
  18959. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18960. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18961. // unbounded run of fields that are never declared, because the counter would
  18962. // only advance for declared fields.
  18963. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18964. Server svr;
  18965. bool handler_called = false;
  18966. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18967. handler_called = true;
  18968. res.set_content("ok", "text/plain");
  18969. });
  18970. auto port = svr.bind_to_any_port(HOST);
  18971. thread t = thread([&]() { svr.listen_after_bind(); });
  18972. auto se = detail::scope_exit([&] {
  18973. svr.stop();
  18974. t.join();
  18975. ASSERT_FALSE(svr.is_running());
  18976. });
  18977. svr.wait_until_ready();
  18978. // Declare nothing, then send far more undeclared trailer fields than the
  18979. // header-count limit. Parsing must stop and reject the request rather than
  18980. // read every line.
  18981. std::string req = "GET / HTTP/1.1\r\n"
  18982. "Transfer-Encoding: chunked\r\n"
  18983. "\r\n"
  18984. "0\r\n";
  18985. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18986. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18987. }
  18988. req += "\r\n";
  18989. std::string res;
  18990. ASSERT_TRUE(send_request(1, req, &res, port));
  18991. // The request is rejected before the handler runs.
  18992. EXPECT_FALSE(handler_called);
  18993. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18994. }
  18995. // The set of declared trailer names is capped so a peer cannot grow it without
  18996. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18997. // declared past the cap is not honored, even if the field is actually sent.
  18998. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18999. Server svr;
  19000. // One name inside the cap and one past it, so the test tracks the cap rather
  19001. // than a fixed count.
  19002. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19003. const std::string within_cap_name = "X-T-0";
  19004. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19005. bool observed_within_cap = false;
  19006. bool observed_past_cap = false;
  19007. svr.Get("/", [&](const Request &req, Response &res) {
  19008. observed_within_cap = req.has_trailer(within_cap_name);
  19009. observed_past_cap = req.has_trailer(past_cap_name);
  19010. res.set_content("ok", "text/plain");
  19011. });
  19012. auto port = svr.bind_to_any_port(HOST);
  19013. thread t = thread([&]() { svr.listen_after_bind(); });
  19014. auto se = detail::scope_exit([&] {
  19015. svr.stop();
  19016. t.join();
  19017. ASSERT_FALSE(svr.is_running());
  19018. });
  19019. svr.wait_until_ready();
  19020. // Declare more trailer names than the cap in a single Trailer field, then
  19021. // actually send the first (within the cap) and the last (past it).
  19022. std::string trailer_decl = "Trailer: ";
  19023. for (int i = 0; i < declared_count; i++) {
  19024. if (i != 0) { trailer_decl += ", "; }
  19025. trailer_decl += "X-T-" + std::to_string(i);
  19026. }
  19027. trailer_decl += "\r\n";
  19028. const std::string req = "GET / HTTP/1.1\r\n"
  19029. "Host: localhost\r\n"
  19030. "Transfer-Encoding: chunked\r\n" +
  19031. trailer_decl +
  19032. "\r\n"
  19033. "0\r\n" +
  19034. within_cap_name + ": a\r\n" + past_cap_name +
  19035. ": b\r\n"
  19036. "\r\n";
  19037. std::string res;
  19038. ASSERT_TRUE(send_request(1, req, &res, port));
  19039. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  19040. // A name within the cap is honored; one declared past the cap is dropped.
  19041. EXPECT_TRUE(observed_within_cap);
  19042. EXPECT_FALSE(observed_past_cap);
  19043. }
  19044. // A direct client that is not listed in trusted_proxies must not be able to
  19045. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  19046. // the peer address on the actual TCP connection determines whether the
  19047. // header is honored.
  19048. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  19049. Server svr;
  19050. // Deliberately does NOT include the loopback address the test client
  19051. // actually connects from, so the direct connection is not a trusted proxy.
  19052. svr.set_trusted_proxies({"203.0.113.66"});
  19053. std::string observed_remote_addr;
  19054. svr.Get("/ip", [&](const Request &req, Response &res) {
  19055. observed_remote_addr = req.remote_addr;
  19056. res.set_content("ok", "text/plain");
  19057. });
  19058. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19059. auto se = detail::scope_exit([&] {
  19060. svr.stop();
  19061. t.join();
  19062. ASSERT_FALSE(svr.is_running());
  19063. });
  19064. svr.wait_until_ready();
  19065. Client cli(HOST, PORT);
  19066. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  19067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19068. EXPECT_EQ(StatusCode::OK_200, res->status);
  19069. // The connecting peer is not a trusted proxy, so the spoofed header must be
  19070. // ignored entirely and the real connection-level address retained.
  19071. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19072. observed_remote_addr == "127.0.0.1");
  19073. }
  19074. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  19075. Server svr;
  19076. std::string observed_remote_addr;
  19077. std::string observed_xff;
  19078. svr.Get("/ip", [&](const Request &req, Response &res) {
  19079. observed_remote_addr = req.remote_addr;
  19080. observed_xff = req.get_header_value("X-Forwarded-For");
  19081. res.set_content("ok", "text/plain");
  19082. });
  19083. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19084. auto se = detail::scope_exit([&] {
  19085. svr.stop();
  19086. t.join();
  19087. ASSERT_FALSE(svr.is_running());
  19088. });
  19089. svr.wait_until_ready();
  19090. Client cli(HOST, PORT);
  19091. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  19092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19093. EXPECT_EQ(StatusCode::OK_200, res->status);
  19094. EXPECT_EQ(observed_xff, "203.0.113.66");
  19095. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19096. observed_remote_addr == "127.0.0.1");
  19097. }
  19098. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  19099. Server svr;
  19100. svr.set_trusted_proxies({"203.0.113.66"});
  19101. std::string observed_remote_addr;
  19102. std::string observed_xff;
  19103. svr.Get("/ip", [&](const Request &req, Response &res) {
  19104. observed_remote_addr = req.remote_addr;
  19105. observed_xff = req.get_header_value("X-Forwarded-For");
  19106. res.set_content("ok", "text/plain");
  19107. });
  19108. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19109. auto se = detail::scope_exit([&] {
  19110. svr.stop();
  19111. t.join();
  19112. ASSERT_FALSE(svr.is_running());
  19113. });
  19114. svr.wait_until_ready();
  19115. Client cli(HOST, PORT);
  19116. auto res = cli.Get("/ip");
  19117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19118. EXPECT_EQ(StatusCode::OK_200, res->status);
  19119. EXPECT_EQ(observed_xff, "");
  19120. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19121. observed_remote_addr == "127.0.0.1");
  19122. }
  19123. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  19124. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  19125. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  19126. Server svr;
  19127. svr.set_trusted_proxies({"127.0.0.1"});
  19128. svr.Get("/ip", [](const Request &req, Response &res) {
  19129. res.set_content(req.remote_addr, "text/plain");
  19130. });
  19131. auto port = svr.bind_to_any_port("::");
  19132. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  19133. thread t = thread([&] { svr.listen_after_bind(); });
  19134. auto se = detail::scope_exit([&] {
  19135. svr.stop();
  19136. t.join();
  19137. ASSERT_FALSE(svr.is_running());
  19138. });
  19139. svr.wait_until_ready();
  19140. Client cli("127.0.0.1", port);
  19141. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  19142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19143. EXPECT_EQ("198.51.100.23", res->body);
  19144. }
  19145. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  19146. Server svr;
  19147. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19148. svr.Get("/ip", [](const Request &req, Response &res) {
  19149. res.set_content(req.remote_addr, "text/plain");
  19150. });
  19151. auto port = svr.bind_to_any_port(HOST);
  19152. ASSERT_GT(port, 0);
  19153. thread t = thread([&] { svr.listen_after_bind(); });
  19154. auto se = detail::scope_exit([&] {
  19155. svr.stop();
  19156. t.join();
  19157. ASSERT_FALSE(svr.is_running());
  19158. });
  19159. svr.wait_until_ready();
  19160. Client cli(HOST, port);
  19161. auto res = cli.Get(
  19162. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  19163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19164. EXPECT_EQ("198.51.100.23", res->body);
  19165. }
  19166. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  19167. Server svr;
  19168. // Include the loopback address the test client actually connects from, so
  19169. // the direct connection itself is recognized as the trusted proxy hop.
  19170. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  19171. std::string observed_remote_addr;
  19172. std::string observed_xff;
  19173. svr.Get("/ip", [&](const Request &req, Response &res) {
  19174. observed_remote_addr = req.remote_addr;
  19175. observed_xff = req.get_header_value("X-Forwarded-For");
  19176. res.set_content("ok", "text/plain");
  19177. });
  19178. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19179. auto se = detail::scope_exit([&] {
  19180. svr.stop();
  19181. t.join();
  19182. ASSERT_FALSE(svr.is_running());
  19183. });
  19184. svr.wait_until_ready();
  19185. Client cli(HOST, PORT);
  19186. auto res = cli.Get(
  19187. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  19188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19189. EXPECT_EQ(StatusCode::OK_200, res->status);
  19190. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  19191. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19192. }
  19193. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  19194. Server svr;
  19195. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  19196. std::string observed_remote_addr;
  19197. std::string observed_xff;
  19198. svr.Get("/ip", [&](const Request &req, Response &res) {
  19199. observed_remote_addr = req.remote_addr;
  19200. observed_xff = req.get_header_value("X-Forwarded-For");
  19201. res.set_content("ok", "text/plain");
  19202. });
  19203. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19204. auto se = detail::scope_exit([&] {
  19205. svr.stop();
  19206. t.join();
  19207. ASSERT_FALSE(svr.is_running());
  19208. });
  19209. svr.wait_until_ready();
  19210. Client cli(HOST, PORT);
  19211. auto res = cli.Get(
  19212. "/ip",
  19213. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19215. EXPECT_EQ(StatusCode::OK_200, res->status);
  19216. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19217. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19218. }
  19219. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  19220. Server svr;
  19221. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19222. std::string observed_remote_addr;
  19223. std::string observed_xff;
  19224. svr.Get("/ip", [&](const Request &req, Response &res) {
  19225. observed_remote_addr = req.remote_addr;
  19226. observed_xff = req.get_header_value("X-Forwarded-For");
  19227. res.set_content("ok", "text/plain");
  19228. });
  19229. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19230. auto se = detail::scope_exit([&] {
  19231. svr.stop();
  19232. t.join();
  19233. ASSERT_FALSE(svr.is_running());
  19234. });
  19235. svr.wait_until_ready();
  19236. Client cli(HOST, PORT);
  19237. auto res = cli.Get(
  19238. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  19239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19240. EXPECT_EQ(StatusCode::OK_200, res->status);
  19241. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  19242. // by the closest hop) is used. The leftmost entry is fully client-controlled
  19243. // and must not be selected.
  19244. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  19245. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  19246. }
  19247. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  19248. Server svr;
  19249. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19250. std::string observed_remote_addr;
  19251. svr.Get("/ip", [&](const Request &req, Response &res) {
  19252. observed_remote_addr = req.remote_addr;
  19253. res.set_content("ok", "text/plain");
  19254. });
  19255. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19256. auto se = detail::scope_exit([&] {
  19257. svr.stop();
  19258. t.join();
  19259. ASSERT_FALSE(svr.is_running());
  19260. });
  19261. svr.wait_until_ready();
  19262. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19263. // a forged address and the trusted proxy's own address; the forged value must
  19264. // not win over the address the trusted proxy actually recorded.
  19265. Client cli(HOST, PORT);
  19266. auto res = cli.Get(
  19267. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19269. EXPECT_EQ(StatusCode::OK_200, res->status);
  19270. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19271. }
  19272. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19273. Server svr;
  19274. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19275. std::string observed_remote_addr;
  19276. std::string observed_xff;
  19277. svr.Get("/ip", [&](const Request &req, Response &res) {
  19278. observed_remote_addr = req.remote_addr;
  19279. observed_xff = req.get_header_value("X-Forwarded-For");
  19280. res.set_content("ok", "text/plain");
  19281. });
  19282. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19283. auto se = detail::scope_exit([&] {
  19284. svr.stop();
  19285. t.join();
  19286. ASSERT_FALSE(svr.is_running());
  19287. });
  19288. svr.wait_until_ready();
  19289. Client cli(HOST, PORT);
  19290. auto res = cli.Get(
  19291. "/ip",
  19292. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19294. EXPECT_EQ(StatusCode::OK_200, res->status);
  19295. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19296. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19297. }
  19298. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19299. Server svr;
  19300. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19301. std::string observed_remote_addr;
  19302. std::string observed_xff;
  19303. svr.Get("/ip", [&](const Request &req, Response &res) {
  19304. observed_remote_addr = req.remote_addr;
  19305. observed_xff = req.get_header_value("X-Forwarded-For");
  19306. res.set_content("ok", "text/plain");
  19307. });
  19308. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19309. auto se = detail::scope_exit([&] {
  19310. svr.stop();
  19311. t.join();
  19312. ASSERT_FALSE(svr.is_running());
  19313. });
  19314. svr.wait_until_ready();
  19315. std::string raw_req =
  19316. "GET /ip HTTP/1.1\r\n"
  19317. "Host: localhost\r\n"
  19318. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19319. "Connection: close\r\n"
  19320. "\r\n";
  19321. std::string out;
  19322. ASSERT_TRUE(send_request(5, raw_req, &out));
  19323. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19324. // Header parser trims surrounding whitespace of the header value
  19325. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19326. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19327. }
  19328. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19329. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19330. // their own X-Forwarded-For as a separate field line rather than extending the
  19331. // one the client sent, so every occurrence has to be taken into account.
  19332. // Reading only the first one hands back the address the client chose.
  19333. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19334. Server svr;
  19335. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19336. std::string observed_remote_addr;
  19337. size_t observed_xff_count = 0;
  19338. svr.Get("/ip", [&](const Request &req, Response &res) {
  19339. observed_remote_addr = req.remote_addr;
  19340. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19341. res.set_content("ok", "text/plain");
  19342. });
  19343. auto port = svr.bind_to_any_port(HOST);
  19344. thread t = thread([&]() { svr.listen_after_bind(); });
  19345. auto se = detail::scope_exit([&] {
  19346. svr.stop();
  19347. t.join();
  19348. ASSERT_FALSE(svr.is_running());
  19349. });
  19350. svr.wait_until_ready();
  19351. // The client supplies the first field line; the trusted proxy appends the
  19352. // address it observed as a second one.
  19353. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19354. "Host: localhost\r\n"
  19355. "X-Forwarded-For: 1.2.3.4\r\n"
  19356. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19357. "Connection: close\r\n"
  19358. "\r\n";
  19359. std::string out;
  19360. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19361. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19362. EXPECT_EQ(observed_xff_count, 2U);
  19363. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19364. // The same chain spread over one field line per hop derives the same client
  19365. // address, i.e. the split and the comma-joined representations agree.
  19366. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19367. "Host: localhost\r\n"
  19368. "X-Forwarded-For: 1.2.3.4\r\n"
  19369. "X-Forwarded-For: 198.51.100.23\r\n"
  19370. "X-Forwarded-For: 192.0.2.45\r\n"
  19371. "Connection: close\r\n"
  19372. "\r\n";
  19373. out.clear();
  19374. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19375. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19376. EXPECT_EQ(observed_xff_count, 3U);
  19377. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19378. }
  19379. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19380. // crash the server (it used to call front() on an empty vector inside
  19381. // get_client_ip). The connection-level remote address must be retained instead.
  19382. static void run_malformed_xff_test(const std::string &xff_value) {
  19383. Server svr;
  19384. svr.set_trusted_proxies({"192.0.2.45"});
  19385. std::string observed_remote_addr;
  19386. svr.Get("/ip", [&](const Request &req, Response &res) {
  19387. observed_remote_addr = req.remote_addr;
  19388. res.set_content("ok", "text/plain");
  19389. });
  19390. int port = 0;
  19391. thread t = thread([&]() {
  19392. port = svr.bind_to_any_port(HOST);
  19393. svr.listen_after_bind();
  19394. });
  19395. auto se = detail::scope_exit([&] {
  19396. svr.stop();
  19397. t.join();
  19398. ASSERT_FALSE(svr.is_running());
  19399. });
  19400. svr.wait_until_ready();
  19401. Client cli(HOST, port);
  19402. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19404. EXPECT_EQ(StatusCode::OK_200, res->status);
  19405. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19406. observed_remote_addr == "127.0.0.1");
  19407. }
  19408. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19409. run_malformed_xff_test("");
  19410. }
  19411. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19412. run_malformed_xff_test(",");
  19413. }
  19414. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19415. run_malformed_xff_test(", , ,");
  19416. }
  19417. // The same rule applies to Accept: a request whose acceptable types are spread
  19418. // over several field lines must be negotiated against all of them.
  19419. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19420. // case-insensitive connection options. Comparing the whole field value against
  19421. // one option misses a client that sends several of them, and misses every
  19422. // casing but the one written in the comparison.
  19423. //
  19424. // Sends req, reads the response, then reuses the same socket for a second
  19425. // request to find out whether the server kept the connection.
  19426. static void probe_connection_reuse(int port, const std::string &req,
  19427. bool *announced_close, bool *reusable) {
  19428. auto error = Error::Success;
  19429. auto sock = detail::create_client_socket(
  19430. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19431. /*connection_timeout_sec=*/5, 0,
  19432. /*read_timeout_sec=*/1, 0,
  19433. /*write_timeout_sec=*/5, 0, std::string(), error);
  19434. ASSERT_NE(sock, INVALID_SOCKET);
  19435. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19436. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19437. "Host: localhost\r\n"
  19438. "Connection: close\r\n"
  19439. "\r\n";
  19440. std::string first_response;
  19441. std::string second_response;
  19442. detail::process_client_socket(
  19443. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19444. [&](Stream &strm) {
  19445. if (strm.write(req.data(), req.size()) !=
  19446. static_cast<ssize_t>(req.size())) {
  19447. return false;
  19448. }
  19449. char buf[512];
  19450. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19451. // Headers plus the two-byte body of the handler below
  19452. while (reader.getline()) {
  19453. first_response += reader.ptr();
  19454. if (first_response.find("ok") != std::string::npos) { break; }
  19455. }
  19456. if (strm.write(second.data(), second.size()) !=
  19457. static_cast<ssize_t>(second.size())) {
  19458. return true;
  19459. }
  19460. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19461. while (reader2.getline()) {
  19462. second_response += reader2.ptr();
  19463. if (second_response.find("ok") != std::string::npos) { break; }
  19464. }
  19465. return true;
  19466. });
  19467. *announced_close =
  19468. first_response.find("Connection: close") != std::string::npos;
  19469. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19470. }
  19471. class ConnectionTokenTest : public ::testing::Test {
  19472. protected:
  19473. void SetUp() override {
  19474. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19475. res.set_content("ok", "text/plain");
  19476. });
  19477. port_ = svr_.bind_to_any_port(HOST);
  19478. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19479. svr_.wait_until_ready();
  19480. }
  19481. void TearDown() override {
  19482. svr_.stop();
  19483. if (thread_.joinable()) { thread_.join(); }
  19484. }
  19485. Server svr_;
  19486. int port_ = 0;
  19487. thread thread_;
  19488. };
  19489. // "close" alongside another option still closes the connection, and the
  19490. // response says so rather than leaving the peer to discover it.
  19491. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19492. bool announced_close = false;
  19493. bool reusable = true;
  19494. probe_connection_reuse(port_,
  19495. "GET /keepalive HTTP/1.1\r\n"
  19496. "Host: localhost\r\n"
  19497. "Connection: keep-alive, close\r\n"
  19498. "\r\n",
  19499. &announced_close, &reusable);
  19500. EXPECT_TRUE(announced_close);
  19501. EXPECT_FALSE(reusable);
  19502. }
  19503. // "close" split over two field lines is the same list, so it is honored too.
  19504. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19505. bool announced_close = false;
  19506. bool reusable = true;
  19507. probe_connection_reuse(port_,
  19508. "GET /keepalive HTTP/1.1\r\n"
  19509. "Host: localhost\r\n"
  19510. "Connection: keep-alive\r\n"
  19511. "Connection: close\r\n"
  19512. "\r\n",
  19513. &announced_close, &reusable);
  19514. EXPECT_TRUE(announced_close);
  19515. EXPECT_FALSE(reusable);
  19516. }
  19517. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19518. // keep-alive in the spelling everyone actually sends keeps its connection.
  19519. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19520. bool announced_close = false;
  19521. bool reusable = false;
  19522. probe_connection_reuse(port_,
  19523. "GET /keepalive HTTP/1.0\r\n"
  19524. "Host: localhost\r\n"
  19525. "Connection: keep-alive\r\n"
  19526. "\r\n",
  19527. &announced_close, &reusable);
  19528. EXPECT_FALSE(announced_close);
  19529. EXPECT_TRUE(reusable);
  19530. }
  19531. // A token the value merely contains is not the token itself.
  19532. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19533. bool announced_close = false;
  19534. bool reusable = false;
  19535. probe_connection_reuse(port_,
  19536. "GET /keepalive HTTP/1.1\r\n"
  19537. "Host: localhost\r\n"
  19538. "Connection: notclose\r\n"
  19539. "\r\n",
  19540. &announced_close, &reusable);
  19541. EXPECT_FALSE(announced_close);
  19542. EXPECT_TRUE(reusable);
  19543. }
  19544. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19545. Server svr;
  19546. std::vector<std::string> observed_types;
  19547. svr.Get("/", [&](const Request &req, Response &res) {
  19548. observed_types = req.accept_content_types;
  19549. res.set_content("ok", "text/plain");
  19550. });
  19551. auto port = svr.bind_to_any_port(HOST);
  19552. thread t = thread([&]() { svr.listen_after_bind(); });
  19553. auto se = detail::scope_exit([&] {
  19554. svr.stop();
  19555. t.join();
  19556. ASSERT_FALSE(svr.is_running());
  19557. });
  19558. svr.wait_until_ready();
  19559. Client cli(HOST, port);
  19560. Headers headers;
  19561. headers.emplace("Accept", "text/plain;q=0.5");
  19562. headers.emplace("Accept", "application/json");
  19563. auto res = cli.Get("/", headers);
  19564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19565. EXPECT_EQ(StatusCode::OK_200, res->status);
  19566. // Sorted by q-value, so the second field line's type comes first
  19567. ASSERT_EQ(2U, observed_types.size());
  19568. EXPECT_EQ("application/json", observed_types[0]);
  19569. EXPECT_EQ("text/plain", observed_types[1]);
  19570. }
  19571. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19572. // empty field line must not contribute a bare comma to the combined value.
  19573. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19574. Server svr;
  19575. std::vector<std::string> observed_types;
  19576. svr.Get("/", [&](const Request &req, Response &res) {
  19577. observed_types = req.accept_content_types;
  19578. res.set_content("ok", "text/plain");
  19579. });
  19580. auto port = svr.bind_to_any_port(HOST);
  19581. thread t = thread([&]() { svr.listen_after_bind(); });
  19582. auto se = detail::scope_exit([&] {
  19583. svr.stop();
  19584. t.join();
  19585. ASSERT_FALSE(svr.is_running());
  19586. });
  19587. svr.wait_until_ready();
  19588. // Empty first field line, then a real one
  19589. std::string raw_req = "GET / HTTP/1.1\r\n"
  19590. "Host: localhost\r\n"
  19591. "Accept:\r\n"
  19592. "Accept: application/json\r\n"
  19593. "Connection: close\r\n"
  19594. "\r\n";
  19595. std::string out;
  19596. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19597. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19598. ASSERT_EQ(1U, observed_types.size());
  19599. EXPECT_EQ("application/json", observed_types[0]);
  19600. }
  19601. // The skip in get_combined_header_value() is what keeps an empty field line
  19602. // from contributing a bare comma. Only a trailing empty field line exercises
  19603. // it: a leading one is already covered by the "combined is still empty" check,
  19604. // and parse_accept_header() now ignores the empty element either way, so the
  19605. // request-level test above can no longer tell the two apart.
  19606. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19607. Headers headers;
  19608. headers.emplace("Accept", "text/html");
  19609. headers.emplace("Accept", "");
  19610. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19611. headers.clear();
  19612. headers.emplace("Accept", "");
  19613. headers.emplace("Accept", "application/json");
  19614. EXPECT_EQ("application/json",
  19615. detail::get_combined_header_value(headers, "Accept"));
  19616. }
  19617. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19618. // An encoding offered on a later Accept-Encoding field line is still offered.
  19619. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19620. Server svr;
  19621. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19622. res.set_content(std::string(1024, 'x'), "text/plain");
  19623. });
  19624. auto port = svr.bind_to_any_port(HOST);
  19625. thread t = thread([&]() { svr.listen_after_bind(); });
  19626. auto se = detail::scope_exit([&] {
  19627. svr.stop();
  19628. t.join();
  19629. ASSERT_FALSE(svr.is_running());
  19630. });
  19631. svr.wait_until_ready();
  19632. Client cli(HOST, port);
  19633. cli.set_decompress(false);
  19634. Headers headers;
  19635. headers.emplace("Accept-Encoding", "identity");
  19636. headers.emplace("Accept-Encoding", "gzip");
  19637. auto res = cli.Get("/", headers);
  19638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19639. EXPECT_EQ(StatusCode::OK_200, res->status);
  19640. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19641. }
  19642. #endif
  19643. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19644. // Transfer-Encoding is not its body.
  19645. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19646. Server svr;
  19647. svr.set_payload_max_length(8);
  19648. svr.Post("/test", [](const Request &, Response &res) {
  19649. res.set_content("ok", "text/plain");
  19650. });
  19651. auto port = svr.bind_to_any_port(HOST);
  19652. ASSERT_GT(port, 0);
  19653. thread t = thread([&] { svr.listen_after_bind(); });
  19654. auto se = detail::scope_exit([&] {
  19655. svr.stop();
  19656. t.join();
  19657. ASSERT_FALSE(svr.is_running());
  19658. });
  19659. svr.wait_until_ready();
  19660. std::string resp;
  19661. ASSERT_TRUE(send_request(1,
  19662. "POST /test HTTP/1.1\r\n"
  19663. "Host: localhost\r\n"
  19664. "Connection: close\r\n"
  19665. "\r\n" +
  19666. std::string(16, 'X'),
  19667. &resp, port));
  19668. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19669. }
  19670. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19671. Server svr;
  19672. svr.Post("/post", [&](const Request &req, Response &res) {
  19673. res.set_content(req.body, "text/plain");
  19674. });
  19675. svr.Put("/put", [&](const Request &req, Response &res) {
  19676. res.set_content(req.body, "text/plain");
  19677. });
  19678. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19679. res.set_content(req.body, "text/plain");
  19680. });
  19681. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19682. res.set_content(req.body, "text/plain");
  19683. });
  19684. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19685. auto se = detail::scope_exit([&] {
  19686. svr.stop();
  19687. t.join();
  19688. ASSERT_FALSE(svr.is_running());
  19689. });
  19690. svr.wait_until_ready();
  19691. std::string resp;
  19692. // POST without Content-Length
  19693. ASSERT_TRUE(send_request(5,
  19694. "POST /post HTTP/1.1\r\n"
  19695. "Host: localhost\r\n"
  19696. "Connection: close\r\n"
  19697. "\r\n",
  19698. &resp));
  19699. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19700. // PUT without Content-Length
  19701. resp.clear();
  19702. ASSERT_TRUE(send_request(5,
  19703. "PUT /put HTTP/1.1\r\n"
  19704. "Host: localhost\r\n"
  19705. "Connection: close\r\n"
  19706. "\r\n",
  19707. &resp));
  19708. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19709. // PATCH without Content-Length
  19710. resp.clear();
  19711. ASSERT_TRUE(send_request(5,
  19712. "PATCH /patch HTTP/1.1\r\n"
  19713. "Host: localhost\r\n"
  19714. "Connection: close\r\n"
  19715. "\r\n",
  19716. &resp));
  19717. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19718. // DELETE without Content-Length
  19719. resp.clear();
  19720. ASSERT_TRUE(send_request(5,
  19721. "DELETE /delete HTTP/1.1\r\n"
  19722. "Host: localhost\r\n"
  19723. "Connection: close\r\n"
  19724. "\r\n",
  19725. &resp));
  19726. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19727. }
  19728. //==============================================================================
  19729. // open_stream() Tests
  19730. //==============================================================================
  19731. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19732. std::string result;
  19733. char buf[8192];
  19734. ssize_t n;
  19735. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19736. result.append(buf, static_cast<size_t>(n));
  19737. }
  19738. return result;
  19739. }
  19740. // Mock stream for unit tests
  19741. class MockStream : public Stream {
  19742. public:
  19743. std::string data;
  19744. size_t pos = 0;
  19745. ssize_t error_after = -1; // -1 = no error
  19746. explicit MockStream(const std::string &d, ssize_t err = -1)
  19747. : data(d), error_after(err) {}
  19748. bool is_readable() const override { return true; }
  19749. bool wait_readable() const override { return true; }
  19750. bool wait_writable() const override { return true; }
  19751. ssize_t read(char *ptr, size_t size) override {
  19752. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19753. if (pos >= data.size()) return 0;
  19754. size_t limit =
  19755. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19756. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19757. std::memcpy(ptr, data.data() + pos, to_read);
  19758. pos += to_read;
  19759. return static_cast<ssize_t>(to_read);
  19760. }
  19761. ssize_t write(const char *, size_t) override { return -1; }
  19762. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19763. ip = "127.0.0.1";
  19764. port = 0;
  19765. }
  19766. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19767. ip = "127.0.0.1";
  19768. port = 0;
  19769. }
  19770. socket_t socket() const override { return INVALID_SOCKET; }
  19771. time_t duration() const override { return 0; }
  19772. };
  19773. TEST(StreamHandleTest, Basic) {
  19774. ClientImpl::StreamHandle handle;
  19775. EXPECT_FALSE(handle.is_valid());
  19776. handle.response = detail::make_unique<Response>();
  19777. handle.error = Error::Connection;
  19778. EXPECT_FALSE(handle.is_valid());
  19779. handle.error = Error::Success;
  19780. EXPECT_TRUE(handle.is_valid());
  19781. }
  19782. TEST(BodyReaderTest, Basic) {
  19783. MockStream stream("Hello, World!");
  19784. detail::BodyReader reader;
  19785. reader.stream = &stream;
  19786. reader.content_length = 13;
  19787. char buf[32];
  19788. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19789. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19790. EXPECT_TRUE(reader.eof);
  19791. }
  19792. TEST(BodyReaderTest, NoStream) {
  19793. detail::BodyReader reader;
  19794. char buf[32];
  19795. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19796. EXPECT_EQ(Error::Connection, reader.last_error);
  19797. }
  19798. TEST(BodyReaderTest, Error) {
  19799. MockStream stream("Hello, World!", 5);
  19800. detail::BodyReader reader;
  19801. reader.stream = &stream;
  19802. reader.content_length = 13;
  19803. char buf[32];
  19804. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19805. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19806. EXPECT_EQ(Error::Read, reader.last_error);
  19807. }
  19808. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19809. // Mock-based StreamHandle tests relying on private internals are removed.
  19810. class OpenStreamTest : public ::testing::Test {
  19811. protected:
  19812. void SetUp() override {
  19813. svr_.Get("/hello", [](const Request &, Response &res) {
  19814. res.set_content("Hello World!", "text/plain");
  19815. });
  19816. svr_.Get("/large", [](const Request &, Response &res) {
  19817. res.set_content(std::string(10000, 'X'), "text/plain");
  19818. });
  19819. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19820. res.set_content("Hello World!", "image/jpeg");
  19821. res.set_header("Content-Encoding", "UTF-8");
  19822. });
  19823. svr_.Get("/chunked", [](const Request &, Response &res) {
  19824. res.set_chunked_content_provider("text/plain",
  19825. [](size_t offset, DataSink &sink) {
  19826. if (offset < 15) {
  19827. sink.write("chunk", 5);
  19828. return true;
  19829. }
  19830. sink.done();
  19831. return true;
  19832. });
  19833. });
  19834. svr_.Get("/compressible", [](const Request &, Response &res) {
  19835. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19836. DataSink &sink) {
  19837. if (offset < 100 * 1024) {
  19838. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19839. sink.write(chunk.data(), chunk.size());
  19840. return true;
  19841. }
  19842. sink.done();
  19843. return true;
  19844. });
  19845. });
  19846. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19847. [](const Request & /*req*/, Response &res) {
  19848. auto i = new int(0);
  19849. res.set_header("Trailer", "Content-Length, X-Allowed");
  19850. res.set_chunked_content_provider(
  19851. "text/plain",
  19852. [i](size_t /*offset*/, DataSink &sink) {
  19853. switch (*i) {
  19854. case 0: sink.os << "123"; break;
  19855. case 1: sink.os << "456"; break;
  19856. case 2: sink.os << "789"; break;
  19857. case 3: {
  19858. sink.done_with_trailer(
  19859. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19860. } break;
  19861. }
  19862. (*i)++;
  19863. return true;
  19864. },
  19865. [i](bool success) {
  19866. EXPECT_TRUE(success);
  19867. delete i;
  19868. });
  19869. });
  19870. // Echo headers endpoint for header-related tests
  19871. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19872. std::string body;
  19873. for (const auto &h : req.headers) {
  19874. body.append(h.first);
  19875. body.push_back(':');
  19876. body.append(h.second);
  19877. body.push_back('\n');
  19878. }
  19879. res.set_content(body, "text/plain");
  19880. });
  19881. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19882. std::string body;
  19883. for (const auto &h : req.headers) {
  19884. body.append(h.first);
  19885. body.push_back(':');
  19886. body.append(h.second);
  19887. body.push_back('\n');
  19888. }
  19889. res.set_content(body, "text/plain");
  19890. });
  19891. port_ = svr_.bind_to_any_port("127.0.0.1");
  19892. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19893. svr_.wait_until_ready();
  19894. }
  19895. void TearDown() override {
  19896. svr_.stop();
  19897. if (thread_.joinable()) thread_.join();
  19898. }
  19899. Server svr_;
  19900. std::thread thread_;
  19901. int port_ = 0;
  19902. };
  19903. TEST_F(OpenStreamTest, Basic) {
  19904. Client cli("127.0.0.1", port_);
  19905. auto handle = cli.open_stream("GET", "/hello");
  19906. EXPECT_TRUE(handle.is_valid());
  19907. EXPECT_EQ("Hello World!", read_all(handle));
  19908. }
  19909. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19910. Client cli("127.0.0.1", port_);
  19911. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19912. ASSERT_TRUE(handle.is_valid());
  19913. EXPECT_EQ("Hello World!", read_all(handle));
  19914. }
  19915. TEST_F(OpenStreamTest, SmallBuffer) {
  19916. Client cli("127.0.0.1", port_);
  19917. auto handle = cli.open_stream("GET", "/hello");
  19918. std::string result;
  19919. char buf[4];
  19920. ssize_t n;
  19921. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19922. result.append(buf, static_cast<size_t>(n));
  19923. EXPECT_EQ("Hello World!", result);
  19924. }
  19925. TEST_F(OpenStreamTest, DefaultHeaders) {
  19926. Client cli("127.0.0.1", port_);
  19927. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19928. {
  19929. auto handle = cli.open_stream("GET", "/echo-headers");
  19930. ASSERT_TRUE(handle.is_valid());
  19931. auto body = read_all(handle);
  19932. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19933. std::string::npos);
  19934. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19935. std::string::npos);
  19936. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19937. }
  19938. // open_stream POST with body and no explicit content_type should NOT add
  19939. // text/plain Content-Type (behavior differs from non-streaming path), but
  19940. // should include Content-Length
  19941. {
  19942. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19943. ASSERT_TRUE(handle.is_valid());
  19944. auto body = read_all(handle);
  19945. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19946. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19947. }
  19948. // open_stream POST with explicit Content-Type should preserve it
  19949. {
  19950. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19951. {{"Content-Type", "application/custom"}},
  19952. "{}", "application/custom");
  19953. ASSERT_TRUE(handle.is_valid());
  19954. auto body = read_all(handle);
  19955. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19956. }
  19957. // User-specified User-Agent must not be overwritten for stream API
  19958. {
  19959. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19960. {{"User-Agent", "MyAgent/1.2"}});
  19961. ASSERT_TRUE(handle.is_valid());
  19962. auto body = read_all(handle);
  19963. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19964. }
  19965. }
  19966. TEST_F(OpenStreamTest, Large) {
  19967. Client cli("127.0.0.1", port_);
  19968. auto handle = cli.open_stream("GET", "/large");
  19969. EXPECT_EQ(10000u, read_all(handle).size());
  19970. }
  19971. TEST_F(OpenStreamTest, ConnectionError) {
  19972. Client cli("127.0.0.1", 9999);
  19973. auto handle = cli.open_stream("GET", "/hello");
  19974. EXPECT_FALSE(handle.is_valid());
  19975. }
  19976. TEST_F(OpenStreamTest, Chunked) {
  19977. Client cli("127.0.0.1", port_);
  19978. auto handle = cli.open_stream("GET", "/chunked");
  19979. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19980. "Transfer-Encoding") == "chunked");
  19981. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19982. }
  19983. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19984. Client cli("127.0.0.1", port_);
  19985. auto handle =
  19986. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19987. ASSERT_TRUE(handle.is_valid());
  19988. // Consume body to allow trailers to be received/parsed
  19989. auto body = read_all(handle);
  19990. // Explicitly parse trailers (ensure trailers are available for assertion)
  19991. handle.parse_trailers_if_needed();
  19992. EXPECT_EQ(std::string("123456789"), body);
  19993. // The response should include a Trailer header declaring both names
  19994. ASSERT_TRUE(handle.response);
  19995. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19996. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19997. handle.response->get_header_value("Trailer"));
  19998. // Prohibited trailer must not be present
  19999. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20000. // Allowed trailer should be present
  20001. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20002. EXPECT_EQ(std::string("yes"),
  20003. handle.response->get_trailer_value("X-Allowed"));
  20004. // Verify trailers are NOT present as regular headers
  20005. EXPECT_EQ(std::string(""),
  20006. handle.response->get_header_value("Content-Length"));
  20007. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20008. }
  20009. // Accepts one connection on an OS-assigned port, which it hands over through
  20010. // port_promise, reads the request head and sends back response. after_send,
  20011. // if given, runs on the connection before it is closed.
  20012. static std::thread
  20013. serve_single_response(std::promise<int> &port_promise,
  20014. const std::string &response,
  20015. std::function<void(socket_t)> after_send = nullptr) {
  20016. return std::thread([&port_promise, response, after_send] {
  20017. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20018. default_socket_options(srv);
  20019. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20020. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20021. sockaddr_in addr{};
  20022. addr.sin_family = AF_INET;
  20023. addr.sin_port = htons(0); // Let OS assign a free port
  20024. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20025. int opt = 1;
  20026. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20027. #ifdef _WIN32
  20028. reinterpret_cast<const char *>(&opt),
  20029. #else
  20030. &opt,
  20031. #endif
  20032. sizeof(opt));
  20033. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  20034. ::listen(srv, 1) != 0) {
  20035. port_promise.set_value(-1);
  20036. detail::close_socket(srv);
  20037. return;
  20038. }
  20039. socklen_t addr_len = sizeof(addr);
  20040. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  20041. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  20042. sockaddr_in cli_addr{};
  20043. socklen_t cli_len = sizeof(cli_addr);
  20044. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20045. if (cli != INVALID_SOCKET) {
  20046. // Read the complete HTTP request (until the blank line that terminates
  20047. // headers) before sending the response. If the server closes the socket
  20048. // while the client's request data is still unread in the kernel receive
  20049. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  20050. // connection on both sides: it discards the client's receive buffer
  20051. // (which already holds our response) and causes any in-progress write on
  20052. // the client to fail with ECONNRESET. Reading all request data first
  20053. // ensures close() emits a graceful FIN.
  20054. {
  20055. char rbuf[256];
  20056. std::string req;
  20057. while (req.find("\r\n\r\n") == std::string::npos) {
  20058. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  20059. if (n <= 0) { break; }
  20060. req.append(rbuf, static_cast<size_t>(n));
  20061. }
  20062. }
  20063. ::send(cli,
  20064. #ifdef _WIN32
  20065. static_cast<const char *>(response.c_str()),
  20066. static_cast<int>(response.size()),
  20067. #else
  20068. response.c_str(), response.size(),
  20069. #endif
  20070. 0);
  20071. if (after_send) { after_send(cli); }
  20072. detail::close_socket(cli);
  20073. }
  20074. detail::close_socket(srv);
  20075. });
  20076. }
  20077. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  20078. #ifndef _WIN32
  20079. signal(SIGPIPE, SIG_IGN);
  20080. #endif
  20081. std::promise<int> port_promise;
  20082. auto port_future = port_promise.get_future();
  20083. auto server_thread =
  20084. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  20085. "Content-Type: text/plain\r\n"
  20086. "Content-Length: not-a-number\r\n"
  20087. "Connection: close\r\n"
  20088. "\r\n"
  20089. "hello");
  20090. auto port = port_future.get();
  20091. ASSERT_GT(port, 0);
  20092. Client cli("127.0.0.1", port);
  20093. auto handle = cli.open_stream("GET", "/");
  20094. EXPECT_FALSE(handle.is_valid());
  20095. server_thread.join();
  20096. }
  20097. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  20098. #ifndef _WIN32
  20099. signal(SIGPIPE, SIG_IGN);
  20100. #endif
  20101. std::promise<int> port_promise;
  20102. auto port_future = port_promise.get_future();
  20103. auto server_thread = serve_single_response(
  20104. port_promise, "HTTP/1.1 200 OK\r\n"
  20105. "Content-Type: text/plain\r\n"
  20106. "Content-Length: 99999999999999999999999999\r\n"
  20107. "Connection: close\r\n"
  20108. "\r\n"
  20109. "hello");
  20110. auto port = port_future.get();
  20111. ASSERT_GT(port, 0);
  20112. // Historically std::stoull would throw std::out_of_range here and crash
  20113. // the process, then parsing silently clamped to a bogus framing length and
  20114. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  20115. // so the stream fails to open, matching the not-a-number case above. The
  20116. // process still must NOT terminate.
  20117. Client cli("127.0.0.1", port);
  20118. auto handle = cli.open_stream("GET", "/");
  20119. EXPECT_FALSE(handle.is_valid());
  20120. server_thread.join();
  20121. }
  20122. #ifndef _WIN32
  20123. // As above for the body of a streamed request: a send() cut short by the write
  20124. // timeout must not leave the rest of the body unsent.
  20125. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  20126. signal(SIGPIPE, SIG_IGN);
  20127. Server svr;
  20128. svr.set_socket_options([](socket_t sock) {
  20129. int size = 8192;
  20130. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  20131. reinterpret_cast<const char *>(&size), sizeof(size));
  20132. });
  20133. svr.Post("/size", [](const Request &, Response &res,
  20134. const ContentReader &content_reader) {
  20135. // Outlast the client's write timeout before reading the body.
  20136. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  20137. size_t received = 0;
  20138. content_reader([&](const char *, size_t len) {
  20139. received += len;
  20140. return true;
  20141. });
  20142. res.set_content(std::to_string(received), "text/plain");
  20143. });
  20144. auto port = svr.bind_to_any_port(HOST);
  20145. std::thread t([&]() { svr.listen_after_bind(); });
  20146. auto se = detail::scope_exit([&] {
  20147. svr.stop();
  20148. t.join();
  20149. });
  20150. svr.wait_until_ready();
  20151. Client cli(HOST, port);
  20152. cli.set_write_timeout(0, 500000);
  20153. cli.set_socket_options([](socket_t sock) {
  20154. int size = 8192;
  20155. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  20156. reinterpret_cast<const char *>(&size), sizeof(size));
  20157. });
  20158. const std::string body(4 * 1024 * 1024, 'A');
  20159. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  20160. "application/octet-stream");
  20161. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20162. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  20163. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  20164. }
  20165. #endif
  20166. // Serves `response` to the single request `fn` makes with a fresh client.
  20167. template <typename Fn>
  20168. static void with_single_response(const std::string &response, Fn fn) {
  20169. #ifndef _WIN32
  20170. signal(SIGPIPE, SIG_IGN);
  20171. #endif
  20172. std::promise<int> port_promise;
  20173. auto port_future = port_promise.get_future();
  20174. auto server_thread = serve_single_response(port_promise, response);
  20175. auto se = detail::scope_exit([&] { server_thread.join(); });
  20176. auto port = port_future.get();
  20177. ASSERT_GT(port, 0);
  20178. Client cli("127.0.0.1", port);
  20179. fn(cli);
  20180. }
  20181. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  20182. // too, also in a build without the decoder for the advertised coding.
  20183. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  20184. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  20185. const auto response = "HTTP/1.1 200 OK\r\n"
  20186. "Content-Encoding: gzip\r\n"
  20187. "Content-Length: " +
  20188. std::to_string(gzipped.size()) +
  20189. "\r\n"
  20190. "Connection: close\r\n\r\n" +
  20191. gzipped;
  20192. with_single_response(response, [&](Client &cli) {
  20193. cli.set_decompress(false);
  20194. auto handle = cli.open_stream("GET", "/");
  20195. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  20196. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20197. EXPECT_EQ(gzipped, read_all(handle));
  20198. EXPECT_FALSE(handle.has_read_error());
  20199. });
  20200. with_single_response(response, [&](Client &cli) {
  20201. cli.set_decompress(false);
  20202. auto res = stream::Get(cli, "/", 7);
  20203. ASSERT_TRUE(res) << to_string(res.error());
  20204. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  20205. EXPECT_EQ(gzipped, res.read_all());
  20206. EXPECT_FALSE(res.has_read_error());
  20207. });
  20208. }
  20209. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  20210. // Neither Content-Length nor chunked: the body ends at the close
  20211. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  20212. "Connection: close\r\n"
  20213. "\r\n"
  20214. "hello";
  20215. with_single_response(close_delimited, [](Client &cli) {
  20216. auto handle = cli.open_stream("GET", "/");
  20217. ASSERT_TRUE(handle.is_valid());
  20218. EXPECT_EQ("hello", read_all(handle));
  20219. EXPECT_FALSE(handle.has_read_error());
  20220. });
  20221. // A close before the end of the Content-Length is still an error
  20222. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  20223. "Content-Length: 10\r\n"
  20224. "\r\n"
  20225. "hello";
  20226. with_single_response(short_content_length, [](Client &cli) {
  20227. auto handle = cli.open_stream("GET", "/");
  20228. ASSERT_TRUE(handle.is_valid());
  20229. read_all(handle);
  20230. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  20231. });
  20232. // So is a close before the last chunk
  20233. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  20234. "Transfer-Encoding: chunked\r\n"
  20235. "\r\n"
  20236. "5\r\nhello\r\n";
  20237. with_single_response(short_chunked, [](Client &cli) {
  20238. auto handle = cli.open_stream("GET", "/");
  20239. ASSERT_TRUE(handle.is_valid());
  20240. read_all(handle);
  20241. EXPECT_TRUE(handle.has_read_error());
  20242. });
  20243. }
  20244. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  20245. const char *responses[] = {
  20246. "HTTP/1.1 103 Early Hints\r\n"
  20247. "Link: </style.css>; rel=preload\r\n"
  20248. "\r\n"
  20249. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20250. "HTTP/1.1 100 Continue\r\n"
  20251. "X-Note: interim\r\n"
  20252. "\r\n"
  20253. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  20254. };
  20255. for (auto response : responses) {
  20256. with_single_response(response, [](Client &cli) {
  20257. auto res = cli.Get("/");
  20258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20259. EXPECT_EQ(StatusCode::OK_200, res->status);
  20260. EXPECT_EQ("ok", res->body);
  20261. });
  20262. }
  20263. }
  20264. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  20265. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  20266. const std::string final_response =
  20267. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  20268. std::string interims;
  20269. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  20270. interims += interim;
  20271. }
  20272. with_single_response(interims + final_response, [](Client &cli) {
  20273. auto res = cli.Get("/");
  20274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20275. EXPECT_EQ("ok", res->body);
  20276. });
  20277. with_single_response(interims + interim + final_response, [](Client &cli) {
  20278. auto res = cli.Get("/");
  20279. ASSERT_FALSE(res);
  20280. EXPECT_EQ(Error::Read, res.error());
  20281. });
  20282. }
  20283. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  20284. #ifndef _WIN32
  20285. signal(SIGPIPE, SIG_IGN);
  20286. #endif
  20287. // The server answers the head without asking for the body. Bytes it then
  20288. // reads on the connection would be taken for the body the request declared.
  20289. auto closed_by_client = false;
  20290. std::promise<int> port_promise;
  20291. auto server_thread = serve_single_response(
  20292. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  20293. [&](socket_t sock) {
  20294. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20295. char buf[256];
  20296. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  20297. });
  20298. Client cli("127.0.0.1", port_promise.get_future().get());
  20299. cli.set_keep_alive(true);
  20300. cli.set_read_timeout(1, 0);
  20301. // Long enough for the client to send Expect: 100-continue.
  20302. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20304. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20305. cli.Get("/second");
  20306. server_thread.join();
  20307. EXPECT_TRUE(closed_by_client);
  20308. }
  20309. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  20310. // Long enough for the client to send Expect: 100-continue
  20311. with_single_response(
  20312. "HTTP/1.1 103 Early Hints\r\n"
  20313. "Link: </style.css>; rel=preload\r\n"
  20314. "\r\n"
  20315. "HTTP/1.1 401 Unauthorized\r\n"
  20316. "Content-Length: 0\r\n\r\n",
  20317. [](Client &cli) {
  20318. cli.set_read_timeout(2, 0);
  20319. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20321. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20322. });
  20323. }
  20324. #ifdef CPPHTTPLIB_SSL_ENABLED
  20325. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20326. #ifndef _WIN32
  20327. signal(SIGPIPE, SIG_IGN);
  20328. #endif
  20329. auto reused = false;
  20330. std::promise<int> port_promise;
  20331. auto server_thread = serve_single_response(
  20332. port_promise,
  20333. "HTTP/1.1 401 Unauthorized\r\n"
  20334. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20335. "Content-Length: 0\r\n\r\n",
  20336. [&](socket_t sock) {
  20337. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20338. char buf[256];
  20339. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20340. });
  20341. Client cli("127.0.0.1", port_promise.get_future().get());
  20342. cli.set_keep_alive(true);
  20343. cli.set_digest_auth("user", "pass");
  20344. cli.set_read_timeout(1, 0);
  20345. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20346. server_thread.join();
  20347. EXPECT_FALSE(reused);
  20348. }
  20349. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20350. // Any other answer to CONNECT would read as the origin's response.
  20351. struct {
  20352. const char *response;
  20353. bool passed_on;
  20354. } cases[] = {
  20355. {"HTTP/1.1 201 Created\r\n"
  20356. "Set-Cookie: session=from-proxy\r\n"
  20357. "Content-Length: 0\r\n\r\n",
  20358. false},
  20359. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20360. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20361. "Content-Length: 0\r\n\r\n",
  20362. true},
  20363. };
  20364. for (const auto &c : cases) {
  20365. std::promise<int> port_promise;
  20366. auto server_thread = serve_single_response(port_promise, c.response);
  20367. SSLClient cli("example.com", 443);
  20368. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20369. auto res = cli.Get("/");
  20370. server_thread.join();
  20371. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20372. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20373. if (res) {
  20374. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20375. }
  20376. }
  20377. }
  20378. #endif
  20379. // Records the client's error logger calls as "error METHOD path", or
  20380. // "error null" for a call without a request
  20381. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20382. return [&log](const Error &err, const Request *req) {
  20383. log.push_back(to_string(err) + " " +
  20384. (req ? req->method + " " + req->path : "null"));
  20385. };
  20386. }
  20387. // A failed request is reported once, with the request the caller made
  20388. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20389. Server svr;
  20390. svr.Get("/big", [](const Request &, Response &res) {
  20391. res.set_content(std::string(100000, 'b'), "text/plain");
  20392. });
  20393. auto port = svr.bind_to_any_port(HOST);
  20394. std::thread t([&]() { svr.listen_after_bind(); });
  20395. auto se = detail::scope_exit([&] {
  20396. svr.stop();
  20397. t.join();
  20398. });
  20399. svr.wait_until_ready();
  20400. Client cli(HOST, port);
  20401. std::vector<std::string> log;
  20402. cli.set_error_logger(record_errors(log));
  20403. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20404. cli.Get("/big", [](const char *, size_t) { return false; });
  20405. EXPECT_EQ(expected, log);
  20406. log.clear();
  20407. cli.Get("/big", [](size_t, size_t) { return false; });
  20408. EXPECT_EQ(expected, log);
  20409. }
  20410. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20411. // Fails while the body is read
  20412. auto broken = [](const Request &, Response &res) {
  20413. res.set_content_provider(10, "text/plain",
  20414. [](size_t, size_t, DataSink &) { return false; });
  20415. };
  20416. Server other;
  20417. other.Get("/broken", broken);
  20418. auto other_port = other.bind_to_any_port(HOST);
  20419. std::thread other_t([&]() { other.listen_after_bind(); });
  20420. auto other_se = detail::scope_exit([&] {
  20421. other.stop();
  20422. other_t.join();
  20423. });
  20424. other.wait_until_ready();
  20425. Server svr;
  20426. svr.Get("/broken", broken);
  20427. svr.Get("/same-origin",
  20428. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20429. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20430. res.set_redirect("http://" + std::string(HOST) + ":" +
  20431. std::to_string(other_port) + "/broken");
  20432. });
  20433. auto port = svr.bind_to_any_port(HOST);
  20434. std::thread t([&]() { svr.listen_after_bind(); });
  20435. auto se = detail::scope_exit([&] {
  20436. svr.stop();
  20437. t.join();
  20438. });
  20439. svr.wait_until_ready();
  20440. Client cli(HOST, port);
  20441. cli.set_follow_location(true);
  20442. std::vector<std::string> log;
  20443. cli.set_error_logger(record_errors(log));
  20444. for (auto path : {"/same-origin", "/cross-origin"}) {
  20445. log.clear();
  20446. auto res = cli.Get(path);
  20447. ASSERT_FALSE(res);
  20448. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20449. log);
  20450. }
  20451. }
  20452. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20453. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20454. std::vector<std::string> log;
  20455. cli.set_error_logger(record_errors(log));
  20456. auto handle = cli.open_stream("GET", "/x");
  20457. EXPECT_FALSE(handle.is_valid());
  20458. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20459. log);
  20460. });
  20461. }
  20462. #ifdef CPPHTTPLIB_SSL_ENABLED
  20463. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20464. // Not a TLS server, so the handshake fails. It waits for a request line in
  20465. // the handshake bytes, so a short read timeout lets it close quickly.
  20466. Server svr;
  20467. svr.set_read_timeout(0, 100000);
  20468. svr.Get("/x", [](const Request &, Response &res) {
  20469. res.set_content("x", "text/plain");
  20470. });
  20471. auto port = svr.bind_to_any_port(HOST);
  20472. std::thread t([&]() { svr.listen_after_bind(); });
  20473. auto se = detail::scope_exit([&] {
  20474. svr.stop();
  20475. t.join();
  20476. });
  20477. svr.wait_until_ready();
  20478. std::vector<std::string> log;
  20479. SSLClient cli(HOST, port);
  20480. cli.enable_server_certificate_verification(false);
  20481. cli.set_error_logger(record_errors(log));
  20482. auto res = cli.Get("/x");
  20483. ASSERT_FALSE(res);
  20484. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20485. log.clear();
  20486. auto handle = cli.open_stream("GET", "/x");
  20487. EXPECT_FALSE(handle.is_valid());
  20488. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20489. log.clear();
  20490. SSLClient no_ca(HOST, port);
  20491. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20492. no_ca.set_error_logger(record_errors(log));
  20493. res = no_ca.Get("/x");
  20494. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20495. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20496. }
  20497. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20498. #ifndef _WIN32
  20499. signal(SIGPIPE, SIG_IGN);
  20500. #endif
  20501. // Refused, answered with a challenge, or closed without an answer
  20502. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20503. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20504. "Content-Length: 0\r\n\r\n",
  20505. ""}) {
  20506. std::promise<int> port_promise;
  20507. auto server_thread = serve_single_response(port_promise, response);
  20508. SSLClient cli("example.com", 443);
  20509. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20510. std::vector<std::string> log;
  20511. cli.set_error_logger(record_errors(log));
  20512. auto res = cli.Get("/");
  20513. server_thread.join();
  20514. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20515. << response;
  20516. }
  20517. }
  20518. #endif
  20519. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20520. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20521. // the chunked coding and drop Content-Length, so a front-end that trusts
  20522. // Content-Length would disagree about where the body ends (response
  20523. // smuggling). The client must reject such a response.
  20524. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20525. for (const char *te : {"chunked", "gzip, chunked"}) {
  20526. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20527. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20528. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20529. "5\r\nhello\r\n0\r\n\r\n";
  20530. with_single_response(response, [&](Client &cli) {
  20531. auto res = cli.Get("/");
  20532. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20533. EXPECT_EQ(Error::Read, res.error()) << te;
  20534. });
  20535. with_single_response(response, [&](Client &cli) {
  20536. auto handle = cli.open_stream("GET", "/");
  20537. EXPECT_FALSE(handle.is_valid()) << te;
  20538. EXPECT_EQ(Error::Read, handle.error) << te;
  20539. });
  20540. }
  20541. }
  20542. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20543. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20544. // closing the connection (unlike a request, which must be rejected).
  20545. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20546. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20547. "Transfer-Encoding: chunked\r\n"
  20548. "Connection: close\r\n"
  20549. "\r\n"
  20550. "5\r\nhello\r\n0\r\n\r\n",
  20551. "HTTP/1.1 200 OK\r\n"
  20552. "Transfer-Encoding: gzip\r\n"
  20553. "Connection: close\r\n"
  20554. "\r\n"
  20555. "hello"}) {
  20556. with_single_response(response, [&](Client &cli) {
  20557. auto res = cli.Get("/");
  20558. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20559. EXPECT_EQ("hello", res->body);
  20560. });
  20561. with_single_response(response, [&](Client &cli) {
  20562. auto handle = cli.open_stream("GET", "/");
  20563. ASSERT_TRUE(handle.is_valid()) << response;
  20564. EXPECT_EQ("hello", read_all(handle));
  20565. });
  20566. }
  20567. }
  20568. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20569. // framing headers describe nothing to read and must not be rejected.
  20570. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20571. const std::string framing = "Content-Length: 5\r\n"
  20572. "Transfer-Encoding: chunked\r\n"
  20573. "Connection: close\r\n"
  20574. "\r\n";
  20575. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20576. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20577. });
  20578. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20579. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20580. });
  20581. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20582. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20583. with_single_response(response, [&](Client &cli) {
  20584. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20585. });
  20586. with_single_response(response, [&](Client &cli) {
  20587. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20588. });
  20589. }
  20590. }
  20591. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20592. // header section, so a stream opened on one has nothing to read, whatever
  20593. // framing or coding headers it carries.
  20594. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20595. struct Case {
  20596. const char *method;
  20597. const char *status;
  20598. };
  20599. // A reader of the declared body reports an early close when nothing
  20600. // follows, and hands back what does.
  20601. struct Framing {
  20602. const char *headers;
  20603. const char *after;
  20604. };
  20605. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20606. Case{"GET", "304 Not Modified"}}) {
  20607. for (const auto &f :
  20608. {Framing{"Content-Length: 5\r\n", ""},
  20609. Framing{"Content-Length: 5\r\n", "hello"},
  20610. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20611. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20612. // Not decoded, so a build without Brotli opens it too
  20613. Framing{"Content-Encoding: br\r\n", ""}}) {
  20614. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20615. "Connection: close\r\n"
  20616. "\r\n" +
  20617. f.after;
  20618. with_single_response(response, [&](Client &cli) {
  20619. auto handle = cli.open_stream(c.method, "/");
  20620. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20621. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20622. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20623. });
  20624. }
  20625. }
  20626. }
  20627. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20628. // response, is faulty framing, so the connection is not reused after it.
  20629. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20630. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20631. "Content-Length: 0\r\n"
  20632. "Transfer-Encoding: chunked\r\n"
  20633. "\r\n"
  20634. "5\r\nhello\r\n0\r\n\r\n",
  20635. "HTTP/1.0 200 Connection established\r\n"
  20636. "Connection: keep-alive\r\n"
  20637. "Transfer-Encoding: chunked\r\n"
  20638. "\r\n"
  20639. "5\r\nhello\r\n0\r\n\r\n"}) {
  20640. with_single_response(response, [&](Client &cli) {
  20641. cli.set_keep_alive(true);
  20642. auto res = cli.Get("/");
  20643. ASSERT_TRUE(res) << response;
  20644. EXPECT_EQ("hello", res->body);
  20645. EXPECT_FALSE(cli.is_socket_open()) << response;
  20646. });
  20647. }
  20648. }
  20649. // A payload max length of 0 means no limit, however the body is framed.
  20650. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20651. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20652. "Transfer-Encoding: chunked\r\n"
  20653. "\r\n"
  20654. "5\r\nhello\r\n0\r\n\r\n",
  20655. "HTTP/1.1 200 OK\r\n"
  20656. "Connection: close\r\n"
  20657. "\r\n"
  20658. "hello"}) {
  20659. with_single_response(response, [&](Client &cli) {
  20660. cli.set_payload_max_length(0);
  20661. auto res = cli.Get("/");
  20662. ASSERT_TRUE(res) << response;
  20663. EXPECT_EQ("hello", res->body) << response;
  20664. });
  20665. }
  20666. }
  20667. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20668. Server svr;
  20669. svr.set_payload_max_length(0);
  20670. svr.Post("/echo", [](const Request &req, Response &res) {
  20671. res.set_content(req.body, "text/plain");
  20672. });
  20673. auto port = svr.bind_to_any_port(HOST);
  20674. thread t = thread([&] { svr.listen_after_bind(); });
  20675. auto se = detail::scope_exit([&] {
  20676. svr.stop();
  20677. t.join();
  20678. ASSERT_FALSE(svr.is_running());
  20679. });
  20680. svr.wait_until_ready();
  20681. Client cli(HOST, port);
  20682. auto res = cli.Post(
  20683. "/echo",
  20684. [](size_t /*offset*/, DataSink &sink) {
  20685. sink.write("hello", 5);
  20686. sink.done();
  20687. return true;
  20688. },
  20689. "text/plain");
  20690. ASSERT_TRUE(res);
  20691. EXPECT_EQ(StatusCode::OK_200, res->status);
  20692. EXPECT_EQ("hello", res->body);
  20693. }
  20694. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20695. TEST_F(OpenStreamTest, Gzip) {
  20696. Client cli("127.0.0.1", port_);
  20697. auto handle = cli.open_stream("GET", "/compressible", {},
  20698. {{"Accept-Encoding", "gzip"}});
  20699. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20700. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20701. }
  20702. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20703. Client cli("127.0.0.1", port_);
  20704. auto handle =
  20705. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20706. {{"Accept-Encoding", "gzip"}});
  20707. ASSERT_TRUE(handle.is_valid());
  20708. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20709. EXPECT_EQ("123456789", read_all(handle));
  20710. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20711. }
  20712. #endif
  20713. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20714. TEST_F(OpenStreamTest, Brotli) {
  20715. Client cli("127.0.0.1", port_);
  20716. auto handle =
  20717. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20718. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20719. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20720. }
  20721. #endif
  20722. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20723. TEST_F(OpenStreamTest, Zstd) {
  20724. Client cli("127.0.0.1", port_);
  20725. auto handle = cli.open_stream("GET", "/compressible", {},
  20726. {{"Accept-Encoding", "zstd"}});
  20727. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20728. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20729. }
  20730. #endif
  20731. #ifdef CPPHTTPLIB_SSL_ENABLED
  20732. class SSLOpenStreamTest : public ::testing::Test {
  20733. protected:
  20734. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20735. void SetUp() override {
  20736. svr_.Get("/hello", [](const Request &, Response &res) {
  20737. res.set_content("Hello SSL World!", "text/plain");
  20738. });
  20739. svr_.Get("/chunked", [](const Request &, Response &res) {
  20740. res.set_chunked_content_provider("text/plain",
  20741. [](size_t offset, DataSink &sink) {
  20742. if (offset < 15) {
  20743. sink.write("chunk", 5);
  20744. return true;
  20745. }
  20746. sink.done();
  20747. return true;
  20748. });
  20749. });
  20750. svr_.Post("/echo", [](const Request &req, Response &res) {
  20751. res.set_content(req.body, req.get_header_value("Content-Type"));
  20752. });
  20753. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20754. std::string body = req.body;
  20755. res.set_chunked_content_provider(
  20756. "text/plain", [body](size_t offset, DataSink &sink) {
  20757. if (offset < body.size()) {
  20758. sink.write(body.data() + offset, body.size() - offset);
  20759. }
  20760. sink.done();
  20761. return true;
  20762. });
  20763. });
  20764. port_ = svr_.bind_to_any_port("127.0.0.1");
  20765. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20766. svr_.wait_until_ready();
  20767. }
  20768. void TearDown() override {
  20769. svr_.stop();
  20770. if (thread_.joinable()) thread_.join();
  20771. }
  20772. SSLServer svr_;
  20773. std::thread thread_;
  20774. int port_ = 0;
  20775. };
  20776. TEST_F(SSLOpenStreamTest, Basic) {
  20777. SSLClient cli("127.0.0.1", port_);
  20778. cli.enable_server_certificate_verification(false);
  20779. auto handle = cli.open_stream("GET", "/hello");
  20780. ASSERT_TRUE(handle.is_valid());
  20781. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20782. }
  20783. TEST_F(SSLOpenStreamTest, Chunked) {
  20784. SSLClient cli("127.0.0.1", port_);
  20785. cli.enable_server_certificate_verification(false);
  20786. auto handle = cli.open_stream("GET", "/chunked");
  20787. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20788. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20789. "Transfer-Encoding") == "chunked");
  20790. auto body = read_all(handle);
  20791. EXPECT_EQ("chunkchunkchunk", body);
  20792. }
  20793. TEST_F(SSLOpenStreamTest, Post) {
  20794. SSLClient cli("127.0.0.1", port_);
  20795. cli.enable_server_certificate_verification(false);
  20796. auto handle =
  20797. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20798. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20799. EXPECT_EQ(200, handle.response->status);
  20800. auto body = read_all(handle);
  20801. EXPECT_EQ("Hello SSL POST", body);
  20802. }
  20803. TEST_F(SSLOpenStreamTest, PostChunked) {
  20804. SSLClient cli("127.0.0.1", port_);
  20805. cli.enable_server_certificate_verification(false);
  20806. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20807. "Chunked SSL Data", "text/plain");
  20808. ASSERT_TRUE(handle.is_valid());
  20809. EXPECT_EQ(200, handle.response->status);
  20810. auto body = read_all(handle);
  20811. EXPECT_EQ("Chunked SSL Data", body);
  20812. }
  20813. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20814. // Content-Length is terminated by the server closing the connection. When the
  20815. // SSL peer sends a close_notify after the body, the client must treat it as a
  20816. // clean EOF and return a successful response rather than an error.
  20817. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20818. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20819. ASSERT_TRUE(svr.is_valid());
  20820. svr.set_keep_alive_max_count(1);
  20821. const std::string expected_body = "Hello from connection-close response!";
  20822. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20823. res.set_content_provider("text/plain",
  20824. [&](size_t offset, DataSink &sink) -> bool {
  20825. if (offset < expected_body.size()) {
  20826. sink.write(expected_body.data() + offset,
  20827. expected_body.size() - offset);
  20828. }
  20829. sink.done();
  20830. return true;
  20831. });
  20832. });
  20833. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20834. auto se = detail::scope_exit([&] {
  20835. svr.stop();
  20836. listen_thread.join();
  20837. ASSERT_FALSE(svr.is_running());
  20838. });
  20839. svr.wait_until_ready();
  20840. SSLClient cli(HOST, PORT);
  20841. cli.enable_server_certificate_verification(false);
  20842. auto res = cli.Get("/no-content-length");
  20843. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20844. EXPECT_EQ(StatusCode::OK_200, res->status);
  20845. EXPECT_EQ(expected_body, res->body);
  20846. }
  20847. #endif // CPPHTTPLIB_SSL_ENABLED
  20848. //==============================================================================
  20849. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20850. // results for various scenarios.
  20851. //==============================================================================
  20852. TEST(ParityTest, GetVsOpenStream) {
  20853. Server svr;
  20854. const std::string path = "/parity";
  20855. const std::string content = "Parity test content: hello world";
  20856. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20857. res.set_content(content, "text/plain");
  20858. });
  20859. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20860. auto se = detail::scope_exit([&] {
  20861. svr.stop();
  20862. t.join();
  20863. ASSERT_FALSE(svr.is_running());
  20864. });
  20865. svr.wait_until_ready();
  20866. Client cli(HOST, PORT);
  20867. // Non-stream path
  20868. auto r1 = cli.Get(path);
  20869. ASSERT_TRUE(r1);
  20870. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20871. // Stream path
  20872. auto h = cli.open_stream("GET", path);
  20873. ASSERT_TRUE(h.is_valid());
  20874. EXPECT_EQ(r1->body, read_all(h));
  20875. }
  20876. // Helper to compress data with provided compressor type T
  20877. template <typename Compressor>
  20878. static std::string compress_payload_for_parity(const std::string &in) {
  20879. std::string out;
  20880. Compressor compressor;
  20881. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20882. [&](const char *data, size_t n) {
  20883. out.append(data, n);
  20884. return true;
  20885. });
  20886. EXPECT_TRUE(ok);
  20887. return out;
  20888. }
  20889. // Helper function for compression parity tests
  20890. template <typename Compressor>
  20891. static void test_compression_parity(const std::string &original,
  20892. const std::string &path,
  20893. const std::string &encoding) {
  20894. const std::string compressed =
  20895. compress_payload_for_parity<Compressor>(original);
  20896. Server svr;
  20897. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20898. res.set_content(compressed, "application/octet-stream");
  20899. res.set_header("Content-Encoding", encoding);
  20900. });
  20901. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20902. auto se = detail::scope_exit([&] {
  20903. svr.stop();
  20904. t.join();
  20905. ASSERT_FALSE(svr.is_running());
  20906. });
  20907. svr.wait_until_ready();
  20908. Client cli(HOST, PORT);
  20909. // Non-streaming
  20910. {
  20911. auto res = cli.Get(path);
  20912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20913. EXPECT_EQ(StatusCode::OK_200, res->status);
  20914. EXPECT_EQ(original, res->body);
  20915. }
  20916. // Streaming
  20917. {
  20918. auto h = cli.open_stream("GET", path);
  20919. ASSERT_TRUE(h.is_valid());
  20920. EXPECT_EQ(original, read_all(h));
  20921. }
  20922. }
  20923. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20924. TEST(ParityTest, Gzip) {
  20925. test_compression_parity<detail::gzip_compressor>(
  20926. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20927. }
  20928. #endif
  20929. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20930. TEST(ParityTest, Brotli) {
  20931. test_compression_parity<detail::brotli_compressor>(
  20932. "Hello, brotli parity test payload", "/parity-br", "br");
  20933. }
  20934. #endif
  20935. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20936. TEST(ParityTest, Zstd) {
  20937. test_compression_parity<detail::zstd_compressor>(
  20938. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20939. }
  20940. #endif
  20941. //==============================================================================
  20942. // New Stream API Tests
  20943. //==============================================================================
  20944. inline std::string read_body(httplib::stream::Result &result) {
  20945. std::string body;
  20946. while (result.next()) {
  20947. body.append(result.data(), result.size());
  20948. }
  20949. return body;
  20950. }
  20951. TEST(ClientConnectionTest, Basic) {
  20952. httplib::ClientConnection conn;
  20953. EXPECT_FALSE(conn.is_open());
  20954. conn.sock = 1;
  20955. EXPECT_TRUE(conn.is_open());
  20956. httplib::ClientConnection conn2(std::move(conn));
  20957. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20958. conn2.sock = INVALID_SOCKET;
  20959. }
  20960. // Unified test server for all stream::* tests
  20961. class StreamApiTest : public ::testing::Test {
  20962. protected:
  20963. void SetUp() override {
  20964. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20965. res.set_content("Hello World!", "text/plain");
  20966. });
  20967. svr_.Get("/echo-params",
  20968. [](const httplib::Request &req, httplib::Response &res) {
  20969. std::string r;
  20970. for (const auto &p : req.params) {
  20971. if (!r.empty()) r += "&";
  20972. r += p.first + "=" + p.second;
  20973. }
  20974. res.set_content(r, "text/plain");
  20975. });
  20976. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20977. res.set_content(req.body, req.get_header_value("Content-Type"));
  20978. });
  20979. svr_.Post("/echo-headers",
  20980. [](const httplib::Request &req, httplib::Response &res) {
  20981. std::string r;
  20982. for (const auto &h : req.headers)
  20983. r += h.first + ": " + h.second + "\n";
  20984. res.set_content(r, "text/plain");
  20985. });
  20986. svr_.Post("/echo-params",
  20987. [](const httplib::Request &req, httplib::Response &res) {
  20988. std::string r = "params:";
  20989. for (const auto &p : req.params)
  20990. r += p.first + "=" + p.second + ";";
  20991. res.set_content(r + " body:" + req.body, "text/plain");
  20992. });
  20993. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20994. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20995. });
  20996. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20997. res.set_content("PUT:" + req.body, "text/plain");
  20998. });
  20999. svr_.Patch("/echo",
  21000. [](const httplib::Request &req, httplib::Response &res) {
  21001. res.set_content("PATCH:" + req.body, "text/plain");
  21002. });
  21003. svr_.Delete(
  21004. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  21005. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  21006. "text/plain");
  21007. });
  21008. svr_.Get("/head-test",
  21009. [](const httplib::Request &, httplib::Response &res) {
  21010. res.set_content("body for HEAD", "text/plain");
  21011. });
  21012. svr_.Options("/options",
  21013. [](const httplib::Request &, httplib::Response &res) {
  21014. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  21015. });
  21016. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  21017. svr_.wait_until_ready();
  21018. }
  21019. void TearDown() override {
  21020. svr_.stop();
  21021. if (thread_.joinable()) thread_.join();
  21022. }
  21023. httplib::Server svr_;
  21024. std::thread thread_;
  21025. };
  21026. // stream::Get tests
  21027. TEST_F(StreamApiTest, GetBasic) {
  21028. httplib::Client cli(HOST, PORT);
  21029. auto result = httplib::stream::Get(cli, "/hello");
  21030. ASSERT_TRUE(result.is_valid());
  21031. EXPECT_EQ(200, result.status());
  21032. EXPECT_EQ("Hello World!", read_body(result));
  21033. }
  21034. TEST_F(StreamApiTest, GetWithParams) {
  21035. httplib::Client cli(HOST, PORT);
  21036. httplib::Params params{{"foo", "bar"}};
  21037. auto result = httplib::stream::Get(cli, "/echo-params", params);
  21038. ASSERT_TRUE(result.is_valid());
  21039. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  21040. }
  21041. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21042. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  21043. httplib::Client cli(HOST, PORT);
  21044. cli.set_payload_max_length(0);
  21045. auto result = httplib::stream::Get(cli, "/hello");
  21046. ASSERT_TRUE(result.is_valid());
  21047. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  21048. EXPECT_EQ("Hello World!", read_body(result));
  21049. }
  21050. #endif
  21051. TEST_F(StreamApiTest, GetConnectionError) {
  21052. httplib::Client cli(HOST, 9999);
  21053. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  21054. }
  21055. TEST_F(StreamApiTest, Get404) {
  21056. httplib::Client cli(HOST, PORT);
  21057. auto result = httplib::stream::Get(cli, "/nonexistent");
  21058. EXPECT_TRUE(result.is_valid());
  21059. EXPECT_EQ(404, result.status());
  21060. }
  21061. // stream::Post tests
  21062. TEST_F(StreamApiTest, PostBasic) {
  21063. httplib::Client cli(HOST, PORT);
  21064. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  21065. "application/json");
  21066. ASSERT_TRUE(result.is_valid());
  21067. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  21068. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  21069. }
  21070. TEST_F(StreamApiTest, PostWithHeaders) {
  21071. httplib::Client cli(HOST, PORT);
  21072. httplib::Headers headers{{"X-Custom", "value"}};
  21073. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  21074. "text/plain");
  21075. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  21076. }
  21077. TEST_F(StreamApiTest, PostWithParams) {
  21078. httplib::Client cli(HOST, PORT);
  21079. httplib::Params params{{"k", "v"}};
  21080. auto result =
  21081. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  21082. auto body = read_body(result);
  21083. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  21084. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  21085. }
  21086. TEST_F(StreamApiTest, PostLarge) {
  21087. httplib::Client cli(HOST, PORT);
  21088. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  21089. size_t total = 0;
  21090. while (result.next()) {
  21091. total += result.size();
  21092. }
  21093. EXPECT_EQ(100u * 1024u, total);
  21094. }
  21095. // stream::Put/Patch tests
  21096. TEST_F(StreamApiTest, PutAndPatch) {
  21097. httplib::Client cli(HOST, PORT);
  21098. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  21099. EXPECT_EQ("PUT:test", read_body(put));
  21100. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  21101. EXPECT_EQ("PATCH:test", read_body(patch));
  21102. }
  21103. // stream::Delete tests
  21104. TEST_F(StreamApiTest, Delete) {
  21105. httplib::Client cli(HOST, PORT);
  21106. auto del1 = httplib::stream::Delete(cli, "/resource");
  21107. EXPECT_EQ("Deleted", read_body(del1));
  21108. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  21109. EXPECT_EQ("Deleted:data", read_body(del2));
  21110. }
  21111. // stream::Head/Options tests
  21112. TEST_F(StreamApiTest, HeadAndOptions) {
  21113. httplib::Client cli(HOST, PORT);
  21114. auto head = httplib::stream::Head(cli, "/head-test");
  21115. EXPECT_TRUE(head.is_valid());
  21116. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  21117. auto opts = httplib::stream::Options(cli, "/options");
  21118. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  21119. }
  21120. // SSL stream::* tests
  21121. #ifdef CPPHTTPLIB_SSL_ENABLED
  21122. class SSLStreamApiTest : public ::testing::Test {
  21123. protected:
  21124. void SetUp() override {
  21125. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  21126. res.set_content("Hello SSL!", "text/plain");
  21127. });
  21128. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  21129. res.set_content(req.body, "text/plain");
  21130. });
  21131. port_ = svr_.bind_to_any_port("127.0.0.1");
  21132. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21133. svr_.wait_until_ready();
  21134. }
  21135. void TearDown() override {
  21136. svr_.stop();
  21137. if (thread_.joinable()) thread_.join();
  21138. }
  21139. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  21140. std::thread thread_;
  21141. int port_ = 0;
  21142. };
  21143. TEST_F(SSLStreamApiTest, GetAndPost) {
  21144. httplib::SSLClient cli("127.0.0.1", port_);
  21145. cli.enable_server_certificate_verification(false);
  21146. auto get = httplib::stream::Get(cli, "/hello");
  21147. EXPECT_EQ("Hello SSL!", read_body(get));
  21148. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  21149. EXPECT_EQ("test", read_body(post));
  21150. }
  21151. #endif
  21152. // Tests for Error::Timeout and Error::ConnectionClosed error types
  21153. // These errors are set in SocketStream/SSLSocketStream and propagated through
  21154. // BodyReader
  21155. TEST(ErrorHandlingTest, StreamReadTimeout) {
  21156. // Test that read timeout during streaming is detected
  21157. // Use a large content-length response where server delays mid-stream
  21158. Server svr;
  21159. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21160. // Send a large response with delay in the middle
  21161. res.set_content_provider(
  21162. 1000, // content_length
  21163. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  21164. if (offset < 100) {
  21165. // Send first 100 bytes immediately
  21166. std::string data(100, 'A');
  21167. sink.write(data.c_str(), data.size());
  21168. return true;
  21169. }
  21170. // Then delay longer than client timeout
  21171. std::this_thread::sleep_for(std::chrono::seconds(3));
  21172. std::string data(900, 'B');
  21173. sink.write(data.c_str(), data.size());
  21174. return true;
  21175. });
  21176. });
  21177. auto port = 8091;
  21178. std::thread t([&]() { svr.listen("localhost", port); });
  21179. svr.wait_until_ready();
  21180. Client cli("localhost", port);
  21181. cli.set_read_timeout(1, 0); // 1 second timeout
  21182. auto handle = cli.open_stream("GET", "/slow-stream");
  21183. ASSERT_TRUE(handle.is_valid());
  21184. char buf[256];
  21185. ssize_t total = 0;
  21186. ssize_t n;
  21187. bool got_error = false;
  21188. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21189. total += n;
  21190. }
  21191. if (n < 0) {
  21192. got_error = true;
  21193. // Should be timeout or read error
  21194. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21195. handle.get_read_error() == Error::Read)
  21196. << "Actual error: " << to_string(handle.get_read_error());
  21197. }
  21198. // Either we got an error, or we got less data than expected
  21199. EXPECT_TRUE(got_error || total < 1000)
  21200. << "Expected timeout but got all " << total << " bytes";
  21201. svr.stop();
  21202. t.join();
  21203. }
  21204. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  21205. // Test connection closed detection via BodyReader
  21206. Server svr;
  21207. std::atomic<bool> close_now{false};
  21208. svr.Get("/will-close", [&](const Request &, Response &res) {
  21209. res.set_content_provider(
  21210. 10000, // Large content_length that we won't fully send
  21211. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21212. if (offset < 100) {
  21213. std::string data(100, 'X');
  21214. sink.write(data.c_str(), data.size());
  21215. return true;
  21216. }
  21217. // Wait for signal then abort
  21218. while (!close_now) {
  21219. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21220. }
  21221. return false; // Abort - server will close connection
  21222. });
  21223. });
  21224. auto port = 8092;
  21225. std::thread t([&]() { svr.listen("localhost", port); });
  21226. svr.wait_until_ready();
  21227. Client cli("localhost", port);
  21228. auto handle = cli.open_stream("GET", "/will-close");
  21229. ASSERT_TRUE(handle.is_valid());
  21230. char buf[256];
  21231. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21232. EXPECT_GT(n, 0) << "First read should succeed";
  21233. // Signal server to close
  21234. close_now = true;
  21235. // Keep reading until error or EOF
  21236. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21237. // Keep reading
  21238. }
  21239. // Should get an error since content_length wasn't satisfied
  21240. if (n < 0) {
  21241. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21242. handle.get_read_error() == Error::Read)
  21243. << "Actual error: " << to_string(handle.get_read_error());
  21244. }
  21245. svr.stop();
  21246. t.join();
  21247. }
  21248. #ifdef CPPHTTPLIB_SSL_ENABLED
  21249. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  21250. // Test that read timeout during SSL streaming is detected
  21251. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21252. svr.Get("/slow-stream", [](const Request &, Response &res) {
  21253. res.set_content_provider(
  21254. 1000, "text/plain",
  21255. [](size_t offset, size_t /*length*/, DataSink &sink) {
  21256. if (offset < 100) {
  21257. std::string data(100, 'A');
  21258. sink.write(data.c_str(), data.size());
  21259. return true;
  21260. }
  21261. std::this_thread::sleep_for(std::chrono::seconds(3));
  21262. std::string data(900, 'B');
  21263. sink.write(data.c_str(), data.size());
  21264. return true;
  21265. });
  21266. });
  21267. auto port = 8093;
  21268. std::thread t([&]() { svr.listen("localhost", port); });
  21269. svr.wait_until_ready();
  21270. SSLClient cli("localhost", port);
  21271. cli.enable_server_certificate_verification(false);
  21272. cli.set_read_timeout(1, 0); // 1 second timeout
  21273. auto handle = cli.open_stream("GET", "/slow-stream");
  21274. ASSERT_TRUE(handle.is_valid());
  21275. char buf[256];
  21276. ssize_t total = 0;
  21277. ssize_t n;
  21278. bool got_error = false;
  21279. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21280. total += n;
  21281. }
  21282. if (n < 0) {
  21283. got_error = true;
  21284. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  21285. handle.get_read_error() == Error::Read)
  21286. << "Actual error: " << to_string(handle.get_read_error());
  21287. }
  21288. EXPECT_TRUE(got_error || total < 1000)
  21289. << "Expected timeout but got all " << total << " bytes";
  21290. svr.stop();
  21291. t.join();
  21292. }
  21293. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  21294. // Test SSL connection closed detection
  21295. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21296. std::atomic<bool> close_now{false};
  21297. svr.Get("/will-close", [&](const Request &, Response &res) {
  21298. res.set_content_provider(
  21299. 10000, "text/plain",
  21300. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  21301. if (offset < 100) {
  21302. std::string data(100, 'X');
  21303. sink.write(data.c_str(), data.size());
  21304. return true;
  21305. }
  21306. while (!close_now) {
  21307. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21308. }
  21309. return false;
  21310. });
  21311. });
  21312. auto port = 8094;
  21313. std::thread t([&]() { svr.listen("localhost", port); });
  21314. svr.wait_until_ready();
  21315. SSLClient cli("localhost", port);
  21316. cli.enable_server_certificate_verification(false);
  21317. auto handle = cli.open_stream("GET", "/will-close");
  21318. ASSERT_TRUE(handle.is_valid());
  21319. char buf[256];
  21320. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21321. EXPECT_GT(n, 0);
  21322. // Signal server to close
  21323. close_now = true;
  21324. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21325. // Keep reading
  21326. }
  21327. if (n < 0) {
  21328. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21329. handle.get_read_error() == Error::Read)
  21330. << "Actual error: " << to_string(handle.get_read_error());
  21331. }
  21332. svr.stop();
  21333. t.join();
  21334. }
  21335. #endif
  21336. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21337. using namespace httplib;
  21338. // Create a test file
  21339. const char *fname = "etag_testfile.txt";
  21340. const char *content = "etag-content";
  21341. {
  21342. std::ofstream ofs(fname);
  21343. ofs << content;
  21344. ASSERT_TRUE(ofs.good());
  21345. }
  21346. Server svr;
  21347. svr.set_mount_point("/static", ".");
  21348. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21349. svr.wait_until_ready();
  21350. Client cli(HOST, PORT);
  21351. // First request: should get 200 with ETag header
  21352. auto res1 = cli.Get("/static/etag_testfile.txt");
  21353. ASSERT_TRUE(res1);
  21354. ASSERT_EQ(200, res1->status);
  21355. ASSERT_TRUE(res1->has_header("ETag"));
  21356. std::string etag = res1->get_header_value("ETag");
  21357. EXPECT_FALSE(etag.empty());
  21358. // Verify ETag format: W/"hex-hex"
  21359. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21360. EXPECT_EQ('W', etag[0]);
  21361. EXPECT_EQ('/', etag[1]);
  21362. EXPECT_EQ('"', etag[2]);
  21363. EXPECT_EQ('"', etag.back());
  21364. // Exact match: expect 304 Not Modified
  21365. Headers h2 = {{"If-None-Match", etag}};
  21366. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21367. ASSERT_TRUE(res2);
  21368. EXPECT_EQ(304, res2->status);
  21369. // Wildcard match: expect 304 Not Modified
  21370. Headers h3 = {{"If-None-Match", "*"}};
  21371. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21372. ASSERT_TRUE(res3);
  21373. EXPECT_EQ(304, res3->status);
  21374. // Non-matching ETag: expect 200
  21375. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21376. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21377. ASSERT_TRUE(res4);
  21378. EXPECT_EQ(200, res4->status);
  21379. // Multiple ETags with one matching: expect 304
  21380. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21381. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21382. ASSERT_TRUE(res5);
  21383. EXPECT_EQ(304, res5->status);
  21384. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21385. // that equivalent to the single comma-separated list above, so the match on
  21386. // the second line must still be found.
  21387. Headers h6;
  21388. h6.emplace("If-None-Match", "W/\"other\"");
  21389. h6.emplace("If-None-Match", etag);
  21390. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21391. ASSERT_TRUE(res6);
  21392. EXPECT_EQ(304, res6->status);
  21393. svr.stop();
  21394. t.join();
  21395. std::remove(fname);
  21396. }
  21397. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21398. using namespace httplib;
  21399. Server svr;
  21400. svr.set_mount_point("/static", ".");
  21401. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21402. svr.wait_until_ready();
  21403. Client cli(HOST, PORT);
  21404. // Send If-None-Match: * to a non-existent file
  21405. Headers h = {{"If-None-Match", "*"}};
  21406. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21408. EXPECT_EQ(404, res->status);
  21409. svr.stop();
  21410. t.join();
  21411. }
  21412. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21413. using namespace httplib;
  21414. // Create a test file
  21415. const char *fname = "etag_boundary_testfile.txt";
  21416. const char *content = "boundary-test";
  21417. {
  21418. std::ofstream ofs(fname);
  21419. ofs << content;
  21420. ASSERT_TRUE(ofs.good());
  21421. }
  21422. Server svr;
  21423. svr.set_mount_point("/static", ".");
  21424. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21425. svr.wait_until_ready();
  21426. Client cli(HOST, PORT);
  21427. // Get the actual ETag
  21428. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21429. ASSERT_TRUE(res1);
  21430. ASSERT_EQ(200, res1->status);
  21431. ASSERT_TRUE(res1->has_header("ETag"));
  21432. std::string etag = res1->get_header_value("ETag");
  21433. // Test 1: Very long ETag value (longer than actual ETag)
  21434. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21435. Headers h1 = {{"If-None-Match", "W/"
  21436. "\"very-long-etag-value-that-is-much-longer-"
  21437. "than-the-actual-etag-value\""}};
  21438. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21439. ASSERT_TRUE(res2);
  21440. EXPECT_EQ(200, res2->status); // Should not match
  21441. // Test 2: Long string followed by wildcard
  21442. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21443. // string)
  21444. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21445. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21446. ASSERT_TRUE(res3);
  21447. EXPECT_EQ(304, res3->status); // Should match on "*"
  21448. // Test 3: Wildcard followed by long string
  21449. // Should match on "*" immediately and return 304
  21450. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21451. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21452. ASSERT_TRUE(res4);
  21453. EXPECT_EQ(304, res4->status); // Should match on "*"
  21454. // Test 4: Multiple long non-matching values
  21455. // Should NOT match and return 200 (test that all comparisons are safe)
  21456. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21457. "W/\"second-long-non-matching-value\", "
  21458. "W/\"third-long-non-matching-value\""}};
  21459. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21460. ASSERT_TRUE(res5);
  21461. EXPECT_EQ(200, res5->status); // Should not match
  21462. // Test 5: Single character that is not "*" (edge case)
  21463. Headers h5 = {{"If-None-Match", "X"}};
  21464. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21465. ASSERT_TRUE(res6);
  21466. EXPECT_EQ(200, res6->status); // Should not match
  21467. svr.stop();
  21468. t.join();
  21469. std::remove(fname);
  21470. }
  21471. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21472. using namespace httplib;
  21473. // Create a test file
  21474. const char *fname = "ims_testfile.txt";
  21475. const char *content = "if-modified-since-test";
  21476. {
  21477. std::ofstream ofs(fname);
  21478. ofs << content;
  21479. ASSERT_TRUE(ofs.good());
  21480. }
  21481. Server svr;
  21482. svr.set_mount_point("/static", ".");
  21483. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21484. svr.wait_until_ready();
  21485. Client cli(HOST, PORT);
  21486. // First request: should get 200 with Last-Modified header
  21487. auto res1 = cli.Get("/static/ims_testfile.txt");
  21488. ASSERT_TRUE(res1);
  21489. ASSERT_EQ(200, res1->status);
  21490. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21491. std::string last_modified = res1->get_header_value("Last-Modified");
  21492. EXPECT_FALSE(last_modified.empty());
  21493. // If-Modified-Since with same time: expect 304
  21494. Headers h2 = {{"If-Modified-Since", last_modified}};
  21495. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21496. ASSERT_TRUE(res2);
  21497. EXPECT_EQ(304, res2->status);
  21498. // If-Modified-Since with future time: expect 304
  21499. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21500. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21501. ASSERT_TRUE(res3);
  21502. EXPECT_EQ(304, res3->status);
  21503. // If-Modified-Since with past time: expect 200
  21504. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21505. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21506. ASSERT_TRUE(res4);
  21507. EXPECT_EQ(200, res4->status);
  21508. // If-None-Match takes precedence over If-Modified-Since
  21509. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21510. ASSERT_TRUE(res1->has_header("ETag"));
  21511. std::string etag = res1->get_header_value("ETag");
  21512. Headers h5 = {{"If-None-Match", etag},
  21513. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21514. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21515. ASSERT_TRUE(res5);
  21516. EXPECT_EQ(304, res5->status);
  21517. svr.stop();
  21518. t.join();
  21519. std::remove(fname);
  21520. }
  21521. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21522. using namespace httplib;
  21523. Server svr;
  21524. // Endpoint that returns compressible content
  21525. svr.Get("/compressible", [](const Request &, Response &res) {
  21526. // Return a large enough body to trigger compression
  21527. std::string body(1000, 'a');
  21528. res.set_content(body, "text/plain");
  21529. });
  21530. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21531. svr.wait_until_ready();
  21532. Client cli(HOST, PORT);
  21533. // Request with gzip support: should get Vary header when compressed
  21534. cli.set_compress(true);
  21535. auto res1 = cli.Get("/compressible");
  21536. ASSERT_TRUE(res1);
  21537. EXPECT_EQ(200, res1->status);
  21538. // If Content-Encoding is set, Vary should also be set
  21539. if (res1->has_header("Content-Encoding")) {
  21540. EXPECT_TRUE(res1->has_header("Vary"));
  21541. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21542. }
  21543. // Request without Accept-Encoding header: should not have compression
  21544. Headers h_no_compress;
  21545. auto res2 = cli.Get("/compressible", h_no_compress);
  21546. ASSERT_TRUE(res2);
  21547. EXPECT_EQ(200, res2->status);
  21548. // Verify Vary header is present when compression is applied
  21549. // (the exact behavior depends on server configuration)
  21550. svr.stop();
  21551. t.join();
  21552. }
  21553. TEST(ETagTest, IfRangeWithETag) {
  21554. using namespace httplib;
  21555. // Create a test file with known content
  21556. const char *fname = "if_range_testfile.txt";
  21557. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21558. {
  21559. std::ofstream ofs(fname);
  21560. ofs << content;
  21561. ASSERT_TRUE(ofs.good());
  21562. }
  21563. Server svr;
  21564. svr.set_mount_point("/static", ".");
  21565. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21566. svr.wait_until_ready();
  21567. Client cli(HOST, PORT);
  21568. // First request: get ETag
  21569. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21570. ASSERT_TRUE(res1);
  21571. ASSERT_EQ(200, res1->status);
  21572. ASSERT_TRUE(res1->has_header("ETag"));
  21573. std::string etag = res1->get_header_value("ETag");
  21574. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21575. // Since our server generates weak ETags (W/"..."), If-Range with our
  21576. // ETag should NOT result in partial content - it should return full content.
  21577. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21578. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21579. ASSERT_TRUE(res2);
  21580. // Weak ETag in If-Range -> full content (200), not partial (206)
  21581. EXPECT_EQ(200, res2->status);
  21582. EXPECT_EQ(content, res2->body);
  21583. EXPECT_FALSE(res2->has_header("Content-Range"));
  21584. // Range request with non-matching If-Range (ETag): should get 200 (full
  21585. // content)
  21586. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21587. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21588. ASSERT_TRUE(res3);
  21589. EXPECT_EQ(200, res3->status);
  21590. EXPECT_EQ(content, res3->body);
  21591. EXPECT_FALSE(res3->has_header("Content-Range"));
  21592. // Range request with strong ETag (hypothetical - our server doesn't generate
  21593. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21594. // should return full content)
  21595. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21596. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21597. ASSERT_TRUE(res4);
  21598. EXPECT_EQ(200, res4->status);
  21599. EXPECT_EQ(content, res4->body);
  21600. EXPECT_FALSE(res4->has_header("Content-Range"));
  21601. svr.stop();
  21602. t.join();
  21603. std::remove(fname);
  21604. }
  21605. TEST(ETagTest, IfRangeWithDate) {
  21606. using namespace httplib;
  21607. // Create a test file
  21608. const char *fname = "if_range_date_testfile.txt";
  21609. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21610. {
  21611. std::ofstream ofs(fname);
  21612. ofs << content;
  21613. ASSERT_TRUE(ofs.good());
  21614. }
  21615. Server svr;
  21616. svr.set_mount_point("/static", ".");
  21617. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21618. svr.wait_until_ready();
  21619. Client cli(HOST, PORT);
  21620. // First request: get Last-Modified
  21621. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21622. ASSERT_TRUE(res1);
  21623. ASSERT_EQ(200, res1->status);
  21624. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21625. std::string last_modified = res1->get_header_value("Last-Modified");
  21626. // Range request with matching If-Range (date): should get 206
  21627. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21628. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21629. ASSERT_TRUE(res2);
  21630. EXPECT_EQ(206, res2->status);
  21631. EXPECT_EQ("FGHIJ", res2->body);
  21632. // Range request with old If-Range date: should get 200 (full content)
  21633. Headers h3 = {{"Range", "bytes=5-9"},
  21634. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21635. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21636. ASSERT_TRUE(res3);
  21637. EXPECT_EQ(200, res3->status);
  21638. EXPECT_EQ(content, res3->body);
  21639. // Range request with future If-Range date: should get 206
  21640. Headers h4 = {{"Range", "bytes=0-4"},
  21641. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21642. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21643. ASSERT_TRUE(res4);
  21644. EXPECT_EQ(206, res4->status);
  21645. EXPECT_EQ("ABCDE", res4->body);
  21646. svr.stop();
  21647. t.join();
  21648. std::remove(fname);
  21649. }
  21650. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21651. using namespace httplib;
  21652. const char *fname = "etag_malformed.txt";
  21653. const char *content = "malformed-etag";
  21654. {
  21655. std::ofstream ofs(fname);
  21656. ofs << content;
  21657. ASSERT_TRUE(ofs.good());
  21658. }
  21659. Server svr;
  21660. svr.set_mount_point("/static", ".");
  21661. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21662. svr.wait_until_ready();
  21663. Client cli(HOST, PORT);
  21664. // baseline: should get 200 and an ETag
  21665. auto res1 = cli.Get("/static/etag_malformed.txt");
  21666. ASSERT_TRUE(res1);
  21667. ASSERT_EQ(200, res1->status);
  21668. ASSERT_TRUE(res1->has_header("ETag"));
  21669. // Malformed ETag value (missing quotes) should be treated as non-matching
  21670. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21671. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21672. ASSERT_TRUE(res_bad);
  21673. EXPECT_EQ(200, res_bad->status);
  21674. // Whitespace-only header value should be considered invalid / non-matching
  21675. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21676. "Host: localhost\r\n"
  21677. "If-None-Match: \r\n"
  21678. "Connection: close\r\n"
  21679. "\r\n";
  21680. std::string out;
  21681. ASSERT_TRUE(send_request(5, raw_req, &out));
  21682. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21683. svr.stop();
  21684. t.join();
  21685. std::remove(fname);
  21686. }
  21687. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21688. using namespace httplib;
  21689. const char *fname = "ims_invalid_format.txt";
  21690. const char *content = "ims-bad-format";
  21691. {
  21692. std::ofstream ofs(fname);
  21693. ofs << content;
  21694. ASSERT_TRUE(ofs.good());
  21695. }
  21696. Server svr;
  21697. svr.set_mount_point("/static", ".");
  21698. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21699. svr.wait_until_ready();
  21700. Client cli(HOST, PORT);
  21701. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21702. ASSERT_TRUE(res1);
  21703. ASSERT_EQ(200, res1->status);
  21704. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21705. // If-Modified-Since with invalid format should not result in 304
  21706. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21707. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21708. ASSERT_TRUE(res_bad);
  21709. EXPECT_EQ(200, res_bad->status);
  21710. // If-Range with invalid date format should be treated as mismatch -> full
  21711. // content (200)
  21712. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21713. {"If-Range", "invalid-date"}};
  21714. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21715. ASSERT_TRUE(res_ifrange);
  21716. EXPECT_EQ(200, res_ifrange->status);
  21717. svr.stop();
  21718. t.join();
  21719. std::remove(fname);
  21720. }
  21721. TEST(ETagTest, IfRangeWithMalformedETag) {
  21722. using namespace httplib;
  21723. const char *fname = "ifrange_malformed.txt";
  21724. const std::string content = "0123456789";
  21725. {
  21726. std::ofstream ofs(fname);
  21727. ofs << content;
  21728. ASSERT_TRUE(ofs.good());
  21729. }
  21730. Server svr;
  21731. svr.set_mount_point("/static", ".");
  21732. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21733. svr.wait_until_ready();
  21734. Client cli(HOST, PORT);
  21735. // First request: get ETag
  21736. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21737. ASSERT_TRUE(res1);
  21738. ASSERT_EQ(200, res1->status);
  21739. ASSERT_TRUE(res1->has_header("ETag"));
  21740. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21741. // full content (200)
  21742. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21743. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21744. ASSERT_TRUE(res2);
  21745. EXPECT_EQ(200, res2->status);
  21746. EXPECT_EQ(content, res2->body);
  21747. svr.stop();
  21748. t.join();
  21749. std::remove(fname);
  21750. }
  21751. TEST(ETagTest, ExtremeLargeDateValues) {
  21752. using namespace httplib;
  21753. const char *fname = "ims_extreme_date.txt";
  21754. const char *content = "ims-extreme-date";
  21755. {
  21756. std::ofstream ofs(fname);
  21757. ofs << content;
  21758. ASSERT_TRUE(ofs.good());
  21759. }
  21760. Server svr;
  21761. svr.set_mount_point("/static", ".");
  21762. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21763. svr.wait_until_ready();
  21764. Client cli(HOST, PORT);
  21765. auto res1 = cli.Get(std::string("/static/") + fname);
  21766. ASSERT_TRUE(res1);
  21767. ASSERT_EQ(200, res1->status);
  21768. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21769. // Extremely large year that may overflow date parsing routines.
  21770. Headers h_large_date = {
  21771. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21772. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21773. ASSERT_TRUE(res_bad);
  21774. // Expect server to treat this as invalid/mismatch and return full content
  21775. EXPECT_EQ(200, res_bad->status);
  21776. // If-Range with extremely large date should be treated as mismatch -> full
  21777. // content (200)
  21778. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21779. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21780. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21781. ASSERT_TRUE(res_ifrange);
  21782. EXPECT_EQ(200, res_ifrange->status);
  21783. svr.stop();
  21784. t.join();
  21785. std::remove(fname);
  21786. }
  21787. TEST(ETagTest, NegativeFileModificationTime) {
  21788. using namespace httplib;
  21789. const char *fname = "ims_negative_mtime.txt";
  21790. const std::string content = "negative-mtime";
  21791. {
  21792. std::ofstream ofs(fname);
  21793. ofs << content;
  21794. ASSERT_TRUE(ofs.good());
  21795. }
  21796. // Try to set file mtime to a negative value. This may fail on some
  21797. // platforms/filesystems; if it fails, the test will still verify server
  21798. // behaves safely by performing a regular conditional request.
  21799. #if defined(__APPLE__) || defined(__linux__)
  21800. bool set_negative = false;
  21801. do {
  21802. struct timeval times[2];
  21803. // access time: now
  21804. times[0].tv_sec = time(nullptr);
  21805. times[0].tv_usec = 0;
  21806. // modification time: negative (e.g., -1)
  21807. times[1].tv_sec = -1;
  21808. times[1].tv_usec = 0;
  21809. if (utimes(fname, times) == 0) { set_negative = true; }
  21810. } while (0);
  21811. #else
  21812. bool set_negative = false;
  21813. #endif
  21814. Server svr;
  21815. svr.set_mount_point("/static", ".");
  21816. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21817. svr.wait_until_ready();
  21818. Client cli(HOST, PORT);
  21819. auto res1 = cli.Get(std::string("/static/") + fname);
  21820. ASSERT_TRUE(res1);
  21821. ASSERT_EQ(200, res1->status);
  21822. bool has_last_modified = res1->has_header("Last-Modified");
  21823. std::string last_modified;
  21824. if (has_last_modified) {
  21825. last_modified = res1->get_header_value("Last-Modified");
  21826. }
  21827. if (set_negative) {
  21828. // If we successfully set a negative mtime, ensure server returns a
  21829. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21830. // with an old date and ensure server handles it without crash.
  21831. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21832. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21833. ASSERT_TRUE(res2);
  21834. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21835. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21836. } else {
  21837. // Could not set negative mtime on this platform; fall back to verifying
  21838. // that normal invalid/malformed dates are treated safely (non-304).
  21839. Headers h_bad_date = {
  21840. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21841. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21842. ASSERT_TRUE(res_bad);
  21843. EXPECT_EQ(200, res_bad->status);
  21844. }
  21845. svr.stop();
  21846. t.join();
  21847. std::remove(fname);
  21848. }
  21849. //==============================================================================
  21850. // Integration Tests with Server
  21851. //==============================================================================
  21852. class SSEIntegrationTest : public ::testing::Test {
  21853. protected:
  21854. void SetUp() override {
  21855. stop_server_.store(false);
  21856. events_.clear();
  21857. server_ = httplib::detail::make_unique<Server>();
  21858. setup_server();
  21859. start_server();
  21860. }
  21861. void TearDown() override {
  21862. stop_server_.store(true);
  21863. event_cv_.notify_all();
  21864. server_->stop();
  21865. if (server_thread_.joinable()) { server_thread_.join(); }
  21866. }
  21867. void setup_server() {
  21868. // Simple SSE endpoint
  21869. server_->Get("/events", [this](const Request &req, Response &res) {
  21870. auto last_id = req.get_header_value("Last-Event-ID");
  21871. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21872. res.set_chunked_content_provider(
  21873. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21874. std::unique_lock<std::mutex> lock(event_mutex_);
  21875. if (event_cv_.wait_for(
  21876. lock, std::chrono::milliseconds(200), [this] {
  21877. return !events_.empty() || stop_server_.load();
  21878. })) {
  21879. if (stop_server_.load()) { return false; }
  21880. if (!events_.empty()) {
  21881. std::string event = events_.front();
  21882. events_.erase(events_.begin());
  21883. sink.write(event.data(), event.size());
  21884. return true;
  21885. }
  21886. }
  21887. return !stop_server_.load();
  21888. });
  21889. });
  21890. // Endpoint that returns error
  21891. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21892. res.status = 500;
  21893. res.set_content("Internal Server Error", "text/plain");
  21894. });
  21895. // Endpoint for custom event types
  21896. server_->Get("/custom-events", [](const Request &, Response &res) {
  21897. res.set_chunked_content_provider(
  21898. "text/event-stream", [](size_t offset, DataSink &sink) {
  21899. if (offset == 0) {
  21900. std::string event = "event: update\ndata: updated\n\n"
  21901. "event: delete\ndata: deleted\n\n";
  21902. sink.write(event.data(), event.size());
  21903. }
  21904. return false; // End stream after sending
  21905. });
  21906. });
  21907. }
  21908. void start_server() {
  21909. port_ = server_->bind_to_any_port(HOST);
  21910. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21911. // Wait for server to start
  21912. while (!server_->is_running()) {
  21913. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21914. }
  21915. }
  21916. int get_port() const { return port_; }
  21917. void send_event(const std::string &event) {
  21918. std::lock_guard<std::mutex> lock(event_mutex_);
  21919. events_.push_back(event);
  21920. event_cv_.notify_all();
  21921. }
  21922. std::unique_ptr<Server> server_;
  21923. std::thread server_thread_;
  21924. std::mutex event_mutex_;
  21925. std::condition_variable event_cv_;
  21926. std::vector<std::string> events_;
  21927. std::atomic<bool> stop_server_{false};
  21928. std::string last_received_event_id_;
  21929. int port_ = 0;
  21930. };
  21931. //==============================================================================
  21932. // SSE Parsing Tests
  21933. //==============================================================================
  21934. class SSEParsingTest : public SSEIntegrationTest {
  21935. protected:
  21936. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21937. // A trailing sentinel event tells when the whole stream has been parsed.
  21938. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21939. auto body = stream + "event: end\ndata: end\n\n";
  21940. server_->Get("/parse", [body](const Request &, Response &res) {
  21941. res.set_content(body, "text/event-stream");
  21942. });
  21943. return collect("/parse");
  21944. }
  21945. // Runs SSEClient against path until an "end" event arrives and returns the
  21946. // messages dispatched before it
  21947. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21948. Client client(HOST, get_port());
  21949. sse::SSEClient sse(client, path);
  21950. std::mutex mutex;
  21951. std::condition_variable cv;
  21952. std::vector<sse::SSEMessage> messages;
  21953. auto done = false;
  21954. sse.on_message([&](const sse::SSEMessage &msg) {
  21955. std::lock_guard<std::mutex> lock(mutex);
  21956. // Ignore a replay from a reconnect that races with stop()
  21957. if (!done) { messages.push_back(msg); }
  21958. });
  21959. sse.on_event("end", [&](const sse::SSEMessage &) {
  21960. std::lock_guard<std::mutex> lock(mutex);
  21961. done = true;
  21962. cv.notify_all();
  21963. });
  21964. sse.set_reconnect_interval(100);
  21965. sse.start_async();
  21966. {
  21967. std::unique_lock<std::mutex> lock(mutex);
  21968. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21969. }
  21970. sse.stop();
  21971. EXPECT_TRUE(done);
  21972. return messages;
  21973. }
  21974. };
  21975. TEST_F(SSEParsingTest, SingleLineData) {
  21976. auto msgs = parse("data: hello\n\n");
  21977. ASSERT_EQ(msgs.size(), 1u);
  21978. EXPECT_EQ(msgs[0].data, "hello");
  21979. EXPECT_EQ(msgs[0].event, "message");
  21980. }
  21981. TEST_F(SSEParsingTest, MultiLineData) {
  21982. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21983. ASSERT_EQ(msgs.size(), 1u);
  21984. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21985. }
  21986. TEST_F(SSEParsingTest, CustomEventType) {
  21987. auto msgs = parse("event: update\ndata: payload\n\n");
  21988. ASSERT_EQ(msgs.size(), 1u);
  21989. EXPECT_EQ(msgs[0].event, "update");
  21990. EXPECT_EQ(msgs[0].data, "payload");
  21991. }
  21992. TEST_F(SSEParsingTest, EventIdHandling) {
  21993. auto msgs = parse("id: 12345\ndata: test\n\n");
  21994. ASSERT_EQ(msgs.size(), 1u);
  21995. EXPECT_EQ(msgs[0].id, "12345");
  21996. }
  21997. TEST_F(SSEParsingTest, EmptyEventId) {
  21998. auto msgs = parse("id:\ndata: test\n\n");
  21999. ASSERT_EQ(msgs.size(), 1u);
  22000. EXPECT_EQ(msgs[0].id, "");
  22001. }
  22002. TEST_F(SSEParsingTest, CommentsIgnored) {
  22003. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  22004. ASSERT_EQ(msgs.size(), 1u);
  22005. EXPECT_EQ(msgs[0].data, "hello");
  22006. EXPECT_EQ(msgs[0].event, "message");
  22007. }
  22008. TEST_F(SSEParsingTest, ColonInValue) {
  22009. auto msgs = parse("data: hello:world:test\n\n");
  22010. ASSERT_EQ(msgs.size(), 1u);
  22011. EXPECT_EQ(msgs[0].data, "hello:world:test");
  22012. }
  22013. TEST_F(SSEParsingTest, FieldNameOnly) {
  22014. // A line without a colon is a field name with an empty value
  22015. auto msgs = parse("data\n\n");
  22016. ASSERT_EQ(msgs.size(), 1u);
  22017. EXPECT_EQ(msgs[0].data, "");
  22018. }
  22019. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  22020. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  22021. ASSERT_EQ(msgs.size(), 1u);
  22022. EXPECT_EQ(msgs[0].event, "update");
  22023. EXPECT_EQ(msgs[0].data, "hello");
  22024. }
  22025. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  22026. auto msgs = parse("data\r\n\r\n");
  22027. ASSERT_EQ(msgs.size(), 1u);
  22028. EXPECT_EQ(msgs[0].data, "");
  22029. }
  22030. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  22031. auto msgs = parse("event: update\rdata: hello\r\r");
  22032. ASSERT_EQ(msgs.size(), 1u);
  22033. EXPECT_EQ(msgs[0].event, "update");
  22034. EXPECT_EQ(msgs[0].data, "hello");
  22035. }
  22036. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  22037. // Chunk boundaries fall inside every \r\n and right before the first one
  22038. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  22039. "\n\r", "\nevent: end\ndata: end\n\n"};
  22040. server_->Get("/split", [chunks](const Request &, Response &res) {
  22041. auto i = std::make_shared<size_t>(0);
  22042. res.set_chunked_content_provider(
  22043. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  22044. if (*i == chunks.size()) {
  22045. sink.done();
  22046. } else {
  22047. sink.write(chunks[*i].data(), chunks[*i].size());
  22048. (*i)++;
  22049. }
  22050. return true;
  22051. });
  22052. });
  22053. auto msgs = collect("/split");
  22054. ASSERT_EQ(msgs.size(), 1u);
  22055. EXPECT_EQ(msgs[0].event, "update");
  22056. EXPECT_EQ(msgs[0].data, "hello");
  22057. }
  22058. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  22059. // Only a BOM at the start of the stream is ignored
  22060. auto msgs = parse("\xEF\xBB\xBF"
  22061. "data: first\n\n"
  22062. "\xEF\xBB\xBF"
  22063. "data: second\n\n");
  22064. ASSERT_EQ(msgs.size(), 1u);
  22065. EXPECT_EQ(msgs[0].data, "first");
  22066. }
  22067. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  22068. auto msgs = parse("unknown: value\ndata: hello\n\n");
  22069. ASSERT_EQ(msgs.size(), 1u);
  22070. EXPECT_EQ(msgs[0].data, "hello");
  22071. EXPECT_EQ(msgs[0].event, "message");
  22072. }
  22073. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  22074. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  22075. ASSERT_EQ(msgs.size(), 2u);
  22076. EXPECT_EQ(msgs[0].data, "hello");
  22077. EXPECT_EQ(msgs[1].data, "hello");
  22078. }
  22079. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  22080. // An event without data is not dispatched, and its type must not leak
  22081. // into the next event
  22082. auto msgs = parse("event: update\n\ndata: hello\n\n");
  22083. ASSERT_EQ(msgs.size(), 1u);
  22084. EXPECT_EQ(msgs[0].event, "message");
  22085. EXPECT_EQ(msgs[0].data, "hello");
  22086. }
  22087. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  22088. // Also when the empty field replaces an earlier type
  22089. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  22090. ASSERT_EQ(msgs.size(), 2u);
  22091. EXPECT_EQ(msgs[0].event, "message");
  22092. EXPECT_EQ(msgs[1].event, "message");
  22093. }
  22094. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  22095. // The first connection sends only an id; the second echoes back the
  22096. // Last-Event-ID it was reconnected with
  22097. std::atomic<int> connection_count{0};
  22098. server_->Get("/id-only", [&](const Request &req, Response &res) {
  22099. if (connection_count++ == 0) {
  22100. res.set_content("id: 42\n\n", "text/event-stream");
  22101. } else {
  22102. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22103. "\n\nevent: end\ndata: end\n\n",
  22104. "text/event-stream");
  22105. }
  22106. });
  22107. auto msgs = collect("/id-only");
  22108. ASSERT_EQ(msgs.size(), 1u);
  22109. EXPECT_EQ(msgs[0].data, "42");
  22110. }
  22111. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  22112. // The first connection sets an id and then clears it with an empty one; the
  22113. // second reports whether it was reconnected with a Last-Event-ID
  22114. std::atomic<int> connection_count{0};
  22115. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  22116. if (connection_count++ == 0) {
  22117. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  22118. "text/event-stream");
  22119. } else {
  22120. res.set_content(
  22121. std::string("data: ") +
  22122. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  22123. "\n\nevent: end\ndata: end\n\n",
  22124. "text/event-stream");
  22125. }
  22126. });
  22127. auto msgs = collect("/id-clear");
  22128. ASSERT_EQ(msgs.size(), 3u);
  22129. EXPECT_EQ(msgs[0].id, "1");
  22130. EXPECT_EQ(msgs[1].id, "");
  22131. EXPECT_EQ(msgs[2].data, "not sent");
  22132. }
  22133. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  22134. // The first connection sets an id and then sends ids that cannot be carried
  22135. // in a header; the second echoes back the Last-Event-ID it was reconnected
  22136. // with
  22137. std::atomic<int> connection_count{0};
  22138. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  22139. if (connection_count++ == 0) {
  22140. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  22141. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  22142. "text/event-stream");
  22143. } else {
  22144. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  22145. "\n\nevent: end\ndata: end\n\n",
  22146. "text/event-stream");
  22147. }
  22148. });
  22149. auto msgs = collect("/id-unsendable");
  22150. ASSERT_EQ(msgs.size(), 1u);
  22151. EXPECT_EQ(msgs[0].data, "42");
  22152. }
  22153. TEST_F(SSEParsingTest, CompleteEventParsing) {
  22154. auto msgs = parse("event: notification\nid: evt-42\n"
  22155. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  22156. ASSERT_EQ(msgs.size(), 1u);
  22157. EXPECT_EQ(msgs[0].event, "notification");
  22158. EXPECT_EQ(msgs[0].id, "evt-42");
  22159. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  22160. }
  22161. TEST(SSEMessageTest, Clear) {
  22162. sse::SSEMessage msg;
  22163. msg.event = "custom";
  22164. msg.data = "some data";
  22165. msg.id = "123";
  22166. msg.clear();
  22167. EXPECT_EQ(msg.event, "message");
  22168. EXPECT_EQ(msg.data, "");
  22169. EXPECT_EQ(msg.id, "");
  22170. }
  22171. //==============================================================================
  22172. // SSE Integration Tests
  22173. //==============================================================================
  22174. // Test: Successful connection and on_open callback
  22175. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  22176. // Add a simple endpoint that sends one event and closes
  22177. server_->Get("/simple-event", [](const Request &, Response &res) {
  22178. res.set_chunked_content_provider(
  22179. "text/event-stream", [](size_t offset, DataSink &sink) {
  22180. if (offset == 0) {
  22181. std::string event = "data: hello\n\n";
  22182. sink.write(event.data(), event.size());
  22183. }
  22184. return false; // Close stream after sending
  22185. });
  22186. });
  22187. Client client("localhost", get_port());
  22188. sse::SSEClient sse(client, "/simple-event");
  22189. std::atomic<bool> open_called{false};
  22190. std::atomic<bool> message_received{false};
  22191. sse.on_open([&open_called]() { open_called.store(true); });
  22192. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  22193. if (msg.data == "hello") { message_received.store(true); }
  22194. });
  22195. sse.set_reconnect_interval(100);
  22196. sse.set_max_reconnect_attempts(1);
  22197. // Start async
  22198. sse.start_async();
  22199. // Wait for message to be processed
  22200. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22201. sse.stop();
  22202. EXPECT_TRUE(open_called.load());
  22203. EXPECT_TRUE(message_received.load());
  22204. }
  22205. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  22206. // A data line that never ends.
  22207. server_->Get("/endless-line", [](const Request &, Response &res) {
  22208. res.set_chunked_content_provider(
  22209. "text/event-stream", [](size_t offset, DataSink &sink) {
  22210. if (offset == 0) { sink.write("data: ", 6); }
  22211. std::string chunk(64 * 1024, 'A');
  22212. return sink.write(chunk.data(), chunk.size());
  22213. });
  22214. });
  22215. Client client("localhost", get_port());
  22216. sse::SSEClient sse(client, "/endless-line");
  22217. std::atomic<bool> too_long{false};
  22218. sse.on_error([&](Error err) {
  22219. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  22220. });
  22221. sse.set_max_reconnect_attempts(1);
  22222. sse.start_async();
  22223. for (int i = 0; i < 500 && !too_long; i++) {
  22224. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22225. }
  22226. sse.stop();
  22227. EXPECT_TRUE(too_long);
  22228. }
  22229. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  22230. // Far more in all than the client's payload limit below.
  22231. server_->Get("/many-events", [](const Request &, Response &res) {
  22232. res.set_chunked_content_provider(
  22233. "text/event-stream", [](size_t offset, DataSink &sink) {
  22234. if (offset == 0) {
  22235. std::string events;
  22236. for (int i = 0; i < 1000; i++) {
  22237. events += "data: message\n\n";
  22238. }
  22239. sink.write(events.data(), events.size());
  22240. }
  22241. return false;
  22242. });
  22243. });
  22244. Client client("localhost", get_port());
  22245. client.set_payload_max_length(1024);
  22246. sse::SSEClient sse(client, "/many-events");
  22247. std::atomic<int> messages{0};
  22248. std::atomic<bool> too_large{false};
  22249. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  22250. sse.on_error([&](Error err) {
  22251. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  22252. });
  22253. sse.set_max_reconnect_attempts(1);
  22254. sse.start_async();
  22255. for (int i = 0; i < 500 && messages < 1000; i++) {
  22256. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22257. }
  22258. sse.stop();
  22259. EXPECT_GE(messages.load(), 1000);
  22260. EXPECT_FALSE(too_large);
  22261. }
  22262. // Test: on_message callback
  22263. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  22264. // Endpoint that sends multiple events then closes
  22265. server_->Get("/multi-event", [](const Request &, Response &res) {
  22266. res.set_chunked_content_provider(
  22267. "text/event-stream", [](size_t offset, DataSink &sink) {
  22268. if (offset == 0) {
  22269. std::string events = "data: message1\n\ndata: message2\n\n";
  22270. sink.write(events.data(), events.size());
  22271. }
  22272. return false;
  22273. });
  22274. });
  22275. Client client("localhost", get_port());
  22276. sse::SSEClient sse(client, "/multi-event");
  22277. std::vector<std::string> received_messages;
  22278. std::mutex messages_mutex;
  22279. sse.on_message([&](const sse::SSEMessage &msg) {
  22280. std::lock_guard<std::mutex> lock(messages_mutex);
  22281. received_messages.push_back(msg.data);
  22282. });
  22283. sse.set_reconnect_interval(100);
  22284. sse.set_max_reconnect_attempts(1);
  22285. sse.start_async();
  22286. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22287. sse.stop();
  22288. std::lock_guard<std::mutex> lock(messages_mutex);
  22289. EXPECT_GE(received_messages.size(), 2u);
  22290. if (received_messages.size() >= 2) {
  22291. EXPECT_EQ(received_messages[0], "message1");
  22292. EXPECT_EQ(received_messages[1], "message2");
  22293. }
  22294. }
  22295. // Test: on_event for specific types
  22296. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  22297. Client client("localhost", get_port());
  22298. sse::SSEClient sse(client, "/custom-events");
  22299. std::atomic<bool> update_received{false};
  22300. std::atomic<bool> delete_received{false};
  22301. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  22302. if (msg.data == "updated") { update_received.store(true); }
  22303. });
  22304. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  22305. if (msg.data == "deleted") { delete_received.store(true); }
  22306. });
  22307. sse.set_max_reconnect_attempts(1);
  22308. sse.start_async();
  22309. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  22310. sse.stop();
  22311. EXPECT_TRUE(update_received.load());
  22312. EXPECT_TRUE(delete_received.load());
  22313. }
  22314. // Test: on_error callback on connection failure
  22315. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  22316. // Connect to a non-existent port
  22317. Client client("localhost", 59999);
  22318. sse::SSEClient sse(client, "/events");
  22319. std::atomic<bool> error_called{false};
  22320. Error received_error = Error::Success;
  22321. sse.on_error([&](Error err) {
  22322. error_called.store(true);
  22323. received_error = err;
  22324. });
  22325. sse.set_reconnect_interval(50);
  22326. sse.set_max_reconnect_attempts(1);
  22327. sse.start_async();
  22328. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22329. sse.stop();
  22330. EXPECT_TRUE(error_called.load());
  22331. EXPECT_NE(received_error, Error::Success);
  22332. }
  22333. // Test: Last-Event-ID header sent on reconnect
  22334. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22335. // Endpoint that sends event with ID
  22336. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22337. res.set_chunked_content_provider(
  22338. "text/event-stream", [](size_t offset, DataSink &sink) {
  22339. if (offset == 0) {
  22340. std::string event = "id: evt-123\ndata: test\n\n";
  22341. sink.write(event.data(), event.size());
  22342. }
  22343. return false;
  22344. });
  22345. });
  22346. Client client("localhost", get_port());
  22347. sse::SSEClient sse(client, "/event-with-id");
  22348. std::atomic<bool> id_received{false};
  22349. sse.on_message([&](const sse::SSEMessage &msg) {
  22350. if (!msg.id.empty()) { id_received.store(true); }
  22351. });
  22352. sse.set_reconnect_interval(100);
  22353. sse.set_max_reconnect_attempts(1);
  22354. sse.start_async();
  22355. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22356. sse.stop();
  22357. EXPECT_TRUE(id_received.load());
  22358. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22359. }
  22360. // Test: last_event_id() read from another thread while start_async() runs
  22361. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  22362. // Ids of every length up to 200, so the stored id keeps changing size
  22363. server_->Get("/many-ids", [](const Request &, Response &res) {
  22364. res.set_chunked_content_provider(
  22365. "text/event-stream", [](size_t offset, DataSink &sink) {
  22366. if (offset == 0) {
  22367. std::string events;
  22368. for (size_t i = 0; i < 2000; i++) {
  22369. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  22370. events += "data: x\n\n";
  22371. }
  22372. events += "id: end\ndata: x\n\n";
  22373. sink.write(events.data(), events.size());
  22374. }
  22375. return false;
  22376. });
  22377. });
  22378. Client client("localhost", get_port());
  22379. sse::SSEClient sse(client, "/many-ids");
  22380. // Wait out the rest of the test rather than replay the stream
  22381. sse.set_reconnect_interval(10000);
  22382. sse.set_max_reconnect_attempts(1);
  22383. sse.start_async();
  22384. auto well_formed = true;
  22385. std::string id;
  22386. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  22387. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  22388. id = sse.last_event_id();
  22389. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  22390. well_formed = false;
  22391. }
  22392. }
  22393. sse.stop();
  22394. EXPECT_TRUE(well_formed);
  22395. EXPECT_EQ(sse.last_event_id(), "end");
  22396. }
  22397. // Test: Manual stop
  22398. TEST_F(SSEIntegrationTest, ManualStop) {
  22399. // Endpoint that sends one event and stays open briefly. The server outlives
  22400. // this test body, so the provider uses the fixture's flag, not a local.
  22401. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22402. res.set_chunked_content_provider(
  22403. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22404. if (offset == 0) {
  22405. std::string event = "data: connected\n\n";
  22406. sink.write(event.data(), event.size());
  22407. }
  22408. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22409. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22410. }
  22411. return false;
  22412. });
  22413. });
  22414. Client client("localhost", get_port());
  22415. sse::SSEClient sse(client, "/stay-open");
  22416. std::atomic<bool> connected{false};
  22417. sse.on_open([&connected]() { connected.store(true); });
  22418. sse.set_reconnect_interval(100);
  22419. sse.set_max_reconnect_attempts(1);
  22420. sse.start_async();
  22421. // Wait for connection to establish
  22422. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22423. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22424. }
  22425. EXPECT_TRUE(connected.load());
  22426. EXPECT_TRUE(sse.is_connected());
  22427. // Signal handler to stop
  22428. stop_server_.store(true);
  22429. // Stop SSE client
  22430. sse.stop();
  22431. EXPECT_FALSE(sse.is_connected());
  22432. }
  22433. // Sends one event, then nothing until stop is set
  22434. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22435. return [&stop](const Request &, Response &res) {
  22436. res.set_chunked_content_provider(
  22437. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22438. if (offset == 0) {
  22439. std::string event = "data: hello\n\n";
  22440. sink.write(event.data(), event.size());
  22441. }
  22442. while (!stop.load()) {
  22443. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22444. }
  22445. return false;
  22446. });
  22447. };
  22448. }
  22449. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22450. static void check_stop_interrupts_blocked_read(Client &client) {
  22451. client.set_read_timeout(30, 0);
  22452. for (auto by_destructor : {false, true}) {
  22453. std::atomic<bool> received{false};
  22454. std::chrono::steady_clock::time_point start;
  22455. {
  22456. sse::SSEClient sse(client, "/idle-stream");
  22457. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22458. sse.start_async();
  22459. for (int i = 0; i < 500 && !received.load(); ++i) {
  22460. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22461. }
  22462. ASSERT_TRUE(received.load());
  22463. // Let the client block in the next read
  22464. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22465. start = std::chrono::steady_clock::now();
  22466. if (!by_destructor) { sse.stop(); }
  22467. }
  22468. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22469. std::chrono::seconds(2));
  22470. }
  22471. }
  22472. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22473. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22474. Client client("localhost", get_port());
  22475. check_stop_interrupts_blocked_read(client);
  22476. }
  22477. #ifdef CPPHTTPLIB_SSL_ENABLED
  22478. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22479. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22480. std::atomic<bool> done{false};
  22481. svr.Get("/idle-stream", idle_event_stream(done));
  22482. auto port = svr.bind_to_any_port(HOST);
  22483. std::thread t([&] { svr.listen_after_bind(); });
  22484. auto se = detail::scope_exit([&] {
  22485. done.store(true);
  22486. svr.stop();
  22487. t.join();
  22488. });
  22489. svr.wait_until_ready();
  22490. Client client("https://localhost:" + std::to_string(port));
  22491. client.enable_server_certificate_verification(false);
  22492. check_stop_interrupts_blocked_read(client);
  22493. }
  22494. #endif
  22495. // Test: SSEClient with custom headers
  22496. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22497. // Setup a server endpoint that checks for custom header
  22498. std::atomic<bool> header_received{false};
  22499. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22500. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22501. header_received.store(true);
  22502. }
  22503. res.set_chunked_content_provider("text/event-stream",
  22504. [](size_t, DataSink &) { return false; });
  22505. });
  22506. Client client("localhost", get_port());
  22507. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22508. sse::SSEClient sse(client, "/header-check", headers);
  22509. sse.set_max_reconnect_attempts(1);
  22510. sse.start_async();
  22511. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22512. sse.stop();
  22513. EXPECT_TRUE(header_received.load());
  22514. }
  22515. // Test: Reconnect interval configuration
  22516. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22517. Client client("localhost", get_port());
  22518. sse::SSEClient sse(client, "/events");
  22519. auto &result = sse.set_reconnect_interval(500);
  22520. // Builder pattern should return reference to self
  22521. EXPECT_EQ(&result, &sse);
  22522. }
  22523. // Test: Max reconnect attempts
  22524. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22525. // Connect to non-existent port to force reconnects
  22526. Client client("localhost", 59998);
  22527. sse::SSEClient sse(client, "/events");
  22528. std::atomic<int> error_count{0};
  22529. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22530. sse.set_reconnect_interval(50);
  22531. sse.set_max_reconnect_attempts(2);
  22532. auto start = std::chrono::steady_clock::now();
  22533. sse.start(); // Blocking call
  22534. auto end = std::chrono::steady_clock::now();
  22535. // Should have stopped after 2 failed attempts
  22536. EXPECT_GE(error_count.load(), 2);
  22537. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22538. auto duration =
  22539. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22540. #ifdef _WIN32
  22541. // Windows is much slower for socket connection failures
  22542. EXPECT_LT(duration.count(), 7000);
  22543. #else
  22544. EXPECT_LT(duration.count(), 1000);
  22545. #endif
  22546. }
  22547. // Test: Multi-line data in integration
  22548. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22549. // Endpoint with multi-line data
  22550. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22551. res.set_chunked_content_provider(
  22552. "text/event-stream", [](size_t offset, DataSink &sink) {
  22553. if (offset == 0) {
  22554. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22555. sink.write(event.data(), event.size());
  22556. }
  22557. return false;
  22558. });
  22559. });
  22560. Client client("localhost", get_port());
  22561. sse::SSEClient sse(client, "/multiline-data");
  22562. std::string received_data;
  22563. std::mutex data_mutex;
  22564. sse.on_message([&](const sse::SSEMessage &msg) {
  22565. std::lock_guard<std::mutex> lock(data_mutex);
  22566. received_data = msg.data;
  22567. });
  22568. sse.set_reconnect_interval(100);
  22569. sse.set_max_reconnect_attempts(1);
  22570. sse.start_async();
  22571. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22572. sse.stop();
  22573. std::lock_guard<std::mutex> lock(data_mutex);
  22574. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22575. }
  22576. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22577. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22578. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22579. DataSink &sink) {
  22580. if (offset == 0) {
  22581. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22582. sink.write(events.data(), events.size());
  22583. }
  22584. return false;
  22585. });
  22586. });
  22587. Client client("localhost", get_port());
  22588. sse::SSEClient sse(client, "/empty-data-lines");
  22589. std::mutex mutex;
  22590. std::condition_variable cv;
  22591. std::vector<std::string> received;
  22592. sse.on_message([&](const sse::SSEMessage &msg) {
  22593. std::lock_guard<std::mutex> lock(mutex);
  22594. received.push_back(msg.data);
  22595. cv.notify_all();
  22596. });
  22597. sse.set_max_reconnect_attempts(1);
  22598. sse.start_async();
  22599. {
  22600. std::unique_lock<std::mutex> lock(mutex);
  22601. cv.wait_for(lock, std::chrono::seconds(2),
  22602. [&] { return received.size() >= 3; });
  22603. }
  22604. sse.stop();
  22605. ASSERT_GE(received.size(), 3u);
  22606. EXPECT_EQ(received[0], "");
  22607. EXPECT_EQ(received[1], "\nhello");
  22608. EXPECT_EQ(received[2], "");
  22609. }
  22610. // Test: Auto-reconnect after server disconnection
  22611. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22612. std::atomic<int> connection_count{0};
  22613. std::atomic<int> message_count{0};
  22614. // Endpoint that sends one event and closes, forcing reconnect
  22615. server_->Get("/reconnect-test",
  22616. [&connection_count](const Request &, Response &res) {
  22617. connection_count.fetch_add(1);
  22618. res.set_chunked_content_provider(
  22619. "text/event-stream", [](size_t offset, DataSink &sink) {
  22620. if (offset == 0) {
  22621. std::string event = "data: hello\n\n";
  22622. sink.write(event.data(), event.size());
  22623. }
  22624. return false; // Close connection after sending
  22625. });
  22626. });
  22627. Client client("localhost", get_port());
  22628. sse::SSEClient sse(client, "/reconnect-test");
  22629. sse.on_message([&message_count](const sse::SSEMessage &) {
  22630. message_count.fetch_add(1);
  22631. });
  22632. sse.set_reconnect_interval(100);
  22633. sse.set_max_reconnect_attempts(3);
  22634. sse.start_async();
  22635. // Wait long enough for multiple reconnects
  22636. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22637. sse.stop();
  22638. // Should have connected multiple times (initial + reconnects)
  22639. EXPECT_GE(connection_count.load(), 2);
  22640. // Should have received messages from multiple connections
  22641. EXPECT_GE(message_count.load(), 2);
  22642. }
  22643. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22644. std::atomic<int> connection_count{0};
  22645. // Neither Content-Length nor chunked: the close ends the stream
  22646. server_->Get("/close-delimited",
  22647. [&connection_count](const Request &, Response &res) {
  22648. connection_count.fetch_add(1);
  22649. res.set_content_provider(
  22650. "text/event-stream", [](size_t offset, DataSink &sink) {
  22651. if (offset == 0) {
  22652. std::string event = "data: hello\n\n";
  22653. sink.write(event.data(), event.size());
  22654. } else {
  22655. sink.done();
  22656. }
  22657. return true;
  22658. });
  22659. });
  22660. Client client("localhost", get_port());
  22661. sse::SSEClient sse(client, "/close-delimited");
  22662. std::atomic<int> error_count{0};
  22663. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22664. sse.set_reconnect_interval(100);
  22665. sse.start_async();
  22666. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22667. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22668. }
  22669. sse.stop();
  22670. // Reconnects as after any end of the stream, but reports no error
  22671. EXPECT_GE(connection_count.load(), 2);
  22672. EXPECT_EQ(0, error_count.load());
  22673. }
  22674. // Test: A retry field that is not all ASCII digits is ignored
  22675. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22676. std::atomic<int> connection_count{0};
  22677. server_->Get("/bad-retry",
  22678. [&connection_count](const Request &, Response &res) {
  22679. connection_count.fetch_add(1);
  22680. res.set_chunked_content_provider(
  22681. "text/event-stream", [](size_t offset, DataSink &sink) {
  22682. if (offset == 0) {
  22683. std::string event = "retry: -1\ndata: hello\n\n";
  22684. sink.write(event.data(), event.size());
  22685. }
  22686. return false;
  22687. });
  22688. });
  22689. Client client("localhost", get_port());
  22690. sse::SSEClient sse(client, "/bad-retry");
  22691. sse.set_reconnect_interval(10000);
  22692. sse.start_async();
  22693. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22694. sse.stop();
  22695. EXPECT_EQ(connection_count.load(), 1);
  22696. }
  22697. // Test: A retry field of all ASCII digits sets the reconnection time
  22698. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22699. std::mutex mutex;
  22700. std::condition_variable cv;
  22701. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22702. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22703. {
  22704. std::lock_guard<std::mutex> lock(mutex);
  22705. connected_at.push_back(std::chrono::steady_clock::now());
  22706. cv.notify_all();
  22707. }
  22708. res.set_chunked_content_provider(
  22709. "text/event-stream", [](size_t offset, DataSink &sink) {
  22710. if (offset == 0) {
  22711. std::string event = "retry: 0\ndata: hello\n\n";
  22712. sink.write(event.data(), event.size());
  22713. }
  22714. return false;
  22715. });
  22716. });
  22717. Client client("localhost", get_port());
  22718. sse::SSEClient sse(client, "/zero-retry");
  22719. sse.set_reconnect_interval(10000);
  22720. sse.start_async();
  22721. {
  22722. std::unique_lock<std::mutex> lock(mutex);
  22723. cv.wait_for(lock, std::chrono::seconds(5),
  22724. [&] { return connected_at.size() >= 2; });
  22725. }
  22726. sse.stop();
  22727. // The server-supplied interval is applied, but never below 100ms, so
  22728. // "retry: 0" does not cause a busy reconnect loop
  22729. std::lock_guard<std::mutex> lock(mutex);
  22730. ASSERT_GE(connected_at.size(), 2u);
  22731. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22732. connected_at[1] - connected_at[0])
  22733. .count();
  22734. EXPECT_GE(interval_ms, 100);
  22735. }
  22736. // Test: Last-Event-ID sent on reconnect
  22737. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22738. std::atomic<int> connection_count{0};
  22739. std::vector<std::string> received_last_event_ids;
  22740. std::mutex id_mutex;
  22741. // Endpoint that checks Last-Event-ID header and sends event with ID
  22742. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22743. int conn = connection_count.fetch_add(1);
  22744. // Capture the Last-Event-ID header from each connection
  22745. {
  22746. std::lock_guard<std::mutex> lock(id_mutex);
  22747. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22748. }
  22749. res.set_chunked_content_provider(
  22750. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22751. if (offset == 0) {
  22752. std::string event =
  22753. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22754. sink.write(event.data(), event.size());
  22755. }
  22756. return false;
  22757. });
  22758. });
  22759. Client client("localhost", get_port());
  22760. sse::SSEClient sse(client, "/reconnect-with-id");
  22761. sse.set_reconnect_interval(100);
  22762. sse.set_max_reconnect_attempts(3);
  22763. sse.start_async();
  22764. // Wait for at least 2 connections
  22765. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22766. sse.stop();
  22767. // Verify behavior
  22768. std::lock_guard<std::mutex> lock(id_mutex);
  22769. EXPECT_GE(received_last_event_ids.size(), 2u);
  22770. // First connection should have no Last-Event-ID
  22771. if (!received_last_event_ids.empty()) {
  22772. EXPECT_EQ(received_last_event_ids[0], "");
  22773. }
  22774. // Second connection should have Last-Event-ID from first connection
  22775. if (received_last_event_ids.size() >= 2) {
  22776. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22777. }
  22778. }
  22779. // Test: set_headers updates headers used on reconnect
  22780. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22781. std::vector<std::string> received_tokens;
  22782. std::mutex token_mutex;
  22783. // Endpoint that captures Authorization header
  22784. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22785. {
  22786. std::lock_guard<std::mutex> lock(token_mutex);
  22787. received_tokens.push_back(req.get_header_value("Authorization"));
  22788. }
  22789. res.set_chunked_content_provider(
  22790. "text/event-stream", [](size_t offset, DataSink &sink) {
  22791. if (offset == 0) {
  22792. std::string event = "data: hello\n\n";
  22793. sink.write(event.data(), event.size());
  22794. }
  22795. return false; // Close connection to trigger reconnect
  22796. });
  22797. });
  22798. Client client("localhost", get_port());
  22799. Headers headers = {{"Authorization", "Bearer old-token"}};
  22800. sse::SSEClient sse(client, "/auth-check", headers);
  22801. // Update headers on each successful connection
  22802. sse.on_open(
  22803. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22804. sse.set_reconnect_interval(100);
  22805. sse.set_max_reconnect_attempts(3);
  22806. sse.start_async();
  22807. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22808. sse.stop();
  22809. std::lock_guard<std::mutex> lock(token_mutex);
  22810. ASSERT_GE(received_tokens.size(), 2u);
  22811. // First connection uses original header
  22812. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22813. // Second connection uses updated header from set_headers
  22814. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22815. }
  22816. // Test: 401 allows reconnection (so on_error can refresh headers)
  22817. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22818. std::atomic<int> connection_count{0};
  22819. // Endpoint: returns 401 on first attempt, 200 on second
  22820. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22821. int conn = connection_count.fetch_add(1);
  22822. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22823. res.status = StatusCode::Unauthorized_401;
  22824. res.set_content("Unauthorized", "text/plain");
  22825. return;
  22826. }
  22827. res.set_chunked_content_provider(
  22828. "text/event-stream", [](size_t offset, DataSink &sink) {
  22829. if (offset == 0) {
  22830. std::string event = "data: authenticated\n\n";
  22831. sink.write(event.data(), event.size());
  22832. }
  22833. return false;
  22834. });
  22835. });
  22836. Client client("localhost", get_port());
  22837. Headers headers = {{"Authorization", "Bearer expired"}};
  22838. sse::SSEClient sse(client, "/auth-retry", headers);
  22839. std::atomic<bool> message_received{false};
  22840. // Refresh token on error
  22841. sse.on_error(
  22842. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22843. sse.on_message([&](const sse::SSEMessage &msg) {
  22844. if (msg.data == "authenticated") { message_received.store(true); }
  22845. });
  22846. sse.set_reconnect_interval(100);
  22847. sse.set_max_reconnect_attempts(3);
  22848. sse.start_async();
  22849. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22850. sse.stop();
  22851. // Should have reconnected after 401 and succeeded with new token
  22852. EXPECT_GE(connection_count.load(), 2);
  22853. EXPECT_TRUE(message_received.load());
  22854. }
  22855. TEST(Issue2318Test, EmptyHostString) {
  22856. {
  22857. httplib::Client cli_empty("", PORT);
  22858. auto res = cli_empty.Get("/");
  22859. ASSERT_FALSE(res);
  22860. EXPECT_EQ(httplib::Error::Connection, res.error());
  22861. }
  22862. {
  22863. httplib::Client cli(" ", PORT);
  22864. auto res = cli.Get("/");
  22865. ASSERT_FALSE(res);
  22866. EXPECT_EQ(httplib::Error::Connection, res.error());
  22867. }
  22868. }
  22869. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22870. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22871. Server svr;
  22872. // Set a small payload limit (1KB)
  22873. svr.set_payload_max_length(1024);
  22874. svr.Post("/test", [&](const Request &req, Response &res) {
  22875. res.set_content("Body size: " + std::to_string(req.body.size()),
  22876. "text/plain");
  22877. });
  22878. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22879. auto se = detail::scope_exit([&] {
  22880. svr.stop();
  22881. listen_thread.join();
  22882. });
  22883. svr.wait_until_ready();
  22884. // Create data that compresses well but exceeds limit when decompressed
  22885. // 8KB of repeated null bytes compresses to a very small size
  22886. std::string original_data(8 * 1024, '\0');
  22887. // Compress the data using gzip
  22888. std::string compressed_data;
  22889. detail::gzip_compressor compressor;
  22890. compressor.compress(original_data.data(), original_data.size(), true,
  22891. [&](const char *data, size_t size) {
  22892. compressed_data.append(data, size);
  22893. return true;
  22894. });
  22895. // Verify compression worked (compressed should be much smaller)
  22896. ASSERT_LT(compressed_data.size(), original_data.size());
  22897. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22898. // Send compressed data with Content-Encoding: gzip
  22899. Client cli(HOST, PORT);
  22900. Headers headers = {{"Content-Encoding", "gzip"}};
  22901. auto res =
  22902. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22903. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22905. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22906. }
  22907. #endif
  22908. // ============================================================================
  22909. // OpenSSL-Specific Tests
  22910. // ============================================================================
  22911. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22912. X509 *readCertificate(const std::string &strFileName) {
  22913. std::ifstream inStream(strFileName);
  22914. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22915. std::istreambuf_iterator<char>());
  22916. if (strCertPEM.empty()) return (nullptr);
  22917. BIO *pbCert = BIO_new(BIO_s_mem());
  22918. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22919. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22920. BIO_free(pbCert);
  22921. return (pCert);
  22922. }
  22923. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22924. std::ifstream inStream(strFileName);
  22925. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22926. std::istreambuf_iterator<char>());
  22927. if (strPrivateKeyPEM.empty()) return (nullptr);
  22928. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22929. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22930. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22931. BIO_free(pbPrivKey);
  22932. return (pPrivateKey);
  22933. }
  22934. TEST(BindServerTest, UpdateCerts) {
  22935. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22936. int port = svr.bind_to_any_port("0.0.0.0");
  22937. ASSERT_TRUE(svr.is_valid());
  22938. ASSERT_TRUE(port > 0);
  22939. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22940. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22941. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22942. ASSERT_TRUE(cert != nullptr);
  22943. ASSERT_TRUE(ca_cert != nullptr);
  22944. ASSERT_TRUE(key != nullptr);
  22945. X509_STORE *cert_store = X509_STORE_new();
  22946. X509_STORE_add_cert(cert_store, ca_cert);
  22947. // svr.update_certs(cert, key, cert_store); // deprecated
  22948. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22949. CLIENT_CA_CERT_FILE);
  22950. ASSERT_TRUE(svr.is_valid());
  22951. svr.stop();
  22952. X509_STORE_free(cert_store);
  22953. X509_free(cert);
  22954. X509_free(ca_cert);
  22955. EVP_PKEY_free(key);
  22956. }
  22957. // Test that update_certs() updates client CA list correctly
  22958. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22959. // Start with file-based constructor
  22960. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22961. ASSERT_TRUE(svr.is_valid());
  22962. // Initially no client CA list should be set
  22963. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22964. ASSERT_TRUE(ssl_ctx != nullptr);
  22965. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22966. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22967. // Now update with client CA (PEM string)
  22968. std::string cert_pem, key_pem, ca_pem;
  22969. read_file(SERVER_CERT_FILE, cert_pem);
  22970. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22971. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22972. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22973. ASSERT_TRUE(svr.is_valid());
  22974. // Now client CA list should be set
  22975. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22976. ASSERT_TRUE(ca_list_after != nullptr);
  22977. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22978. }
  22979. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22980. // Test that the file-path SSLServer constructor properly sets the client CA
  22981. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22982. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22983. ASSERT_TRUE(svr.is_valid());
  22984. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22985. ASSERT_TRUE(ssl_ctx != nullptr);
  22986. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22987. ASSERT_TRUE(ca_list != nullptr);
  22988. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22989. }
  22990. #endif
  22991. // ============================================================================
  22992. // MbedTLS-Specific Tests
  22993. // ============================================================================
  22994. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22995. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22996. using namespace httplib::tls;
  22997. // Track if callback was invoked
  22998. bool callback_invoked = false;
  22999. // The callback receives void* ctx which is actually MbedTlsContext*
  23000. // We can access the mbedtls_ssl_config via the context
  23001. auto setup_callback = [&callback_invoked](void *ctx) {
  23002. callback_invoked = true;
  23003. // Cast to MbedTlsContext* to access the ssl config
  23004. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  23005. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  23006. // Use static variables to hold certificate data (simplified for test)
  23007. static mbedtls_x509_crt own_cert;
  23008. static mbedtls_pk_context own_key;
  23009. static mbedtls_x509_crt ca_chain;
  23010. static bool initialized = false;
  23011. if (!initialized) {
  23012. mbedtls_x509_crt_init(&own_cert);
  23013. mbedtls_pk_init(&own_key);
  23014. mbedtls_x509_crt_init(&ca_chain);
  23015. // Load server certificate
  23016. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  23017. return false;
  23018. }
  23019. // Load server private key.
  23020. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  23021. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  23022. #if MBEDTLS_VERSION_MAJOR == 3
  23023. ,
  23024. mbedtls_ctr_drbg_random, nullptr
  23025. #endif
  23026. ) != 0) {
  23027. return false;
  23028. }
  23029. // Load CA chain for client verification
  23030. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  23031. return false;
  23032. }
  23033. initialized = true;
  23034. }
  23035. // Configure the SSL config
  23036. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  23037. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  23038. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  23039. // Set minimum TLS version using mbedTLS native API
  23040. #if MBEDTLS_VERSION_MAJOR >= 3
  23041. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  23042. #else
  23043. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  23044. MBEDTLS_SSL_MINOR_VERSION_3);
  23045. #endif
  23046. return true;
  23047. };
  23048. SSLServer svr(setup_callback);
  23049. ASSERT_TRUE(svr.is_valid());
  23050. ASSERT_TRUE(callback_invoked);
  23051. svr.Get("/test", [&](const Request &req, Response &res) {
  23052. res.set_content("test", "text/plain");
  23053. auto cert = req.peer_cert();
  23054. ASSERT_TRUE(static_cast<bool>(cert));
  23055. auto common_name = cert.subject_cn();
  23056. EXPECT_EQ("Common Name", common_name);
  23057. });
  23058. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23059. auto se = detail::scope_exit([&] {
  23060. svr.stop();
  23061. t.join();
  23062. ASSERT_FALSE(svr.is_running());
  23063. });
  23064. svr.wait_until_ready();
  23065. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  23066. cli.enable_server_certificate_verification(false);
  23067. cli.set_connection_timeout(30);
  23068. auto res = cli.Get("/test");
  23069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23070. ASSERT_EQ(StatusCode::OK_200, res->status);
  23071. }
  23072. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  23073. // context (owning mbedtls_ssl_config) before shutting down a still-open
  23074. // keep-alive SSL session, which reads through that config in
  23075. // mbedtls_ssl_close_notify.
  23076. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  23077. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23078. ASSERT_TRUE(svr.is_valid());
  23079. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  23080. res.set_content("test", "text/plain");
  23081. });
  23082. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  23083. auto se = detail::scope_exit([&] {
  23084. svr.stop();
  23085. t.join();
  23086. ASSERT_FALSE(svr.is_running());
  23087. });
  23088. svr.wait_until_ready();
  23089. {
  23090. SSLClient cli(HOST, PORT);
  23091. cli.enable_server_certificate_verification(false);
  23092. cli.set_keep_alive(true);
  23093. auto res = cli.Get("/test");
  23094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23095. ASSERT_EQ(StatusCode::OK_200, res->status);
  23096. // cli is destructed here with the keep-alive SSL session still open.
  23097. }
  23098. }
  23099. #endif
  23100. // WebSocket Tests
  23101. TEST(WebSocketTest, RSVBitsMustBeZero) {
  23102. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  23103. // defining the meaning of these bits has been negotiated.
  23104. auto make_frame = [](uint8_t first_byte) {
  23105. std::string frame;
  23106. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  23107. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  23108. frame += "Hello";
  23109. return frame;
  23110. };
  23111. // RSV1 set (0x40)
  23112. {
  23113. detail::BufferStream strm;
  23114. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  23115. ws::Opcode opcode;
  23116. std::string payload;
  23117. bool fin;
  23118. EXPECT_EQ(
  23119. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23120. ws::impl::FrameRead::Fail);
  23121. }
  23122. // RSV2 set (0x20)
  23123. {
  23124. detail::BufferStream strm;
  23125. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  23126. ws::Opcode opcode;
  23127. std::string payload;
  23128. bool fin;
  23129. EXPECT_EQ(
  23130. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23131. ws::impl::FrameRead::Fail);
  23132. }
  23133. // RSV3 set (0x10)
  23134. {
  23135. detail::BufferStream strm;
  23136. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  23137. ws::Opcode opcode;
  23138. std::string payload;
  23139. bool fin;
  23140. EXPECT_EQ(
  23141. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23142. ws::impl::FrameRead::Fail);
  23143. }
  23144. // No RSV bits set - should succeed
  23145. {
  23146. detail::BufferStream strm;
  23147. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  23148. ws::Opcode opcode;
  23149. std::string payload;
  23150. bool fin;
  23151. EXPECT_EQ(
  23152. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23153. ws::impl::FrameRead::Ok);
  23154. EXPECT_EQ(ws::Opcode::Text, opcode);
  23155. EXPECT_EQ("Hello", payload);
  23156. EXPECT_TRUE(fin);
  23157. }
  23158. }
  23159. TEST(WebSocketTest, ControlFrameValidation) {
  23160. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  23161. // payload length <= 125.
  23162. // Ping with FIN=0 - must be rejected
  23163. {
  23164. detail::BufferStream strm;
  23165. std::string frame;
  23166. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  23167. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23168. strm.write(frame.data(), frame.size());
  23169. ws::Opcode opcode;
  23170. std::string payload;
  23171. bool fin;
  23172. EXPECT_EQ(
  23173. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23174. ws::impl::FrameRead::Fail);
  23175. }
  23176. // Close with FIN=0 - must be rejected
  23177. {
  23178. detail::BufferStream strm;
  23179. std::string frame;
  23180. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  23181. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  23182. strm.write(frame.data(), frame.size());
  23183. ws::Opcode opcode;
  23184. std::string payload;
  23185. bool fin;
  23186. EXPECT_EQ(
  23187. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23188. ws::impl::FrameRead::Fail);
  23189. }
  23190. // Ping with payload_len=126 (extended length) - must be rejected
  23191. {
  23192. detail::BufferStream strm;
  23193. std::string frame;
  23194. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23195. frame += static_cast<char>(126); // payload_len=126 (>125)
  23196. frame += static_cast<char>(0x00); // extended length high byte
  23197. frame += static_cast<char>(126); // extended length low byte
  23198. frame += std::string(126, 'x');
  23199. strm.write(frame.data(), frame.size());
  23200. ws::Opcode opcode;
  23201. std::string payload;
  23202. bool fin;
  23203. EXPECT_EQ(
  23204. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23205. ws::impl::FrameRead::Fail);
  23206. }
  23207. // Ping with FIN=1 and payload_len=125 - should succeed
  23208. {
  23209. detail::BufferStream strm;
  23210. std::string frame;
  23211. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  23212. frame += static_cast<char>(125); // payload_len=125
  23213. frame += std::string(125, 'x');
  23214. strm.write(frame.data(), frame.size());
  23215. ws::Opcode opcode;
  23216. std::string payload;
  23217. bool fin;
  23218. EXPECT_EQ(
  23219. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23220. ws::impl::FrameRead::Ok);
  23221. EXPECT_EQ(ws::Opcode::Ping, opcode);
  23222. EXPECT_EQ(125u, payload.size());
  23223. EXPECT_TRUE(fin);
  23224. }
  23225. }
  23226. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  23227. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  23228. // length MUST be 0.
  23229. // MSB set - must be rejected
  23230. {
  23231. detail::BufferStream strm;
  23232. std::string frame;
  23233. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23234. frame += static_cast<char>(127); // 64-bit extended length
  23235. frame += static_cast<char>(0x80); // MSB set (invalid)
  23236. frame += std::string(7, '\0'); // remaining 7 bytes of length
  23237. strm.write(frame.data(), frame.size());
  23238. ws::Opcode opcode;
  23239. std::string payload;
  23240. bool fin;
  23241. EXPECT_EQ(
  23242. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23243. ws::impl::FrameRead::Fail);
  23244. }
  23245. // MSB clear - should pass length parsing (will be rejected by max_len,
  23246. // but that's a different check; use a small length to verify)
  23247. {
  23248. detail::BufferStream strm;
  23249. std::string frame;
  23250. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  23251. frame += static_cast<char>(127); // 64-bit extended length
  23252. frame += std::string(7, '\0'); // high bytes = 0
  23253. frame += static_cast<char>(0x03); // length = 3
  23254. frame += "abc";
  23255. strm.write(frame.data(), frame.size());
  23256. ws::Opcode opcode;
  23257. std::string payload;
  23258. bool fin;
  23259. EXPECT_EQ(
  23260. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  23261. ws::impl::FrameRead::Ok);
  23262. EXPECT_EQ(ws::Opcode::Text, opcode);
  23263. EXPECT_EQ("abc", payload);
  23264. }
  23265. }
  23266. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  23267. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  23268. // Valid UTF-8
  23269. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  23270. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  23271. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  23272. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  23273. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  23274. // Invalid UTF-8
  23275. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  23276. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  23277. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  23278. EXPECT_FALSE(
  23279. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  23280. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  23281. }
  23282. TEST(WebSocketTest, ConnectAndDisconnect) {
  23283. Server svr;
  23284. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23285. std::string msg;
  23286. while (ws.read(msg)) {}
  23287. });
  23288. auto port = svr.bind_to_any_port(HOST);
  23289. std::thread t([&]() { svr.listen_after_bind(); });
  23290. svr.wait_until_ready();
  23291. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23292. auto res = client.connect();
  23293. ASSERT_TRUE(res);
  23294. EXPECT_EQ(Error::Success, res.error());
  23295. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  23296. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  23297. EXPECT_TRUE(client.is_open());
  23298. client.close();
  23299. EXPECT_FALSE(client.is_open());
  23300. svr.stop();
  23301. t.join();
  23302. }
  23303. TEST(WebSocketTest, ValidURL) {
  23304. ws::WebSocketClient ws1("ws://localhost:8080/path");
  23305. EXPECT_TRUE(ws1.is_valid());
  23306. ws::WebSocketClient ws2("ws://example.com/path");
  23307. EXPECT_TRUE(ws2.is_valid());
  23308. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  23309. EXPECT_TRUE(ws3.is_valid());
  23310. #ifdef CPPHTTPLIB_SSL_ENABLED
  23311. ws::WebSocketClient wss1("wss://example.com/path");
  23312. EXPECT_TRUE(wss1.is_valid());
  23313. ws::WebSocketClient wss2("wss://example.com:443/path");
  23314. EXPECT_TRUE(wss2.is_valid());
  23315. #endif
  23316. }
  23317. TEST(WebSocketTest, InvalidURL) {
  23318. // No scheme
  23319. ws::WebSocketClient ws1("localhost:8080/path");
  23320. EXPECT_FALSE(ws1.is_valid());
  23321. // No path
  23322. ws::WebSocketClient ws2("ws://localhost:8080");
  23323. EXPECT_FALSE(ws2.is_valid());
  23324. // Empty string
  23325. ws::WebSocketClient ws3("");
  23326. EXPECT_FALSE(ws3.is_valid());
  23327. // Missing host
  23328. ws::WebSocketClient ws4("ws://:8080/path");
  23329. EXPECT_FALSE(ws4.is_valid());
  23330. // Port number overflow — should not crash
  23331. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  23332. EXPECT_FALSE(ws5.is_valid());
  23333. // Port out of range
  23334. ws::WebSocketClient ws6("ws://localhost:99999/path");
  23335. EXPECT_FALSE(ws6.is_valid());
  23336. }
  23337. TEST(WebSocketTest, UnsupportedScheme) {
  23338. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  23339. ws::WebSocketClient ws1("http://localhost:8080/path");
  23340. EXPECT_FALSE(ws1.is_valid());
  23341. ws::WebSocketClient ws2("https://localhost:8080/path");
  23342. EXPECT_FALSE(ws2.is_valid());
  23343. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  23344. EXPECT_FALSE(ws3.is_valid());
  23345. #else
  23346. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  23347. std::invalid_argument);
  23348. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  23349. std::invalid_argument);
  23350. #endif
  23351. }
  23352. TEST(WebSocketTest, ConnectWhenInvalid) {
  23353. ws::WebSocketClient ws("not a valid url");
  23354. EXPECT_FALSE(ws.is_valid());
  23355. auto res = ws.connect();
  23356. EXPECT_FALSE(res);
  23357. EXPECT_EQ(Error::Connection, res.error());
  23358. EXPECT_EQ(-1, res.status());
  23359. }
  23360. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23361. // Grab a port that is free, then close it again so nothing listens there
  23362. Server svr;
  23363. auto port = svr.bind_to_any_port(HOST);
  23364. svr.stop();
  23365. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23366. auto res = client.connect();
  23367. ASSERT_FALSE(res);
  23368. EXPECT_EQ(Error::Connection, res.error());
  23369. EXPECT_EQ(-1, res.status());
  23370. }
  23371. TEST(WebSocketTest, DefaultPort) {
  23372. ws::WebSocketClient ws1("ws://example.com/path");
  23373. EXPECT_TRUE(ws1.is_valid());
  23374. // ws:// defaults to port 80 (verified by successful parse)
  23375. #ifdef CPPHTTPLIB_SSL_ENABLED
  23376. ws::WebSocketClient ws2("wss://example.com/path");
  23377. EXPECT_TRUE(ws2.is_valid());
  23378. // wss:// defaults to port 443 (verified by successful parse)
  23379. #endif
  23380. }
  23381. TEST(WebSocketTest, IPv6LiteralAddress) {
  23382. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23383. EXPECT_TRUE(ws1.is_valid());
  23384. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23385. EXPECT_TRUE(ws2.is_valid());
  23386. }
  23387. TEST(WebSocketTest, ComplexPath) {
  23388. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23389. EXPECT_TRUE(ws1.is_valid());
  23390. ws::WebSocketClient ws2("ws://localhost:8080/");
  23391. EXPECT_TRUE(ws2.is_valid());
  23392. }
  23393. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23394. Server svr;
  23395. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23396. std::string msg;
  23397. while (ws.read(msg)) {}
  23398. });
  23399. auto port = svr.bind_to_any_port(HOST);
  23400. std::thread t([&]() { svr.listen_after_bind(); });
  23401. svr.wait_until_ready();
  23402. auto another_host = "example.com";
  23403. auto wrong_ip = "192.0.2.1";
  23404. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23405. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23406. ASSERT_TRUE(client.connect());
  23407. EXPECT_TRUE(client.is_open());
  23408. client.close();
  23409. svr.stop();
  23410. t.join();
  23411. }
  23412. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23413. Server svr;
  23414. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23415. std::string msg;
  23416. while (ws.read(msg)) {}
  23417. });
  23418. auto port = svr.bind_to_any_port(HOST);
  23419. std::thread t([&]() { svr.listen_after_bind(); });
  23420. svr.wait_until_ready();
  23421. auto wrong_ip = "192.0.2.1";
  23422. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23423. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23424. client.set_connection_timeout(1);
  23425. client.set_read_timeout(1);
  23426. client.set_write_timeout(1);
  23427. EXPECT_FALSE(client.connect());
  23428. EXPECT_FALSE(client.is_open());
  23429. svr.stop();
  23430. t.join();
  23431. }
  23432. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23433. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23434. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23435. // (RFC 6761) is only a map key and the Host header value.
  23436. auto host = "target.invalid";
  23437. Server svr;
  23438. std::string received_host;
  23439. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23440. received_host = req.get_header_value("Host");
  23441. std::string msg;
  23442. while (ws.read(msg)) {}
  23443. });
  23444. auto port = svr.bind_to_any_port(HOST);
  23445. std::thread t([&]() { svr.listen_after_bind(); });
  23446. // ASSERT_* below returns from the test body, which would leave t joinable
  23447. // and make ~thread call std::terminate.
  23448. auto se = detail::scope_exit([&] {
  23449. svr.stop();
  23450. if (t.joinable()) { t.join(); }
  23451. });
  23452. svr.wait_until_ready();
  23453. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23454. std::to_string(port) + "/ws");
  23455. client.set_hostname_addr_map({{host, HOST}});
  23456. ASSERT_TRUE(client.connect());
  23457. EXPECT_TRUE(client.is_open());
  23458. client.close();
  23459. svr.stop();
  23460. t.join();
  23461. // The mapping only redirects the connection; the identity stays host_.
  23462. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23463. }
  23464. class WebSocketIntegrationTest : public ::testing::Test {
  23465. protected:
  23466. void SetUp() override {
  23467. server_ = httplib::detail::make_unique<Server>();
  23468. setup_server();
  23469. start_server();
  23470. }
  23471. void TearDown() override {
  23472. server_->stop();
  23473. if (server_thread_.joinable()) { server_thread_.join(); }
  23474. }
  23475. void setup_server() {
  23476. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23477. std::string msg;
  23478. ws::ReadResult ret;
  23479. while ((ret = ws.read(msg))) {
  23480. if (ret == ws::Binary) {
  23481. ws.send(msg.data(), msg.size());
  23482. } else {
  23483. ws.send(msg);
  23484. }
  23485. }
  23486. });
  23487. server_->WebSocket("/ws-echo-string",
  23488. [](const Request &, ws::WebSocket &ws) {
  23489. std::string msg;
  23490. while (ws.read(msg)) {
  23491. ws.send("echo: " + msg);
  23492. }
  23493. });
  23494. server_->WebSocket(
  23495. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23496. // Echo back request metadata
  23497. ws.send("path:" + req.path);
  23498. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23499. std::string msg;
  23500. while (ws.read(msg)) {}
  23501. });
  23502. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23503. std::string msg;
  23504. ws.read(msg); // wait for a message
  23505. ws.close();
  23506. });
  23507. server_->WebSocket("/ws-close-status",
  23508. [](const Request &, ws::WebSocket &ws) {
  23509. std::string msg;
  23510. ws.read(msg); // wait for a message
  23511. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23512. });
  23513. server_->WebSocket(
  23514. "/ws-subprotocol",
  23515. [](const Request &, ws::WebSocket &ws) {
  23516. std::string msg;
  23517. while (ws.read(msg)) {
  23518. ws.send(msg);
  23519. }
  23520. },
  23521. [](const std::vector<std::string> &protocols) -> std::string {
  23522. for (const auto &p : protocols) {
  23523. if (p == "graphql-ws") { return p; }
  23524. }
  23525. return "";
  23526. });
  23527. server_->WebSocket(
  23528. "/ws-subprotocol-unoffered",
  23529. [](const Request &, ws::WebSocket &ws) {
  23530. std::string msg;
  23531. while (ws.read(msg)) {
  23532. ws.send(msg);
  23533. }
  23534. },
  23535. [](const std::vector<std::string> &) -> std::string {
  23536. return "admin";
  23537. });
  23538. }
  23539. void start_server() {
  23540. port_ = server_->bind_to_any_port(HOST);
  23541. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23542. server_->wait_until_ready();
  23543. }
  23544. std::unique_ptr<Server> server_;
  23545. std::thread server_thread_;
  23546. int port_ = 0;
  23547. };
  23548. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23549. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23550. "/ws-echo");
  23551. ASSERT_TRUE(client.connect());
  23552. ASSERT_TRUE(client.is_open());
  23553. ASSERT_TRUE(client.send("Hello WebSocket"));
  23554. std::string msg;
  23555. EXPECT_EQ(ws::Text, client.read(msg));
  23556. EXPECT_EQ("Hello WebSocket", msg);
  23557. client.close();
  23558. }
  23559. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23560. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23561. "/ws-echo");
  23562. ASSERT_TRUE(client.connect());
  23563. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23564. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23565. std::string msg;
  23566. EXPECT_EQ(ws::Binary, client.read(msg));
  23567. EXPECT_EQ(binary_data, msg);
  23568. client.close();
  23569. }
  23570. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23571. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23572. "/ws-echo");
  23573. ASSERT_TRUE(client.connect());
  23574. for (int i = 0; i < 10; i++) {
  23575. auto text = "message " + std::to_string(i);
  23576. ASSERT_TRUE(client.send(text));
  23577. std::string msg;
  23578. ASSERT_TRUE(client.read(msg));
  23579. EXPECT_EQ(text, msg);
  23580. }
  23581. client.close();
  23582. }
  23583. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23584. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23585. "/ws-close");
  23586. ASSERT_TRUE(client.connect());
  23587. // Send a message to trigger the server to close
  23588. ASSERT_TRUE(client.send("trigger close"));
  23589. // The server will close, so read should return false
  23590. std::string msg;
  23591. EXPECT_FALSE(client.read(msg));
  23592. EXPECT_FALSE(client.is_open());
  23593. }
  23594. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23595. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23596. "/ws-echo");
  23597. ASSERT_TRUE(client.connect());
  23598. // 128KB message
  23599. std::string large_data(128 * 1024, 'X');
  23600. ASSERT_TRUE(client.send(large_data));
  23601. std::string msg;
  23602. ASSERT_TRUE(client.read(msg));
  23603. EXPECT_EQ(large_data, msg);
  23604. client.close();
  23605. }
  23606. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23607. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23608. "/ws-echo");
  23609. ASSERT_TRUE(client.connect());
  23610. const int num_threads = 4;
  23611. std::vector<std::thread> threads;
  23612. std::atomic<int> send_count{0};
  23613. for (int t = 0; t < num_threads; t++) {
  23614. threads.emplace_back([&client, &send_count, t]() {
  23615. for (int i = 0; i < 5; i++) {
  23616. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23617. if (client.send(text)) { send_count++; }
  23618. }
  23619. });
  23620. }
  23621. for (auto &th : threads) {
  23622. th.join();
  23623. }
  23624. int received = 0;
  23625. std::string msg;
  23626. while (received < send_count.load()) {
  23627. if (!client.read(msg)) { break; }
  23628. received++;
  23629. }
  23630. EXPECT_EQ(send_count.load(), received);
  23631. client.close();
  23632. }
  23633. TEST_F(WebSocketIntegrationTest, ReadString) {
  23634. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23635. "/ws-echo-string");
  23636. ASSERT_TRUE(client.connect());
  23637. ASSERT_TRUE(client.send("hello"));
  23638. std::string msg;
  23639. ASSERT_TRUE(client.read(msg));
  23640. EXPECT_EQ("echo: hello", msg);
  23641. ASSERT_TRUE(client.send("world"));
  23642. ASSERT_TRUE(client.read(msg));
  23643. EXPECT_EQ("echo: world", msg);
  23644. client.close();
  23645. }
  23646. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23647. Headers headers = {{"X-Test-Header", "test-value"}};
  23648. ws::WebSocketClient client(
  23649. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23650. ASSERT_TRUE(client.connect());
  23651. std::string msg;
  23652. ASSERT_TRUE(client.read(msg));
  23653. EXPECT_EQ("path:/ws-request-info", msg);
  23654. ASSERT_TRUE(client.read(msg));
  23655. EXPECT_EQ("header:test-value", msg);
  23656. client.close();
  23657. }
  23658. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23659. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23660. "/ws-echo");
  23661. client.set_read_timeout(1, 0); // 1 second
  23662. ASSERT_TRUE(client.connect());
  23663. // Don't send anything — server echo handler waits for a message, so read()
  23664. // should time out. The connection survives it: nothing was consumed.
  23665. std::string msg;
  23666. EXPECT_EQ(client.read(msg), ws::Timeout);
  23667. EXPECT_TRUE(client.is_open());
  23668. // And it is still usable afterwards.
  23669. EXPECT_TRUE(client.send("after timeout"));
  23670. EXPECT_EQ(client.read(msg), ws::Text);
  23671. EXPECT_EQ(msg, "after timeout");
  23672. }
  23673. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23674. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23675. "/ws-echo");
  23676. client.set_read_timeout(1, 0);
  23677. ASSERT_TRUE(client.connect());
  23678. ASSERT_TRUE(client.send("first"));
  23679. std::string msg;
  23680. ASSERT_EQ(client.read(msg), ws::Text);
  23681. ASSERT_EQ(msg, "first");
  23682. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23683. // not be used with a read timeout: it would reprocess the previous message.
  23684. EXPECT_EQ(client.read(msg), ws::Timeout);
  23685. EXPECT_EQ(msg, "first");
  23686. }
  23687. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23688. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23689. "/ws-echo");
  23690. ASSERT_TRUE(client.connect());
  23691. // Setting it once the connection is open reaches the live stream, not just
  23692. // the seed for the next connect().
  23693. client.set_read_timeout(1, 0);
  23694. std::string msg;
  23695. EXPECT_EQ(client.read(msg), ws::Timeout);
  23696. EXPECT_TRUE(client.is_open());
  23697. }
  23698. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23699. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23700. "/ws-echo");
  23701. client.set_read_timeout(5, 0);
  23702. ASSERT_TRUE(client.connect());
  23703. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23704. // The server should reject it and close the connection.
  23705. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23706. client.send(oversized);
  23707. // The server's read() should have failed due to payload limit,
  23708. // so our read() should return false (connection closed).
  23709. std::string msg;
  23710. EXPECT_FALSE(client.read(msg));
  23711. }
  23712. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23713. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23714. "/ws-echo");
  23715. client.set_read_timeout(10, 0);
  23716. ASSERT_TRUE(client.connect());
  23717. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23718. // This should succeed.
  23719. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23720. ASSERT_TRUE(client.send(at_limit));
  23721. std::string msg;
  23722. ASSERT_TRUE(client.read(msg));
  23723. EXPECT_EQ(at_limit.size(), msg.size());
  23724. client.close();
  23725. }
  23726. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23727. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23728. "/nonexistent");
  23729. auto res = client.connect();
  23730. EXPECT_FALSE(res);
  23731. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23732. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23733. EXPECT_FALSE(client.is_open());
  23734. }
  23735. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23736. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23737. "/ws-echo");
  23738. ASSERT_TRUE(client.connect());
  23739. ASSERT_TRUE(client.send(""));
  23740. std::string msg;
  23741. EXPECT_EQ(ws::Text, client.read(msg));
  23742. EXPECT_EQ("", msg);
  23743. client.close();
  23744. }
  23745. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23746. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23747. "/ws-echo");
  23748. // First connection
  23749. ASSERT_TRUE(client.connect());
  23750. ASSERT_TRUE(client.send("first"));
  23751. std::string msg;
  23752. ASSERT_TRUE(client.read(msg));
  23753. EXPECT_EQ("first", msg);
  23754. client.close();
  23755. EXPECT_FALSE(client.is_open());
  23756. // Reconnect using the same client object
  23757. ASSERT_TRUE(client.connect());
  23758. ASSERT_TRUE(client.is_open());
  23759. ASSERT_TRUE(client.send("second"));
  23760. ASSERT_TRUE(client.read(msg));
  23761. EXPECT_EQ("second", msg);
  23762. client.close();
  23763. }
  23764. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23765. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23766. "/ws-close-status");
  23767. ASSERT_TRUE(client.connect());
  23768. // Trigger the server to close with GoingAway status
  23769. ASSERT_TRUE(client.send("trigger"));
  23770. // read() should return false after receiving the close frame
  23771. std::string msg;
  23772. EXPECT_FALSE(client.read(msg));
  23773. EXPECT_FALSE(client.is_open());
  23774. }
  23775. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23776. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23777. "/ws-echo");
  23778. ASSERT_TRUE(client.connect());
  23779. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23780. EXPECT_FALSE(client.is_open());
  23781. }
  23782. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23783. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23784. ws::WebSocketClient client(
  23785. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23786. ASSERT_TRUE(client.connect());
  23787. // Server should have selected graphql-ws
  23788. EXPECT_EQ("graphql-ws", client.subprotocol());
  23789. client.close();
  23790. }
  23791. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23792. Headers headers;
  23793. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23794. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23795. ws::WebSocketClient client(
  23796. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23797. ASSERT_TRUE(client.connect());
  23798. // The offer on the second field line counts too, so graphql-ws is selected
  23799. EXPECT_EQ("graphql-ws", client.subprotocol());
  23800. client.close();
  23801. }
  23802. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23803. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23804. ws::WebSocketClient client(
  23805. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23806. ASSERT_TRUE(client.connect());
  23807. // Server should not have selected any subprotocol
  23808. EXPECT_TRUE(client.subprotocol().empty());
  23809. client.close();
  23810. }
  23811. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23812. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23814. "/ws-subprotocol-unoffered",
  23815. headers);
  23816. ASSERT_TRUE(client.connect());
  23817. EXPECT_TRUE(client.subprotocol().empty());
  23818. client.close();
  23819. }
  23820. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23821. // Connect without requesting any subprotocol
  23822. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23823. "/ws-subprotocol");
  23824. ASSERT_TRUE(client.connect());
  23825. EXPECT_TRUE(client.subprotocol().empty());
  23826. client.close();
  23827. }
  23828. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23829. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23830. "/ws-echo");
  23831. client.set_tcp_nodelay(true);
  23832. client.set_connection_timeout(3, 0);
  23833. bool socket_options_called = false;
  23834. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23835. ASSERT_TRUE(client.connect());
  23836. ASSERT_TRUE(client.is_open());
  23837. EXPECT_TRUE(socket_options_called);
  23838. ASSERT_TRUE(client.send("hello"));
  23839. std::string msg;
  23840. auto result = client.read(msg);
  23841. EXPECT_EQ(result, ws::ReadResult::Text);
  23842. EXPECT_EQ(msg, "hello");
  23843. client.close();
  23844. }
  23845. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23846. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23847. "/ws-echo");
  23848. client.set_connection_timeout(std::chrono::seconds(3));
  23849. client.set_write_timeout(std::chrono::seconds(3));
  23850. // A sub-second remainder exercises the seconds/microseconds split.
  23851. client.set_read_timeout(std::chrono::milliseconds(1500));
  23852. ASSERT_TRUE(client.connect());
  23853. auto start = std::chrono::steady_clock::now();
  23854. std::string msg;
  23855. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23856. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23857. std::chrono::steady_clock::now() - start)
  23858. .count();
  23859. // Above 1s so that dropping the microseconds half of the split fails here.
  23860. // Ignoring the setter altogether would not reach this line at all: a client
  23861. // waits forever by default.
  23862. EXPECT_GE(elapsed, 1400);
  23863. EXPECT_LT(elapsed, 30000);
  23864. }
  23865. #ifndef _WIN32
  23866. // A send() that times out after part of the data went out returns the count
  23867. // written so far. Every byte of the frame must still be sent, or the peer reads
  23868. // the next frame's header and payload as the rest of this one.
  23869. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  23870. signal(SIGPIPE, SIG_IGN);
  23871. const std::string large(4 * 1024 * 1024, 'A');
  23872. std::atomic<bool> large_sent{false};
  23873. std::atomic<bool> small_sent{false};
  23874. Server svr;
  23875. svr.set_write_timeout(0, 500000);
  23876. svr.set_socket_options([](socket_t sock) {
  23877. int size = 8192;
  23878. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  23879. reinterpret_cast<const char *>(&size), sizeof(size));
  23880. });
  23881. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  23882. large_sent = ws.send(large.data(), large.size());
  23883. small_sent = ws.send("after");
  23884. std::string msg;
  23885. while (ws.read(msg)) {}
  23886. });
  23887. auto port = svr.bind_to_any_port(HOST);
  23888. std::thread t([&]() { svr.listen_after_bind(); });
  23889. auto se = detail::scope_exit([&] {
  23890. svr.stop();
  23891. t.join();
  23892. });
  23893. svr.wait_until_ready();
  23894. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  23895. std::to_string(port) + "/ws");
  23896. client.set_read_timeout(5);
  23897. client.set_socket_options([](socket_t sock) {
  23898. int size = 8192;
  23899. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  23900. reinterpret_cast<const char *>(&size), sizeof(size));
  23901. });
  23902. ASSERT_TRUE(client.connect());
  23903. // Outlast the server's write timeout, then drain.
  23904. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  23905. std::string msg;
  23906. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  23907. EXPECT_TRUE(msg == large);
  23908. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  23909. EXPECT_EQ("after", msg);
  23910. EXPECT_TRUE(large_sent);
  23911. EXPECT_TRUE(small_sent);
  23912. client.close();
  23913. }
  23914. #endif
  23915. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23916. Server svr;
  23917. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23918. if (!req.has_header("Authorization")) {
  23919. res.status = StatusCode::Unauthorized_401;
  23920. res.set_content("Unauthorized", "text/plain");
  23921. return Server::HandlerResponse::Handled;
  23922. }
  23923. return Server::HandlerResponse::Unhandled;
  23924. });
  23925. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23926. std::string msg;
  23927. while (ws.read(msg)) {
  23928. ws.send(msg);
  23929. }
  23930. });
  23931. auto port = svr.bind_to_any_port("localhost");
  23932. std::thread t([&]() { svr.listen_after_bind(); });
  23933. svr.wait_until_ready();
  23934. // Without Authorization header - should be rejected before upgrade
  23935. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23936. EXPECT_FALSE(client1.connect());
  23937. // The rejection is framed like any other HTTP response
  23938. {
  23939. Client cli("localhost", port);
  23940. Headers headers = {{"Upgrade", "websocket"},
  23941. {"Connection", "Upgrade"},
  23942. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23943. {"Sec-WebSocket-Version", "13"}};
  23944. auto res = cli.Get("/ws", headers);
  23945. ASSERT_TRUE(res);
  23946. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23947. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23948. EXPECT_EQ("Unauthorized", res->body);
  23949. }
  23950. // With Authorization header - should succeed
  23951. Headers headers = {{"Authorization", "Bearer token123"}};
  23952. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23953. headers);
  23954. ASSERT_TRUE(client2.connect());
  23955. ASSERT_TRUE(client2.send("hello"));
  23956. std::string msg;
  23957. ASSERT_TRUE(client2.read(msg));
  23958. EXPECT_EQ("hello", msg);
  23959. client2.close();
  23960. svr.stop();
  23961. t.join();
  23962. }
  23963. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23964. Server svr;
  23965. std::atomic<int> pre_routing_calls{0};
  23966. std::atomic<int> pre_request_calls{0};
  23967. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23968. pre_routing_calls++;
  23969. if (req.path == "/handled") {
  23970. res.set_content("handled", "text/plain");
  23971. return Server::HandlerResponse::Handled;
  23972. }
  23973. return Server::HandlerResponse::Unhandled;
  23974. });
  23975. svr.set_pre_request_handler([&](const Request &, Response &) {
  23976. pre_request_calls++;
  23977. return Server::HandlerResponse::Unhandled;
  23978. });
  23979. svr.Get("/http", [](const Request &, Response &res) {
  23980. res.set_content("http", "text/plain");
  23981. });
  23982. svr.WebSocket("/ws",
  23983. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23984. auto port = svr.bind_to_any_port("localhost");
  23985. std::thread t([&]() { svr.listen_after_bind(); });
  23986. auto se = detail::scope_exit([&] {
  23987. svr.stop();
  23988. t.join();
  23989. });
  23990. svr.wait_until_ready();
  23991. Headers upgrade = {{"Upgrade", "websocket"},
  23992. {"Connection", "Upgrade"},
  23993. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23994. {"Sec-WebSocket-Version", "13"}};
  23995. auto get = [&](const char *path) {
  23996. pre_routing_calls = 0;
  23997. return Client("localhost", port).Get(path, upgrade);
  23998. };
  23999. // No WebSocket route, but an HTTP one
  24000. auto res = get("/http");
  24001. ASSERT_TRUE(res);
  24002. EXPECT_EQ(StatusCode::OK_200, res->status);
  24003. EXPECT_EQ("http", res->body);
  24004. EXPECT_EQ(1, pre_routing_calls);
  24005. EXPECT_EQ(1, pre_request_calls);
  24006. // No route at all
  24007. res = get("/none");
  24008. ASSERT_TRUE(res);
  24009. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24010. EXPECT_EQ(1, pre_routing_calls);
  24011. // Answered by the pre-routing handler
  24012. res = get("/handled");
  24013. ASSERT_TRUE(res);
  24014. EXPECT_EQ(StatusCode::OK_200, res->status);
  24015. EXPECT_EQ("handled", res->body);
  24016. EXPECT_EQ(1, pre_routing_calls);
  24017. // A WebSocket route
  24018. pre_routing_calls = 0;
  24019. pre_request_calls = 0;
  24020. {
  24021. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24022. "/ws");
  24023. ASSERT_TRUE(client.connect());
  24024. std::string msg;
  24025. ASSERT_TRUE(client.read(msg));
  24026. EXPECT_EQ("ws", msg);
  24027. client.close();
  24028. }
  24029. EXPECT_EQ(1, pre_routing_calls);
  24030. EXPECT_EQ(1, pre_request_calls);
  24031. }
  24032. // An upgrade request answered by a hook leaves its body unread, so that body
  24033. // must not be served as the next request on the connection.
  24034. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  24035. Server svr;
  24036. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  24037. if (req.path == "/pre-routing") {
  24038. res.set_content("pre-routing", "text/plain");
  24039. return Server::HandlerResponse::Handled;
  24040. }
  24041. return Server::HandlerResponse::Unhandled;
  24042. });
  24043. svr.set_pre_request_handler([](const Request &req, Response &res) {
  24044. if (req.matched_route == "/pre-request") {
  24045. res.set_content("pre-request", "text/plain");
  24046. return Server::HandlerResponse::Handled;
  24047. }
  24048. return Server::HandlerResponse::Unhandled;
  24049. });
  24050. svr.Get("/smuggled", [](const Request &, Response &res) {
  24051. res.set_content("smuggled", "text/plain");
  24052. });
  24053. svr.WebSocket("/pre-request",
  24054. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  24055. auto port = svr.bind_to_any_port(HOST);
  24056. std::thread t([&]() { svr.listen_after_bind(); });
  24057. auto se = detail::scope_exit([&] {
  24058. svr.stop();
  24059. t.join();
  24060. });
  24061. svr.wait_until_ready();
  24062. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  24063. for (auto path : {"/pre-routing", "/pre-request"}) {
  24064. std::string req = std::string("GET ") + path +
  24065. " HTTP/1.1\r\n"
  24066. "Host: localhost\r\n"
  24067. "Upgrade: websocket\r\n"
  24068. "Connection: Upgrade\r\n"
  24069. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  24070. "Sec-WebSocket-Version: 13\r\n"
  24071. "Content-Length: " +
  24072. std::to_string(body.size()) + "\r\n\r\n" + body;
  24073. std::string res;
  24074. ASSERT_TRUE(send_request(5, req, &res, port));
  24075. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  24076. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  24077. // Only one response, and the body was not served as a request
  24078. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  24079. }
  24080. }
  24081. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  24082. Server svr;
  24083. std::atomic<int> pre_request_calls{0};
  24084. std::atomic<bool> route_matched{false};
  24085. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  24086. pre_request_calls++;
  24087. if (req.matched_route == "/ws/:id") { route_matched = true; }
  24088. if (req.get_header_value("Authorization") != "Bearer token123") {
  24089. res.status = StatusCode::Unauthorized_401;
  24090. res.set_content("Unauthorized", "text/plain");
  24091. return Server::HandlerResponse::Handled;
  24092. }
  24093. return Server::HandlerResponse::Unhandled;
  24094. });
  24095. std::atomic<bool> handler_called{false};
  24096. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  24097. handler_called = true;
  24098. ws.send(req.matched_route + " " + req.path_params.at("id"));
  24099. });
  24100. auto port = svr.bind_to_any_port("localhost");
  24101. std::thread t([&]() { svr.listen_after_bind(); });
  24102. svr.wait_until_ready();
  24103. // Without Authorization header - should be rejected before upgrade
  24104. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  24105. "/ws/1");
  24106. EXPECT_FALSE(client1.connect());
  24107. EXPECT_FALSE(handler_called);
  24108. EXPECT_EQ(1, pre_request_calls);
  24109. EXPECT_TRUE(route_matched);
  24110. // The rejection is an ordinary HTTP response, not a protocol switch
  24111. {
  24112. Client cli("localhost", port);
  24113. Headers headers = {{"Upgrade", "websocket"},
  24114. {"Connection", "Upgrade"},
  24115. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24116. {"Sec-WebSocket-Version", "13"}};
  24117. auto res = cli.Get("/ws/1", headers);
  24118. ASSERT_TRUE(res);
  24119. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  24120. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  24121. EXPECT_EQ("Unauthorized", res->body);
  24122. }
  24123. EXPECT_FALSE(handler_called);
  24124. // With Authorization header - should succeed
  24125. Headers headers = {{"Authorization", "Bearer token123"}};
  24126. ws::WebSocketClient client2(
  24127. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  24128. ASSERT_TRUE(client2.connect());
  24129. std::string msg;
  24130. ASSERT_TRUE(client2.read(msg));
  24131. EXPECT_EQ("/ws/:id 2", msg);
  24132. EXPECT_TRUE(handler_called);
  24133. client2.close();
  24134. svr.stop();
  24135. t.join();
  24136. }
  24137. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  24138. static Headers websocket_upgrade_headers() {
  24139. return {{"Upgrade", "websocket"},
  24140. {"Connection", "Upgrade"},
  24141. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24142. {"Sec-WebSocket-Version", "13"},
  24143. {"Sec-WebSocket-Protocol", "chat"}};
  24144. }
  24145. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  24146. Server svr;
  24147. svr.set_pre_routing_handler([](const Request &req, Response &) {
  24148. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  24149. return Server::HandlerResponse::Unhandled;
  24150. });
  24151. svr.set_pre_request_handler([](const Request &req, Response &) {
  24152. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  24153. return Server::HandlerResponse::Unhandled;
  24154. });
  24155. svr.set_exception_handler(
  24156. [](const Request &, Response &res, std::exception_ptr ep) {
  24157. try {
  24158. std::rethrow_exception(ep);
  24159. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  24160. });
  24161. auto handler = [](const Request &, ws::WebSocket &) {};
  24162. svr.WebSocket("/pre-routing", handler);
  24163. svr.WebSocket("/pre-request", handler);
  24164. svr.WebSocket("/sub-protocol", handler,
  24165. [](const std::vector<std::string> &) -> std::string {
  24166. throw std::runtime_error("/sub-protocol");
  24167. });
  24168. auto port = svr.bind_to_any_port(HOST);
  24169. ASSERT_GT(port, 0);
  24170. thread t = thread([&] { svr.listen_after_bind(); });
  24171. auto se = detail::scope_exit([&] {
  24172. svr.stop();
  24173. t.join();
  24174. ASSERT_FALSE(svr.is_running());
  24175. });
  24176. svr.wait_until_ready();
  24177. Client cli(HOST, port);
  24178. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  24179. auto res = cli.Get(path, websocket_upgrade_headers());
  24180. if (!res) {
  24181. ADD_FAILURE() << path << ": " << to_string(res.error());
  24182. continue;
  24183. }
  24184. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  24185. EXPECT_EQ(path, res->body);
  24186. }
  24187. }
  24188. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  24189. Server svr;
  24190. svr.set_pre_routing_handler(
  24191. [](const Request &, Response &) -> Server::HandlerResponse {
  24192. throw std::runtime_error("pre-routing");
  24193. });
  24194. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24195. auto port = svr.bind_to_any_port(HOST);
  24196. ASSERT_GT(port, 0);
  24197. thread t = thread([&] { svr.listen_after_bind(); });
  24198. auto se = detail::scope_exit([&] {
  24199. svr.stop();
  24200. t.join();
  24201. ASSERT_FALSE(svr.is_running());
  24202. });
  24203. svr.wait_until_ready();
  24204. Client cli(HOST, port);
  24205. auto res = cli.Get("/ws", websocket_upgrade_headers());
  24206. ASSERT_TRUE(res) << to_string(res.error());
  24207. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  24208. }
  24209. #endif
  24210. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  24211. Server svr;
  24212. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24213. // A read timeout is how a handler gets control back. Without it, a handler
  24214. // parked in read() can never write on the connection it is reading.
  24215. ws.set_read_timeout(std::chrono::milliseconds(100));
  24216. std::string msg;
  24217. while (ws.is_open()) {
  24218. auto r = ws.read(msg);
  24219. if (r == httplib::ws::Timeout) {
  24220. ws.send("tick");
  24221. continue;
  24222. }
  24223. if (r == httplib::ws::Fail) { break; }
  24224. ws.send(msg);
  24225. }
  24226. });
  24227. auto port = svr.bind_to_any_port("localhost");
  24228. std::thread t([&]() { svr.listen_after_bind(); });
  24229. svr.wait_until_ready();
  24230. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24231. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  24232. ASSERT_TRUE(client.connect());
  24233. // The client sends nothing, so anything it receives came out of the
  24234. // handler's timeout path.
  24235. std::string msg;
  24236. ASSERT_EQ(client.read(msg), ws::Text);
  24237. EXPECT_EQ("tick", msg);
  24238. client.close();
  24239. svr.stop();
  24240. t.join();
  24241. }
  24242. // Stream::read may return fewer bytes than asked for. This is that contract at
  24243. // its worst -- one byte per call -- which is what a frame header straddling a
  24244. // read buffer's boundary looks like to the frame parser.
  24245. class WsByteAtATimeStream : public Stream {
  24246. public:
  24247. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  24248. bool is_readable() const override { return true; }
  24249. bool wait_readable() const override { return true; }
  24250. bool wait_writable() const override { return true; }
  24251. ssize_t read(char *ptr, size_t size) override {
  24252. if (size == 0 || pos_ >= data_.size()) { return 0; }
  24253. *ptr = data_[pos_++];
  24254. return 1;
  24255. }
  24256. ssize_t write(const char *, size_t size) override {
  24257. return static_cast<ssize_t>(size);
  24258. }
  24259. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  24260. ip = "127.0.0.1";
  24261. port = 0;
  24262. }
  24263. void get_local_ip_and_port(std::string &ip, int &port) const override {
  24264. ip = "127.0.0.1";
  24265. port = 0;
  24266. }
  24267. socket_t socket() const override { return INVALID_SOCKET; }
  24268. time_t duration() const override { return 0; }
  24269. private:
  24270. std::string data_;
  24271. size_t pos_ = 0;
  24272. };
  24273. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  24274. // The payload uses the 16-bit extended length, so the header, the length
  24275. // and the mask key are all multi-byte fields here. Each used to be read
  24276. // with a single read() call, which fails as soon as one is split. The
  24277. // payload is also a little over one read chunk, so it is read in two.
  24278. std::string body;
  24279. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  24280. body += static_cast<char>(i % 251);
  24281. }
  24282. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  24283. std::string frame;
  24284. frame += static_cast<char>(0x81); // FIN + Text
  24285. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  24286. frame += static_cast<char>(body.size() >> 8);
  24287. frame += static_cast<char>(body.size() & 0xff);
  24288. for (size_t i = 0; i < 4; i++) {
  24289. frame += static_cast<char>(mask[i]);
  24290. }
  24291. for (size_t i = 0; i < body.size(); i++) {
  24292. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  24293. }
  24294. WsByteAtATimeStream strm(frame);
  24295. ws::Opcode opcode;
  24296. std::string payload;
  24297. bool fin = false;
  24298. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  24299. /*expect_masked=*/true, body.size()),
  24300. ws::impl::FrameRead::Ok);
  24301. EXPECT_TRUE(fin);
  24302. EXPECT_EQ(opcode, ws::Opcode::Text);
  24303. EXPECT_EQ(payload, body);
  24304. }
  24305. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  24306. std::string body(2000, 'x');
  24307. std::string frame;
  24308. frame += static_cast<char>(0x82); // FIN + Binary
  24309. frame += static_cast<char>(126); // 16-bit length follows
  24310. frame += static_cast<char>(body.size() >> 8);
  24311. frame += static_cast<char>(body.size() & 0xff);
  24312. frame += body;
  24313. detail::BufferStream strm;
  24314. strm.write(frame.data(), frame.size());
  24315. ws::Opcode opcode;
  24316. std::string payload;
  24317. bool fin;
  24318. EXPECT_EQ(
  24319. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  24320. ws::impl::FrameRead::Ok);
  24321. EXPECT_EQ(body, payload);
  24322. }
  24323. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  24324. // The header announces the largest payload allowed, and only 3 bytes of it
  24325. // ever arrive.
  24326. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  24327. std::string frame;
  24328. frame += static_cast<char>(0x82); // FIN + Binary
  24329. frame += static_cast<char>(127); // 64-bit length follows
  24330. for (int shift = 56; shift >= 0; shift -= 8) {
  24331. frame += static_cast<char>((len >> shift) & 0xff);
  24332. }
  24333. frame += "abc";
  24334. detail::BufferStream strm;
  24335. strm.write(frame.data(), frame.size());
  24336. ws::Opcode opcode;
  24337. std::string payload;
  24338. bool fin;
  24339. EXPECT_EQ(
  24340. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  24341. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  24342. ws::impl::FrameRead::Fail);
  24343. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  24344. }
  24345. TEST(WebSocketTest, QueryStringInHandshake) {
  24346. Server svr;
  24347. std::mutex mtx;
  24348. std::string received_target;
  24349. std::string received_token;
  24350. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24351. {
  24352. std::lock_guard<std::mutex> lock(mtx);
  24353. received_target = req.target;
  24354. if (req.has_param("token")) {
  24355. received_token = req.get_param_value("token");
  24356. }
  24357. }
  24358. std::string msg;
  24359. while (ws.read(msg)) {
  24360. ws.send(msg);
  24361. }
  24362. });
  24363. auto port = svr.bind_to_any_port("localhost");
  24364. std::thread t([&]() { svr.listen_after_bind(); });
  24365. svr.wait_until_ready();
  24366. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  24367. "/ws?token=ABC&session=123");
  24368. ASSERT_TRUE(client.connect());
  24369. // Round-trip ensures the handler has run and captured the request.
  24370. ASSERT_TRUE(client.send("hello"));
  24371. std::string msg;
  24372. ASSERT_TRUE(client.read(msg));
  24373. EXPECT_EQ("hello", msg);
  24374. client.close();
  24375. {
  24376. std::lock_guard<std::mutex> lock(mtx);
  24377. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  24378. EXPECT_EQ("ABC", received_token);
  24379. }
  24380. svr.stop();
  24381. t.join();
  24382. }
  24383. // Run a handshake against a throwaway server and hand the request the server
  24384. // received back to the caller, so tests can assert on the headers the client
  24385. // actually put on the wire.
  24386. static void capture_websocket_handshake_request(
  24387. const Headers &client_headers,
  24388. std::function<void(const Request &, int port)> verify) {
  24389. Server svr;
  24390. std::mutex mtx;
  24391. Request received;
  24392. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24393. {
  24394. std::lock_guard<std::mutex> lock(mtx);
  24395. received = req;
  24396. }
  24397. std::string msg;
  24398. while (ws.read(msg)) {
  24399. ws.send(msg);
  24400. }
  24401. });
  24402. auto port = svr.bind_to_any_port("localhost");
  24403. std::thread t([&]() { svr.listen_after_bind(); });
  24404. auto se = detail::scope_exit([&] {
  24405. svr.stop();
  24406. t.join();
  24407. });
  24408. svr.wait_until_ready();
  24409. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24410. client_headers);
  24411. ASSERT_TRUE(client.connect());
  24412. ASSERT_TRUE(client.send("hello"));
  24413. std::string msg;
  24414. ASSERT_TRUE(client.read(msg));
  24415. client.close();
  24416. {
  24417. std::lock_guard<std::mutex> lock(mtx);
  24418. verify(received, port);
  24419. }
  24420. }
  24421. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24422. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24423. // Non-default port must be present in the Host header. Default ports
  24424. // (80/443) are omitted; that logic is covered by
  24425. // MakeHostAndPortStringTest.
  24426. EXPECT_EQ("localhost:" + std::to_string(port),
  24427. req.get_header_value("Host"));
  24428. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24429. req.get_header_value("User-Agent"));
  24430. EXPECT_FALSE(req.has_header("Accept"));
  24431. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24432. EXPECT_FALSE(req.has_header("Content-Length"));
  24433. });
  24434. }
  24435. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24436. capture_websocket_handshake_request(
  24437. {{"Host", "example.com"},
  24438. {"User-Agent", "custom-agent"},
  24439. {"X-Custom", "value"}},
  24440. [](const Request &req, int) {
  24441. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24442. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24443. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24444. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24445. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24446. });
  24447. }
  24448. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24449. capture_websocket_handshake_request(
  24450. {{"Upgrade", "bogus"},
  24451. {"Connection", "close"},
  24452. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24453. {"Sec-WebSocket-Version", "8"}},
  24454. [](const Request &req, int) {
  24455. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24456. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24457. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24458. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24459. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24460. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24461. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24462. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24463. req.get_header_value("Sec-WebSocket-Key"));
  24464. });
  24465. }
  24466. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24467. // A header the client refuses to send must abort the handshake before any
  24468. // part of it reaches the wire; a lone request line would otherwise sit in
  24469. // the peer's buffer as a truncated request.
  24470. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24471. ASSERT_NE(INVALID_SOCKET, srv);
  24472. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24473. sockaddr_in addr{};
  24474. addr.sin_family = AF_INET;
  24475. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24476. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24477. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24478. ASSERT_EQ(0, ::listen(srv, 1));
  24479. sockaddr_in bound{};
  24480. socklen_t bound_len = sizeof(bound);
  24481. ASSERT_EQ(
  24482. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24483. auto port = ntohs(bound.sin_port);
  24484. ssize_t received = -1;
  24485. std::thread t([&] {
  24486. // Bound every blocking call so a regression fails the test with a bad
  24487. // value instead of hanging the suite.
  24488. fd_set rfds;
  24489. FD_ZERO(&rfds);
  24490. FD_SET(srv, &rfds);
  24491. timeval tv{5, 0};
  24492. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24493. 0) {
  24494. return;
  24495. }
  24496. sockaddr_in cli_addr{};
  24497. socklen_t cli_len = sizeof(cli_addr);
  24498. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24499. if (cli == INVALID_SOCKET) { return; }
  24500. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24501. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24502. char buf[4096];
  24503. received = ::recv(cli, buf, sizeof(buf), 0);
  24504. });
  24505. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24506. // connect() has already shut the socket down by the time it returns false,
  24507. // so the peer sees EOF without waiting for the client to be destroyed.
  24508. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24509. {{"X-Bad", "a\r\nInjected: 1"}});
  24510. EXPECT_FALSE(client.connect());
  24511. t.join();
  24512. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24513. EXPECT_EQ(0, received);
  24514. }
  24515. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24516. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24517. // contains "upgrade" as a substring is a different token and must not
  24518. // start a WebSocket handshake.
  24519. auto make_request = [](const std::vector<std::string> &connection_values) {
  24520. Request req;
  24521. req.method = "GET";
  24522. req.headers.emplace("Upgrade", "websocket");
  24523. for (const auto &value : connection_values) {
  24524. req.headers.emplace("Connection", value);
  24525. }
  24526. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24527. req.headers.emplace("Sec-WebSocket-Version", "13");
  24528. return req;
  24529. };
  24530. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24531. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24532. EXPECT_TRUE(
  24533. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24534. EXPECT_TRUE(
  24535. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24536. EXPECT_TRUE(
  24537. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24538. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24539. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24540. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24541. EXPECT_FALSE(
  24542. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24543. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24544. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24545. }
  24546. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24547. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24548. // asks recipients to match each protocol-name case-insensitively, and RFC
  24549. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24550. // client naming websocket alongside another protocol, or on a second field
  24551. // line, is offering websocket; a value that merely contains "websocket" as a
  24552. // substring is a different protocol name and is not.
  24553. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24554. Request req;
  24555. req.method = "GET";
  24556. for (const auto &value : upgrade_values) {
  24557. req.headers.emplace("Upgrade", value);
  24558. }
  24559. req.headers.emplace("Connection", "Upgrade");
  24560. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24561. req.headers.emplace("Sec-WebSocket-Version", "13");
  24562. return req;
  24563. };
  24564. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24565. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24566. EXPECT_TRUE(
  24567. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24568. EXPECT_TRUE(
  24569. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24570. EXPECT_TRUE(
  24571. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24572. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24573. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24574. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24575. EXPECT_FALSE(
  24576. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24577. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24578. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24579. }
  24580. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24581. Server svr;
  24582. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24583. auto port = svr.bind_to_any_port("localhost");
  24584. std::thread t([&]() { svr.listen_after_bind(); });
  24585. auto se = detail::scope_exit([&] {
  24586. svr.stop();
  24587. t.join();
  24588. });
  24589. svr.wait_until_ready();
  24590. Headers headers = {{"Upgrade", "websocket"},
  24591. {"Connection", "notupgrade"},
  24592. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24593. {"Sec-WebSocket-Version", "13"}};
  24594. Client cli("localhost", port);
  24595. auto res = cli.Get("/ws", headers);
  24596. // The route exists only as a WebSocket route, so a request that fails the
  24597. // handshake check falls through to ordinary routing.
  24598. ASSERT_TRUE(res);
  24599. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24600. }
  24601. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24602. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24603. // Connection value is the only thing left for the client to reject.
  24604. Server svr;
  24605. svr.Get("/ws", [](const Request &req, Response &res) {
  24606. res.status = StatusCode::SwitchingProtocol_101;
  24607. res.set_header("Upgrade", "websocket");
  24608. res.set_header("Connection", "notupgrade");
  24609. res.set_header("Sec-WebSocket-Accept",
  24610. detail::websocket_accept_key(
  24611. req.get_header_value("Sec-WebSocket-Key")));
  24612. });
  24613. auto port = svr.bind_to_any_port("localhost");
  24614. std::thread t([&]() { svr.listen_after_bind(); });
  24615. auto se = detail::scope_exit([&] {
  24616. svr.stop();
  24617. t.join();
  24618. });
  24619. svr.wait_until_ready();
  24620. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24621. auto res = client.connect();
  24622. EXPECT_FALSE(res);
  24623. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24624. EXPECT_FALSE(client.is_open());
  24625. }
  24626. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24627. Server svr;
  24628. svr.Get("/ws", [](const Request &req, Response &res) {
  24629. res.status = StatusCode::SwitchingProtocol_101;
  24630. res.set_header("Upgrade", "websocket");
  24631. res.set_header("Connection", "Upgrade");
  24632. res.set_header("Sec-WebSocket-Accept",
  24633. detail::websocket_accept_key(
  24634. req.get_header_value("Sec-WebSocket-Key")));
  24635. res.set_header("Sec-WebSocket-Protocol", "admin");
  24636. });
  24637. auto port = svr.bind_to_any_port("localhost");
  24638. std::thread t([&]() { svr.listen_after_bind(); });
  24639. auto se = detail::scope_exit([&] {
  24640. svr.stop();
  24641. t.join();
  24642. });
  24643. svr.wait_until_ready();
  24644. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24645. // Server selects a subprotocol the client never offered
  24646. {
  24647. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24648. ws::WebSocketClient client(url, headers);
  24649. auto res = client.connect();
  24650. EXPECT_FALSE(res);
  24651. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24652. EXPECT_FALSE(client.is_open());
  24653. EXPECT_TRUE(client.subprotocol().empty());
  24654. }
  24655. // Client offered none but the server named one anyway
  24656. {
  24657. ws::WebSocketClient client(url);
  24658. auto res = client.connect();
  24659. EXPECT_FALSE(res);
  24660. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24661. EXPECT_FALSE(client.is_open());
  24662. EXPECT_TRUE(client.subprotocol().empty());
  24663. }
  24664. }
  24665. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24666. // The socket path doubles as the URL host, so it must not contain '/'.
  24667. const char *shard = getenv("GTEST_SHARD_INDEX");
  24668. const std::string sock_path =
  24669. shard ? std::string("httplib-ws-") + shard + ".sock"
  24670. : std::string("httplib-ws.sock");
  24671. std::remove(sock_path.c_str());
  24672. Server svr;
  24673. std::mutex mtx;
  24674. std::string received_host;
  24675. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24676. {
  24677. std::lock_guard<std::mutex> lock(mtx);
  24678. received_host = req.get_header_value("Host");
  24679. }
  24680. std::string msg;
  24681. while (ws.read(msg)) {
  24682. ws.send(msg);
  24683. }
  24684. });
  24685. svr.set_address_family(AF_UNIX);
  24686. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24687. auto se = detail::scope_exit([&] {
  24688. svr.stop();
  24689. t.join();
  24690. std::remove(sock_path.c_str());
  24691. });
  24692. svr.wait_until_ready();
  24693. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24694. client.set_address_family(AF_UNIX);
  24695. ASSERT_TRUE(client.connect());
  24696. ASSERT_TRUE(client.send("hello"));
  24697. std::string msg;
  24698. ASSERT_TRUE(client.read(msg));
  24699. client.close();
  24700. {
  24701. std::lock_guard<std::mutex> lock(mtx);
  24702. // There is no host:port for a Unix socket, so the same "localhost"
  24703. // placeholder the HTTP client uses is expected.
  24704. EXPECT_EQ("localhost", received_host);
  24705. }
  24706. }
  24707. // Two threads must never parse WebSocket frames from the same stream.
  24708. // close() used to read the peer's Close reply with its own frame read, so it
  24709. // raced a reader thread that was in the middle of a payload: the payload loop
  24710. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24711. // so bytes taken by close() were replaced with bytes from further along the
  24712. // stream. The message kept its length and silently changed content.
  24713. //
  24714. // The raw peer below sends a frame header plus part of the payload, waits for
  24715. // the handler to call close(), and only then sends the rest. Whichever thread
  24716. // would win the race for those bytes, the message must arrive intact, because
  24717. // close() must not touch the stream while read() owns it.
  24718. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24719. #ifndef _WIN32
  24720. signal(SIGPIPE, SIG_IGN);
  24721. #endif
  24722. const size_t payload_len = 120; // fits the 7-bit length field
  24723. const size_t prefix_len = 8;
  24724. const int attempts = 8;
  24725. std::string expected(payload_len, '\0');
  24726. for (size_t i = 0; i < payload_len; i++) {
  24727. expected[i] = static_cast<char>('a' + i % 26);
  24728. }
  24729. std::atomic<bool> peer_stalled{false};
  24730. std::atomic<bool> handler_done{false};
  24731. std::mutex received_mutex;
  24732. std::vector<std::string> received;
  24733. // Bound every wait, so a regression fails the test instead of hanging the
  24734. // suite.
  24735. auto wait_for = [](const std::atomic<bool> &flag) {
  24736. for (int i = 0; i < 500 && !flag; i++) {
  24737. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24738. }
  24739. };
  24740. Server svr;
  24741. svr.set_websocket_ping_interval(0);
  24742. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24743. std::thread reader([&]() {
  24744. std::string msg;
  24745. while (ws.read(msg)) {
  24746. std::lock_guard<std::mutex> guard(received_mutex);
  24747. received.push_back(msg);
  24748. }
  24749. });
  24750. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24751. // inside read_websocket_frame() when close() runs.
  24752. wait_for(peer_stalled);
  24753. ws.close();
  24754. reader.join();
  24755. handler_done = true;
  24756. });
  24757. auto port = svr.bind_to_any_port("127.0.0.1");
  24758. std::thread t([&]() { svr.listen_after_bind(); });
  24759. auto se = detail::scope_exit([&] {
  24760. svr.stop();
  24761. t.join();
  24762. });
  24763. svr.wait_until_ready();
  24764. auto send_bytes = [](socket_t s, const std::string &data) {
  24765. #ifdef _WIN32
  24766. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24767. #else
  24768. auto n = ::send(s, data.data(), data.size(), 0);
  24769. #endif
  24770. return n == static_cast<decltype(n)>(data.size());
  24771. };
  24772. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24773. // Every length used here fits the 7-bit length field.
  24774. auto masked_header = [](uint8_t first_byte, size_t len) {
  24775. std::string h;
  24776. h += static_cast<char>(first_byte);
  24777. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24778. h.append(4, '\0'); // mask key
  24779. return h;
  24780. };
  24781. for (int attempt = 0; attempt < attempts; attempt++) {
  24782. peer_stalled = false;
  24783. handler_done = false;
  24784. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24785. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24786. auto se_sock = detail::scope_exit([&] {
  24787. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24788. });
  24789. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24790. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24791. sockaddr_in addr{};
  24792. addr.sin_family = AF_INET;
  24793. addr.sin_port = htons(static_cast<uint16_t>(port));
  24794. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24795. ASSERT_EQ(
  24796. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24797. << "attempt " << attempt;
  24798. ASSERT_TRUE(send_bytes(sock,
  24799. "GET /ws HTTP/1.1\r\n"
  24800. "Host: 127.0.0.1\r\n"
  24801. "Upgrade: websocket\r\n"
  24802. "Connection: Upgrade\r\n"
  24803. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24804. "Sec-WebSocket-Version: 13\r\n"
  24805. "\r\n"))
  24806. << "attempt " << attempt;
  24807. std::string response;
  24808. while (response.find("\r\n\r\n") == std::string::npos) {
  24809. char buf[512];
  24810. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24811. if (n <= 0) { break; }
  24812. response.append(buf, static_cast<size_t>(n));
  24813. }
  24814. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24815. << "attempt " << attempt;
  24816. // Send the header of a Binary message but only the first prefix_len bytes
  24817. // of its payload, leaving the reader thread stalled inside the payload.
  24818. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24819. expected.substr(0, prefix_len)))
  24820. << "attempt " << attempt;
  24821. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24822. peer_stalled = true;
  24823. // Let close() send its Close frame and park in its own read before the
  24824. // rest of the payload arrives, so both threads are waiting for it.
  24825. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24826. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24827. close_frame += static_cast<char>(0x03); // status 1000
  24828. close_frame += static_cast<char>(0xE8);
  24829. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24830. << "attempt " << attempt;
  24831. // Closing the peer releases the reader thread even on the buggy path,
  24832. // where it waits for bytes another thread already consumed.
  24833. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24834. detail::close_socket(sock);
  24835. sock = INVALID_SOCKET;
  24836. wait_for(handler_done);
  24837. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24838. }
  24839. std::lock_guard<std::mutex> guard(received_mutex);
  24840. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24841. << "a message in flight when close() ran was dropped";
  24842. for (size_t i = 0; i < received.size(); i++) {
  24843. EXPECT_EQ(expected, received[i]) << "message " << i;
  24844. }
  24845. }
  24846. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24847. // returning the socket, or INVALID_SOCKET.
  24848. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24849. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24850. if (sock == INVALID_SOCKET) { return sock; }
  24851. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24852. sockaddr_in addr{};
  24853. addr.sin_family = AF_INET;
  24854. addr.sin_port = htons(static_cast<uint16_t>(port));
  24855. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24856. std::string req = "GET " + path +
  24857. " HTTP/1.1\r\n"
  24858. "Host: 127.0.0.1\r\n"
  24859. "Upgrade: websocket\r\n"
  24860. "Connection: Upgrade\r\n"
  24861. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24862. "Sec-WebSocket-Version: 13\r\n"
  24863. "\r\n";
  24864. std::string res;
  24865. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24866. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24867. static_cast<ssize_t>(req.size())) {
  24868. char c;
  24869. while (res.find("\r\n\r\n") == std::string::npos &&
  24870. ::recv(sock, &c, 1, 0) == 1) {
  24871. res += c;
  24872. }
  24873. }
  24874. if (res.find(" 101 ") == std::string::npos) {
  24875. detail::close_socket(sock);
  24876. return INVALID_SOCKET;
  24877. }
  24878. return sock;
  24879. }
  24880. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24881. // The payload must fit the 7-bit length field.
  24882. static std::string masked_frame(uint8_t first_byte,
  24883. const std::string &payload) {
  24884. std::string f;
  24885. f += static_cast<char>(first_byte);
  24886. f += static_cast<char>(0x80 | payload.size());
  24887. f.append(4, '\0');
  24888. return f + payload;
  24889. }
  24890. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24891. std::atomic<bool> done{false};
  24892. std::string received;
  24893. Server svr;
  24894. svr.set_websocket_ping_interval(0);
  24895. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24896. std::string msg;
  24897. if (ws.read(msg) == ws::Binary) { received = msg; }
  24898. done = true;
  24899. });
  24900. auto port = svr.bind_to_any_port("127.0.0.1");
  24901. std::thread t([&]() { svr.listen_after_bind(); });
  24902. auto se = detail::scope_exit([&] {
  24903. svr.stop();
  24904. t.join();
  24905. });
  24906. svr.wait_until_ready();
  24907. auto sock = connect_raw_websocket(port, "/ws");
  24908. ASSERT_NE(INVALID_SOCKET, sock);
  24909. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24910. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24911. masked_frame(0x89, "p") + // FIN + Ping
  24912. masked_frame(0x80, "lo"); // FIN + Continuation
  24913. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24914. for (int i = 0; i < 500 && !done; i++) {
  24915. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24916. }
  24917. ASSERT_TRUE(done);
  24918. EXPECT_EQ("Hello", received);
  24919. // The Ping between the fragments is answered with a Pong.
  24920. char pong[3];
  24921. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24922. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24923. }
  24924. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24925. Server svr;
  24926. svr.set_websocket_ping_interval(-1);
  24927. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24928. std::string msg;
  24929. while (ws.read(msg)) {}
  24930. });
  24931. auto port = svr.bind_to_any_port("127.0.0.1");
  24932. std::thread t([&]() { svr.listen_after_bind(); });
  24933. auto se = detail::scope_exit([&] {
  24934. svr.stop();
  24935. t.join();
  24936. });
  24937. svr.wait_until_ready();
  24938. auto sock = connect_raw_websocket(port, "/ws");
  24939. ASSERT_NE(INVALID_SOCKET, sock);
  24940. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24941. // Nothing comes while the client stays quiet.
  24942. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24943. char c;
  24944. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24945. }
  24946. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24947. // and that has to end a read() already waiting on the peer, on every platform.
  24948. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24949. // The peer sends no pings, and its handler never calls read(), which is
  24950. // where pongs are written.
  24951. std::mutex mutex;
  24952. std::condition_variable cv;
  24953. auto release = false;
  24954. svr.set_websocket_ping_interval(0);
  24955. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24956. std::unique_lock<std::mutex> lock(mutex);
  24957. cv.wait(lock, [&] { return release; });
  24958. });
  24959. auto port = svr.bind_to_any_port(HOST);
  24960. std::thread t([&]() { svr.listen_after_bind(); });
  24961. auto se = detail::scope_exit([&] {
  24962. {
  24963. std::lock_guard<std::mutex> lock(mutex);
  24964. release = true;
  24965. }
  24966. cv.notify_all();
  24967. svr.stop();
  24968. t.join();
  24969. });
  24970. svr.wait_until_ready();
  24971. ws::WebSocketClient client(std::string(scheme) +
  24972. "://localhost:" + std::to_string(port) + "/ws");
  24973. #ifdef CPPHTTPLIB_SSL_ENABLED
  24974. client.enable_server_certificate_verification(false);
  24975. #endif
  24976. // A ping a second, given up on after two go unanswered: about 3s
  24977. client.set_websocket_ping_interval(1);
  24978. client.set_websocket_max_missed_pongs(2);
  24979. // Well past that, so that a read the timeout ends instead stands out
  24980. client.set_read_timeout(10);
  24981. ASSERT_TRUE(client.connect());
  24982. auto start = std::chrono::steady_clock::now();
  24983. std::string msg;
  24984. EXPECT_EQ(ws::Fail, client.read(msg));
  24985. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24986. std::chrono::steady_clock::now() - start)
  24987. .count(),
  24988. 6000);
  24989. EXPECT_FALSE(client.is_open());
  24990. }
  24991. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24992. Server svr;
  24993. check_pong_timeout_ends_read(svr, "ws");
  24994. }
  24995. #ifdef CPPHTTPLIB_SSL_ENABLED
  24996. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24997. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24998. ASSERT_TRUE(svr.is_valid());
  24999. check_pong_timeout_ends_read(svr, "wss");
  25000. }
  25001. #endif
  25002. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  25003. Server svr;
  25004. svr.set_websocket_ping_interval(0);
  25005. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25006. std::string msg;
  25007. while (ws.read(msg)) {}
  25008. });
  25009. auto port = svr.bind_to_any_port("127.0.0.1");
  25010. std::thread t([&]() { svr.listen_after_bind(); });
  25011. auto se = detail::scope_exit([&] {
  25012. svr.stop();
  25013. t.join();
  25014. });
  25015. svr.wait_until_ready();
  25016. // Each Close payload and the reply it should get: an echo when valid, 1002
  25017. // otherwise.
  25018. std::vector<std::pair<std::string, std::string>> cases = {
  25019. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  25020. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  25021. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  25022. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  25023. };
  25024. // Also between the fragments of a message.
  25025. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  25026. for (const auto &c : cases) {
  25027. auto sock = connect_raw_websocket(port, "/ws");
  25028. ASSERT_NE(INVALID_SOCKET, sock);
  25029. auto frames = prefix + masked_frame(0x88, c.first);
  25030. detail::send_socket(sock, frames.data(), frames.size(), 0);
  25031. std::string reply;
  25032. char buf[256];
  25033. while (reply.size() < 2 + c.second.size()) {
  25034. auto n = ::recv(sock, buf, sizeof(buf), 0);
  25035. if (n <= 0) { break; }
  25036. reply.append(buf, static_cast<size_t>(n));
  25037. }
  25038. detail::close_socket(sock);
  25039. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  25040. c.second,
  25041. reply);
  25042. }
  25043. }
  25044. }
  25045. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  25046. class WebSocketSSLIntegrationTest : public ::testing::Test {
  25047. protected:
  25048. void SetUp() override {
  25049. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  25050. SERVER_PRIVATE_KEY_FILE);
  25051. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25052. std::string msg;
  25053. ws::ReadResult ret;
  25054. while ((ret = ws.read(msg))) {
  25055. if (ret == ws::Binary) {
  25056. ws.send(msg.data(), msg.size());
  25057. } else {
  25058. ws.send(msg);
  25059. }
  25060. }
  25061. });
  25062. port_ = server_->bind_to_any_port(HOST);
  25063. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25064. server_->wait_until_ready();
  25065. }
  25066. void TearDown() override {
  25067. server_->stop();
  25068. if (server_thread_.joinable()) { server_thread_.join(); }
  25069. }
  25070. std::unique_ptr<SSLServer> server_;
  25071. std::thread server_thread_;
  25072. int port_ = 0;
  25073. };
  25074. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  25075. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25076. {
  25077. ws::WebSocketClient client(url);
  25078. client.enable_server_certificate_verification(false);
  25079. auto calls = 0;
  25080. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  25081. calls++;
  25082. return false;
  25083. });
  25084. EXPECT_FALSE(client.connect());
  25085. EXPECT_GT(calls, 0);
  25086. }
  25087. {
  25088. ws::WebSocketClient client(url);
  25089. client.enable_server_certificate_verification(false);
  25090. client.set_session_verifier([](tls::session_t) {
  25091. return SSLVerifierResponse::CertificateRejected;
  25092. });
  25093. EXPECT_FALSE(client.connect());
  25094. }
  25095. {
  25096. ws::WebSocketClient client(url);
  25097. client.enable_server_certificate_verification(false);
  25098. client.set_session_verifier([](tls::session_t) {
  25099. return SSLVerifierResponse::CertificateAccepted;
  25100. });
  25101. EXPECT_TRUE(client.connect());
  25102. }
  25103. }
  25104. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  25105. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25106. "/ws-echo");
  25107. client.enable_server_certificate_verification(false);
  25108. ASSERT_TRUE(client.connect());
  25109. ASSERT_TRUE(client.is_open());
  25110. ASSERT_TRUE(client.send("Hello WSS"));
  25111. std::string msg;
  25112. EXPECT_EQ(ws::Text, client.read(msg));
  25113. EXPECT_EQ("Hello WSS", msg);
  25114. client.close();
  25115. }
  25116. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  25117. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  25118. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  25119. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  25120. // client (without calling close() first) is the only path that runs
  25121. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  25122. // bug exactly.
  25123. //
  25124. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  25125. // when linked against an instrumented libssl; run under Valgrind to catch it
  25126. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  25127. // suite (the freed session otherwise stalls on the close handshake) — this test
  25128. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  25129. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  25130. {
  25131. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25132. "/ws-echo");
  25133. client.enable_server_certificate_verification(false);
  25134. client.set_read_timeout(2, 0);
  25135. client.set_write_timeout(2, 0);
  25136. ASSERT_TRUE(client.connect());
  25137. ASSERT_TRUE(client.is_open());
  25138. ASSERT_TRUE(client.send("still open"));
  25139. // Intentionally do NOT call client.close(): leaving scope runs
  25140. // shutdown_and_close() with the WebSocket still open, which must send the
  25141. // close frame while the TLS session is still alive.
  25142. }
  25143. }
  25144. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  25145. // shutdown_and_close() at the start of connect(), reproducing the same
  25146. // use-after-free within the test body rather than at scope exit. The second
  25147. // connect must succeed and echo, proving the close handshake ran over a live
  25148. // session. See the note above about memory-tool requirements.
  25149. TEST_F(WebSocketSSLIntegrationTest,
  25150. ReconnectWhileOpenSendsCloseOverLiveSession) {
  25151. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  25152. "/ws-echo");
  25153. client.enable_server_certificate_verification(false);
  25154. client.set_read_timeout(2, 0);
  25155. client.set_write_timeout(2, 0);
  25156. ASSERT_TRUE(client.connect());
  25157. ASSERT_TRUE(client.is_open());
  25158. ASSERT_TRUE(client.send("still open"));
  25159. // Reconnect without closing first: connect() calls shutdown_and_close() on
  25160. // the still-open connection, which must not touch a freed TLS session.
  25161. ASSERT_TRUE(client.connect());
  25162. ASSERT_TRUE(client.is_open());
  25163. ASSERT_TRUE(client.send("after reconnect"));
  25164. std::string msg;
  25165. EXPECT_EQ(ws::Text, client.read(msg));
  25166. EXPECT_EQ("after reconnect", msg);
  25167. client.close();
  25168. }
  25169. #endif
  25170. #ifdef CPPHTTPLIB_SSL_ENABLED
  25171. class WebSocketSSLCATest : public ::testing::Test {
  25172. protected:
  25173. void SetUp() override {
  25174. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  25175. SERVER_PRIVATE_KEY_FILE);
  25176. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25177. std::string msg;
  25178. while (ws.read(msg)) {
  25179. ws.send(msg);
  25180. }
  25181. });
  25182. port_ = server_->bind_to_any_port("127.0.0.1");
  25183. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25184. server_->wait_until_ready();
  25185. }
  25186. void TearDown() override {
  25187. server_->stop();
  25188. if (server_thread_.joinable()) { server_thread_.join(); }
  25189. }
  25190. std::string url() const {
  25191. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  25192. }
  25193. std::unique_ptr<SSLServer> server_;
  25194. std::thread server_thread_;
  25195. int port_ = 0;
  25196. };
  25197. // A custom CA loaded as PEM verifies the server with full certificate
  25198. // verification enabled
  25199. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  25200. ws::WebSocketClient client(url());
  25201. std::string cert;
  25202. read_file(SERVER_CERT2_FILE, cert);
  25203. client.load_ca_cert_store(cert.c_str(), cert.size());
  25204. ASSERT_TRUE(client.connect());
  25205. ASSERT_TRUE(client.send("hello"));
  25206. std::string msg;
  25207. EXPECT_EQ(ws::Text, client.read(msg));
  25208. EXPECT_EQ("hello", msg);
  25209. client.close();
  25210. }
  25211. // A custom CA that does not cover the server must fail verification (the
  25212. // custom CA is exclusive; system certs are not loaded alongside it)
  25213. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  25214. ws::WebSocketClient client(url());
  25215. std::string cert;
  25216. read_file(CLIENT_CA_CERT_FILE, cert);
  25217. client.load_ca_cert_store(cert.c_str(), cert.size());
  25218. auto res = client.connect();
  25219. ASSERT_FALSE(res);
  25220. EXPECT_EQ(Error::SSLServerVerification, res.error());
  25221. EXPECT_EQ(-1, res.status());
  25222. EXPECT_NE(0u, res.ssl_backend_error());
  25223. }
  25224. // The same CA as a file path rather than PEM in memory
  25225. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  25226. ws::WebSocketClient client(url());
  25227. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25228. ASSERT_TRUE(client.connect());
  25229. ASSERT_TRUE(client.send("hello"));
  25230. std::string msg;
  25231. EXPECT_EQ(ws::Text, client.read(msg));
  25232. EXPECT_EQ("hello", msg);
  25233. client.close();
  25234. }
  25235. // ...and a CA file that does not cover the server still fails, so it is the
  25236. // path above that decides the outcome
  25237. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  25238. ws::WebSocketClient client(url());
  25239. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25240. ASSERT_FALSE(client.connect());
  25241. }
  25242. // Regression test: reconnecting with a native custom CA store used to reuse
  25243. // a store handle the previous TLS context had already freed (use-after-free
  25244. // under the OpenSSL backend). The context now lives as long as the client.
  25245. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  25246. ws::WebSocketClient client(url());
  25247. std::string cert;
  25248. read_file(SERVER_CERT2_FILE, cert);
  25249. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  25250. ASSERT_TRUE(client.connect());
  25251. client.close();
  25252. ASSERT_TRUE(client.connect());
  25253. ASSERT_TRUE(client.send("again"));
  25254. std::string msg;
  25255. EXPECT_EQ(ws::Text, client.read(msg));
  25256. EXPECT_EQ("again", msg);
  25257. client.close();
  25258. }
  25259. // Regression test: a certificate with a trusted chain but no identity match
  25260. // for the server IP must be rejected. The Mbed TLS backend used to skip
  25261. // verification entirely for IP hosts, so this connection succeeded there.
  25262. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  25263. // chain verification while the identity check must still fail.
  25264. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  25265. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  25266. ASSERT_TRUE(svr.is_valid());
  25267. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25268. std::string msg;
  25269. while (ws.read(msg)) {
  25270. ws.send(msg);
  25271. }
  25272. });
  25273. auto port = svr.bind_to_any_port("127.0.0.1");
  25274. auto t = std::thread([&]() { svr.listen_after_bind(); });
  25275. auto se = detail::scope_exit([&] {
  25276. svr.stop();
  25277. t.join();
  25278. });
  25279. svr.wait_until_ready();
  25280. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  25281. "/echo");
  25282. std::string cert;
  25283. read_file(SERVER_CERT_FILE, cert);
  25284. client.load_ca_cert_store(cert.c_str(), cert.size());
  25285. ASSERT_FALSE(client.connect());
  25286. }
  25287. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  25288. // SNI, so nothing binds the host name to the TLS session. These bind the
  25289. // server to "localhost" instead, the only shape that exercises the SNI and
  25290. // hostname-verification path with certificate verification left enabled.
  25291. class WebSocketSSLDnsHostTest : public ::testing::Test {
  25292. protected:
  25293. void Start(const char *cert_file) {
  25294. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  25295. SERVER_PRIVATE_KEY_FILE);
  25296. ASSERT_TRUE(server_->is_valid());
  25297. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  25298. std::string msg;
  25299. while (ws.read(msg)) {
  25300. ws.send(msg);
  25301. }
  25302. });
  25303. port_ = server_->bind_to_any_port("localhost");
  25304. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25305. server_->wait_until_ready();
  25306. }
  25307. void TearDown() override {
  25308. if (server_) { server_->stop(); }
  25309. if (server_thread_.joinable()) { server_thread_.join(); }
  25310. }
  25311. std::string url() const {
  25312. return "wss://localhost:" + std::to_string(port_) + "/echo";
  25313. }
  25314. std::unique_ptr<SSLServer> server_;
  25315. std::thread server_thread_;
  25316. int port_ = 0;
  25317. };
  25318. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  25319. // out and the connection is usable
  25320. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  25321. Start(SERVER_CERT2_FILE);
  25322. ws::WebSocketClient client(url());
  25323. client.set_ca_cert_path(SERVER_CERT2_FILE);
  25324. ASSERT_TRUE(client.connect());
  25325. ASSERT_TRUE(client.send("hello"));
  25326. std::string msg;
  25327. EXPECT_EQ(ws::Text, client.read(msg));
  25328. EXPECT_EQ("hello", msg);
  25329. client.close();
  25330. }
  25331. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  25332. // while the identity check must still reject "localhost"
  25333. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  25334. Start(SERVER_CERT_FILE);
  25335. ws::WebSocketClient client(url());
  25336. client.set_ca_cert_path(SERVER_CERT_FILE);
  25337. auto res = client.connect();
  25338. ASSERT_FALSE(res);
  25339. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  25340. EXPECT_EQ(-1, res.status());
  25341. }
  25342. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  25343. // disabled: the chain is still checked, only the identity check is skipped
  25344. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  25345. Start(SERVER_CERT_FILE);
  25346. ws::WebSocketClient client(url());
  25347. client.set_ca_cert_path(SERVER_CERT_FILE);
  25348. client.enable_server_hostname_verification(false);
  25349. ASSERT_TRUE(client.connect());
  25350. ASSERT_TRUE(client.send("hello"));
  25351. std::string msg;
  25352. EXPECT_EQ(ws::Text, client.read(msg));
  25353. EXPECT_EQ("hello", msg);
  25354. client.close();
  25355. }
  25356. // A CA that did not sign the server certificate fails the chain, even though
  25357. // the name would match
  25358. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  25359. Start(SERVER_CERT2_FILE);
  25360. ws::WebSocketClient client(url());
  25361. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  25362. ASSERT_FALSE(client.connect());
  25363. }
  25364. // With verification disabled, neither the chain nor the name is checked
  25365. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  25366. Start(SERVER_CERT_FILE);
  25367. ws::WebSocketClient client(url());
  25368. client.enable_server_certificate_verification(false);
  25369. ASSERT_TRUE(client.connect());
  25370. ASSERT_TRUE(client.send("hello"));
  25371. std::string msg;
  25372. EXPECT_EQ(ws::Text, client.read(msg));
  25373. EXPECT_EQ("hello", msg);
  25374. client.close();
  25375. }
  25376. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  25377. protected:
  25378. void SetUp() override {
  25379. server_ = httplib::detail::make_unique<SSLServer>(
  25380. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  25381. ASSERT_TRUE(server_->is_valid());
  25382. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  25383. std::string msg;
  25384. while (ws.read(msg)) {
  25385. ws.send(msg);
  25386. }
  25387. });
  25388. port_ = server_->bind_to_any_port("localhost");
  25389. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  25390. server_->wait_until_ready();
  25391. }
  25392. void TearDown() override {
  25393. server_->stop();
  25394. if (server_thread_.joinable()) { server_thread_.join(); }
  25395. }
  25396. std::string url() const {
  25397. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  25398. }
  25399. void ConnectWithClientCert(const std::string &client_cert_file,
  25400. const std::string &client_private_key_file,
  25401. const char *private_key_password) {
  25402. std::string cert_pem, key_pem;
  25403. read_file(client_cert_file, cert_pem);
  25404. read_file(client_private_key_file, key_pem);
  25405. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  25406. key_pem.c_str(), key_pem.size(),
  25407. private_key_password};
  25408. ConnectWithPem(pem);
  25409. }
  25410. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25411. ws::WebSocketClient client(url(), pem);
  25412. ASSERT_TRUE(client.is_valid());
  25413. client.enable_server_certificate_verification(false);
  25414. ASSERT_TRUE(client.connect());
  25415. ASSERT_TRUE(client.send("hello"));
  25416. std::string msg;
  25417. EXPECT_EQ(ws::Text, client.read(msg));
  25418. EXPECT_EQ("hello", msg);
  25419. client.close();
  25420. }
  25421. std::unique_ptr<SSLServer> server_;
  25422. std::thread server_thread_;
  25423. int port_ = 0;
  25424. };
  25425. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25426. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25427. }
  25428. // Control for the tests above: the fixture's server really does require a
  25429. // client certificate, so it is the PEM the constructor installed that decides
  25430. // the outcome.
  25431. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25432. ws::WebSocketClient client(url());
  25433. ASSERT_TRUE(client.is_valid());
  25434. client.enable_server_certificate_verification(false);
  25435. EXPECT_FALSE(client.connect());
  25436. }
  25437. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25438. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25439. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25440. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25441. }
  25442. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25443. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25444. std::string cert_pem, key_pem;
  25445. read_file(CLIENT_CERT_FILE, cert_pem);
  25446. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25447. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25448. std::vector<char> key(key_pem.begin(), key_pem.end());
  25449. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25450. key.size(), nullptr};
  25451. ConnectWithPem(pem);
  25452. }
  25453. #endif
  25454. #if !defined(_WIN32)
  25455. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25456. auto secret_dir = std::string("./symlink_test_secret");
  25457. auto served_dir = std::string("./symlink_test_served");
  25458. auto secret_file = secret_dir + "/secret.txt";
  25459. auto symlink_path = served_dir + "/escape";
  25460. // Setup: create directories and files
  25461. mkdir(secret_dir.c_str(), 0755);
  25462. mkdir(served_dir.c_str(), 0755);
  25463. {
  25464. std::ofstream ofs(secret_file);
  25465. ofs << "SECRET_DATA";
  25466. }
  25467. // Create symlink using absolute path so it resolves correctly
  25468. #ifdef PATH_MAX
  25469. char abs_secret[PATH_MAX];
  25470. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25471. #else
  25472. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25473. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25474. ASSERT_NE(nullptr, abs_secret);
  25475. #endif
  25476. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25477. auto se = detail::scope_exit([&] {
  25478. unlink(symlink_path.c_str());
  25479. unlink(secret_file.c_str());
  25480. rmdir(served_dir.c_str());
  25481. rmdir(secret_dir.c_str());
  25482. });
  25483. Server svr;
  25484. svr.set_mount_point("/", served_dir);
  25485. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25486. auto se2 = detail::scope_exit([&] {
  25487. svr.stop();
  25488. listen_thread.join();
  25489. });
  25490. svr.wait_until_ready();
  25491. Client cli("localhost", PORT);
  25492. // Symlink pointing outside base dir should be blocked
  25493. auto res = cli.Get("/escape/secret.txt");
  25494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25495. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25496. }
  25497. #endif
  25498. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25499. // "GET /smuggled" request), reads the first response, and only then sends the
  25500. // embedded request as the body. Returns how many times /smuggled ran.
  25501. //
  25502. // The body is sent AFTER receiving the first response (as in the original
  25503. // PoC) so that the stream_line_reader cannot buffer it together with the
  25504. // headers of the first request.
  25505. static int count_smuggled_requests(const std::string &outer_head,
  25506. std::string &first_response) {
  25507. Server svr;
  25508. svr.set_mount_point("/", "./www");
  25509. std::atomic<int> smuggled_count(0);
  25510. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25511. smuggled_count++;
  25512. res.set_content("oops", "text/plain");
  25513. });
  25514. svr.Post("/post", [&](const Request &req, Response &res) {
  25515. res.set_content(req.body, "text/plain");
  25516. });
  25517. auto port = svr.bind_to_any_port("localhost");
  25518. thread t = thread([&] { svr.listen_after_bind(); });
  25519. auto se = detail::scope_exit([&] {
  25520. svr.stop();
  25521. t.join();
  25522. });
  25523. svr.wait_until_ready();
  25524. auto error = Error::Success;
  25525. auto sock = detail::create_client_socket(
  25526. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25527. /*connection_timeout_sec=*/2, 0,
  25528. /*read_timeout_sec=*/2, 0,
  25529. /*write_timeout_sec=*/2, 0, std::string(), error);
  25530. EXPECT_NE(INVALID_SOCKET, sock);
  25531. if (sock == INVALID_SOCKET) { return -1; }
  25532. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25533. // The "smuggled" request will be sent as the body of the outer request
  25534. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25535. "Host: localhost\r\n"
  25536. "Connection: close\r\n"
  25537. "\r\n";
  25538. auto head = outer_head;
  25539. auto len = std::to_string(smuggled.size());
  25540. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25541. pos = head.find("{len}", pos + len.size())) {
  25542. head.replace(pos, 5, len);
  25543. }
  25544. // Step 1: Send only the outer request headers (no body yet)
  25545. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25546. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25547. // Step 2: Read the first response
  25548. char buf[4096];
  25549. for (;;) {
  25550. auto n = recv(sock, buf, sizeof(buf), 0);
  25551. if (n <= 0) break;
  25552. first_response.append(buf, static_cast<size_t>(n));
  25553. // Stop once we have a complete response (headers + body)
  25554. auto hdr_end = first_response.find("\r\n\r\n");
  25555. if (hdr_end != std::string::npos) {
  25556. // Check for Content-Length to know when the body is complete
  25557. auto cl_pos = first_response.find("Content-Length:");
  25558. if (cl_pos != std::string::npos) {
  25559. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25560. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25561. auto cl = std::stoul(
  25562. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25563. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25564. } else {
  25565. break; // No Content-Length, assume headers-only response
  25566. }
  25567. }
  25568. }
  25569. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25570. // vulnerable server the keep-alive loop reads this as a second request. The
  25571. // server may already have closed the connection, so the result is ignored.
  25572. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25573. // Half-close so that a server which drained the body sees EOF and closes,
  25574. // instead of the read below waiting for the read timeout.
  25575. #ifdef _WIN32
  25576. ::shutdown(sock, SD_SEND);
  25577. #else
  25578. ::shutdown(sock, SHUT_WR);
  25579. #endif
  25580. // Step 4: Read until the server closes the connection
  25581. for (;;) {
  25582. auto n = recv(sock, buf, sizeof(buf), 0);
  25583. if (n <= 0) break;
  25584. }
  25585. return smuggled_count.load();
  25586. }
  25587. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25588. // A GET request with Content-Length to a static file handler must have its
  25589. // body drained before the keep-alive connection is reused. Otherwise the
  25590. // unread body bytes are interpreted as the next HTTP request.
  25591. std::string first_response;
  25592. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25593. "Host: localhost\r\n"
  25594. "Content-Length: {len}\r\n"
  25595. "\r\n",
  25596. first_response));
  25597. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25598. }
  25599. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25600. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25601. // be answered with 400 and the connection closed. Treating it as "no body"
  25602. // leaves the body to be parsed as the next request.
  25603. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25604. const char *targets[] = {
  25605. "GET /file", // handler that never reads the body
  25606. "GET /not-found", // no handler matches (404)
  25607. "POST /post", // handler that reads the body
  25608. };
  25609. for (auto target : targets) {
  25610. for (auto value : values) {
  25611. std::string first_response;
  25612. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25613. " HTTP/1.1\r\n"
  25614. "Host: localhost\r\n"
  25615. "Content-Length: " +
  25616. value + "\r\n\r\n",
  25617. first_response))
  25618. << target << " with Content-Length: " << value;
  25619. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25620. << target << " with Content-Length: " << value;
  25621. }
  25622. }
  25623. }
  25624. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25625. // A 400 for an unparseable request line leaves the rest of the message
  25626. // unread, so the connection must be closed rather than reused.
  25627. std::string first_response;
  25628. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25629. "Host: localhost\r\n"
  25630. "Content-Length: {len}\r\n"
  25631. "\r\n",
  25632. first_response));
  25633. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25634. }
  25635. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25636. // Same as above for a header block that fails to parse.
  25637. std::string first_response;
  25638. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25639. "Host: localhost\r\n"
  25640. "Bad Header\r\n"
  25641. "Content-Length: {len}\r\n"
  25642. "\r\n",
  25643. first_response));
  25644. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25645. }
  25646. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25647. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25648. // server must not read another request on that connection, even when the
  25649. // request had no body to drain.
  25650. std::string first_response;
  25651. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25652. "Host: localhost\r\n"
  25653. "\r\n",
  25654. first_response));
  25655. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25656. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25657. }
  25658. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25659. // A content reader that stops early leaves the stream inside the body.
  25660. // Draining the whole Content-Length from there, or reading the body again,
  25661. // reads into the next request, and whatever follows is parsed as a request
  25662. // of its own.
  25663. Server svr;
  25664. std::atomic<int> smuggled_count(0);
  25665. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25666. svr.Post("/upload", [](const Request &req, Response &res,
  25667. const ContentReader &content_reader) {
  25668. // Stop at the last chunk, so the whole body has been read however it
  25669. // arrives.
  25670. auto length = req.get_header_value_u64("Content-Length");
  25671. size_t total = 0;
  25672. auto consumed = content_reader([&](const char *, size_t n) {
  25673. total += n;
  25674. return total < length;
  25675. });
  25676. EXPECT_FALSE(consumed);
  25677. if (req.has_param("retry")) {
  25678. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25679. }
  25680. // Replace the 400 the aborted read set, which would close the connection.
  25681. res.set_redirect("/done");
  25682. });
  25683. auto port = svr.bind_to_any_port(HOST);
  25684. thread t = thread([&] { svr.listen_after_bind(); });
  25685. auto se = detail::scope_exit([&] {
  25686. svr.stop();
  25687. t.join();
  25688. });
  25689. svr.wait_until_ready();
  25690. // A front end sees the second request as a POST whose body is the GET. The
  25691. // first body is as long as the POST's headers, so draining it again reads
  25692. // exactly those and leaves the GET to be parsed next.
  25693. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25694. "Host: localhost\r\n"
  25695. "\r\n";
  25696. std::string second_head = "POST /post HTTP/1.1\r\n"
  25697. "Host: localhost\r\n"
  25698. "Content-Length: " +
  25699. std::to_string(inner.size()) +
  25700. "\r\n"
  25701. "\r\n";
  25702. for (auto target : {"/upload", "/upload?retry"}) {
  25703. smuggled_count = 0;
  25704. std::string request = "POST " + std::string(target) +
  25705. " HTTP/1.1\r\n"
  25706. "Host: localhost\r\n"
  25707. "Content-Length: " +
  25708. std::to_string(second_head.size()) +
  25709. "\r\n"
  25710. "\r\n" +
  25711. std::string(second_head.size(), 'A') + second_head +
  25712. inner;
  25713. std::string response;
  25714. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25715. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25716. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25717. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25718. EXPECT_EQ(0, smuggled_count.load()) << target;
  25719. }
  25720. }
  25721. // An error response closes the connection anyway, so the body is left unread
  25722. // with a redirect, such as one to a login page.
  25723. static void serve_redirects(Server &svr,
  25724. const std::function<void(int)> &client) {
  25725. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25726. res.set_redirect("/login");
  25727. return Server::HandlerResponse::Handled;
  25728. });
  25729. auto port = svr.bind_to_any_port(HOST);
  25730. ASSERT_GT(port, 0);
  25731. thread t = thread([&] { svr.listen_after_bind(); });
  25732. auto se = detail::scope_exit([&] {
  25733. svr.stop();
  25734. t.join();
  25735. ASSERT_FALSE(svr.is_running());
  25736. });
  25737. svr.wait_until_ready();
  25738. client(port);
  25739. }
  25740. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25741. Server svr;
  25742. serve_redirects(svr, [](int port) {
  25743. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25744. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25745. std::to_string(body.size()) + "\r\n\r\n" + body +
  25746. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25747. std::string resp;
  25748. ASSERT_TRUE(send_request(1, req, &resp, port));
  25749. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25750. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25751. });
  25752. }
  25753. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25754. Server svr;
  25755. svr.set_read_timeout(0, 200000);
  25756. serve_redirects(svr, [](int port) {
  25757. // A byte every 100 ms keeps each read within the read timeout, but not the
  25758. // body as a whole, so the server closes and the bytes sent after that fail.
  25759. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25760. "Content-Length: 10\r\n\r\n"};
  25761. parts.resize(11, "x");
  25762. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25763. });
  25764. }
  25765. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25766. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25767. // must be rejected with 400 Bad Request.
  25768. Server svr;
  25769. svr.Post("/test", [&](const Request &, Response &res) {
  25770. res.set_content("ok", "text/plain");
  25771. });
  25772. thread t = thread([&] { svr.listen(HOST, PORT); });
  25773. auto se = detail::scope_exit([&] {
  25774. svr.stop();
  25775. t.join();
  25776. ASSERT_FALSE(svr.is_running());
  25777. });
  25778. svr.wait_until_ready();
  25779. // Exact "chunked"
  25780. {
  25781. auto req = "POST /test HTTP/1.1\r\n"
  25782. "Host: localhost\r\n"
  25783. "Content-Length: 5\r\n"
  25784. "Transfer-Encoding: chunked\r\n"
  25785. "Connection: close\r\n"
  25786. "\r\n"
  25787. "hello";
  25788. std::string response;
  25789. ASSERT_TRUE(send_request(1, req, &response));
  25790. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25791. response.substr(0, response.find("\r\n")));
  25792. }
  25793. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25794. {
  25795. auto req = "POST /test HTTP/1.1\r\n"
  25796. "Host: localhost\r\n"
  25797. "Content-Length: 5\r\n"
  25798. "Transfer-Encoding: gzip, chunked\r\n"
  25799. "Connection: close\r\n"
  25800. "\r\n"
  25801. "hello";
  25802. std::string response;
  25803. ASSERT_TRUE(send_request(1, req, &response));
  25804. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25805. response.substr(0, response.find("\r\n")));
  25806. }
  25807. }
  25808. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25809. Server svr;
  25810. svr.Post("/test", [&](const Request &, Response &res) {
  25811. res.set_content("ok", "text/plain");
  25812. });
  25813. thread t = thread([&] { svr.listen(HOST, PORT); });
  25814. auto se = detail::scope_exit([&] {
  25815. svr.stop();
  25816. t.join();
  25817. ASSERT_FALSE(svr.is_running());
  25818. });
  25819. svr.wait_until_ready();
  25820. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25821. // length cannot be determined, so the server must answer 400 and close
  25822. // rather than treat the request as bodyless and leave the body in the
  25823. // socket for the next request to pick up.
  25824. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25825. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25826. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25827. std::string response;
  25828. ASSERT_TRUE(send_request(1, req, &response));
  25829. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25830. response.substr(0, response.find("\r\n")))
  25831. << transfer_encoding;
  25832. }
  25833. // RFC 9110 5.3: the codings may also be split across several
  25834. // Transfer-Encoding lines, which combine in the order they were received.
  25835. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25836. // just like the single-line "chunked, gzip" above.
  25837. {
  25838. auto req = "POST /test HTTP/1.1\r\n"
  25839. "Host: localhost\r\n"
  25840. "Transfer-Encoding: chunked\r\n"
  25841. "Transfer-Encoding: gzip\r\n"
  25842. "\r\n"
  25843. "0\r\n\r\n";
  25844. std::string response;
  25845. ASSERT_TRUE(send_request(1, req, &response));
  25846. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25847. response.substr(0, response.find("\r\n")));
  25848. }
  25849. }
  25850. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25851. Server svr;
  25852. svr.Post("/test", [&](const Request &, Response &res) {
  25853. res.set_content("ok", "text/plain");
  25854. });
  25855. auto port = svr.bind_to_any_port(HOST);
  25856. ASSERT_GT(port, 0);
  25857. thread t = thread([&] { svr.listen_after_bind(); });
  25858. auto se = detail::scope_exit([&] {
  25859. svr.stop();
  25860. t.join();
  25861. ASSERT_FALSE(svr.is_running());
  25862. });
  25863. svr.wait_until_ready();
  25864. for (auto transfer_encoding :
  25865. {"Transfer-Encoding: gzip, chunked\r\n",
  25866. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25867. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25868. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25869. transfer_encoding + "\r\n0\r\n\r\n";
  25870. std::string response;
  25871. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25872. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25873. response.substr(0, response.find("\r\n")))
  25874. << transfer_encoding;
  25875. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25876. << transfer_encoding;
  25877. }
  25878. }
  25879. // Regression for issue #2450: a DELETE without Content-Length on a
  25880. // keep-alive connection must not let the post-response drain consume the
  25881. // next request's bytes.
  25882. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25883. Server svr;
  25884. std::atomic<int> delete_count(0);
  25885. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25886. delete_count++;
  25887. res.status = StatusCode::NoContent_204;
  25888. });
  25889. auto port = svr.bind_to_any_port(HOST);
  25890. thread t = thread([&] { svr.listen_after_bind(); });
  25891. auto se = detail::scope_exit([&] {
  25892. svr.stop();
  25893. t.join();
  25894. });
  25895. svr.wait_until_ready();
  25896. auto error = Error::Success;
  25897. auto sock = detail::create_client_socket(
  25898. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25899. /*connection_timeout_sec=*/2, 0,
  25900. /*read_timeout_sec=*/2, 0,
  25901. /*write_timeout_sec=*/2, 0, std::string(), error);
  25902. ASSERT_NE(INVALID_SOCKET, sock);
  25903. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25904. auto send_request_and_read_response = [&](const std::string &req,
  25905. std::string &out) -> bool {
  25906. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25907. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25908. char buf[4096];
  25909. for (;;) {
  25910. auto n = recv(sock, buf, sizeof(buf), 0);
  25911. if (n <= 0) { return !out.empty(); }
  25912. out.append(buf, static_cast<size_t>(n));
  25913. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25914. }
  25915. };
  25916. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25917. "Host: localhost\r\n"
  25918. "\r\n";
  25919. std::string resp1;
  25920. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25921. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25922. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25923. "Host: localhost\r\n"
  25924. "Connection: close\r\n"
  25925. "\r\n";
  25926. std::string resp2;
  25927. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25928. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25929. EXPECT_EQ(2, delete_count.load());
  25930. }
  25931. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25932. Server svr;
  25933. svr.Post("/ingest", [&](const Request &, Response &res,
  25934. const ContentReader &content_reader) {
  25935. auto consumed = content_reader([](const char *, size_t) { return false; });
  25936. EXPECT_FALSE(consumed);
  25937. res.status = StatusCode::Conflict_409;
  25938. res.set_header("Connection", "close");
  25939. });
  25940. auto port = svr.bind_to_any_port(HOST);
  25941. thread t = thread([&] { svr.listen_after_bind(); });
  25942. auto se = detail::scope_exit([&] {
  25943. svr.stop();
  25944. t.join();
  25945. });
  25946. svr.wait_until_ready();
  25947. auto error = Error::Success;
  25948. auto sock = detail::create_client_socket(
  25949. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25950. /*connection_timeout_sec=*/2, 0,
  25951. /*read_timeout_sec=*/1, 0,
  25952. /*write_timeout_sec=*/2, 0, std::string(), error);
  25953. ASSERT_NE(INVALID_SOCKET, sock);
  25954. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25955. std::string request = "POST /ingest HTTP/1.1\r\n"
  25956. "Host: localhost\r\n"
  25957. "Transfer-Encoding: chunked\r\n"
  25958. "\r\n"
  25959. "4\r\n"
  25960. "data\r\n";
  25961. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25962. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25963. std::string response;
  25964. ssize_t received = 0;
  25965. do {
  25966. char buf[4096];
  25967. received = recv(sock, buf, sizeof(buf), 0);
  25968. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25969. } while (received > 0);
  25970. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25971. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25972. EXPECT_EQ(0, received);
  25973. }
  25974. namespace no_proxy_test {
  25975. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25976. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25977. // calling listen().
  25978. class ScopedServer {
  25979. public:
  25980. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25981. ~ScopedServer() {
  25982. svr_.stop();
  25983. if (th_.joinable()) { th_.join(); }
  25984. }
  25985. Server &svr() { return svr_; }
  25986. int port() const { return port_; }
  25987. void listen() {
  25988. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25989. svr_.wait_until_ready();
  25990. }
  25991. private:
  25992. Server svr_;
  25993. std::thread th_;
  25994. int port_ = 0;
  25995. };
  25996. class ProxyAndTargetServers {
  25997. public:
  25998. ProxyAndTargetServers() {
  25999. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  26000. proxy_hits_++;
  26001. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26002. res.set_content("via-proxy", "text/plain");
  26003. });
  26004. target_.Get(".*", [this](const Request &req, Response &res) {
  26005. target_hits_++;
  26006. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  26007. res.set_content("direct", "text/plain");
  26008. });
  26009. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  26010. target_port_ = target_.bind_to_any_port("127.0.0.1");
  26011. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  26012. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  26013. proxy_mock_.wait_until_ready();
  26014. target_.wait_until_ready();
  26015. }
  26016. ~ProxyAndTargetServers() {
  26017. proxy_mock_.stop();
  26018. target_.stop();
  26019. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  26020. if (target_thread_.joinable()) { target_thread_.join(); }
  26021. }
  26022. Server &proxy_mock() { return proxy_mock_; }
  26023. Server &target() { return target_; }
  26024. int proxy_port() const { return proxy_port_; }
  26025. int target_port() const { return target_port_; }
  26026. int proxy_hits() const { return proxy_hits_.load(); }
  26027. int target_hits() const { return target_hits_.load(); }
  26028. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  26029. void reset_counters() {
  26030. proxy_hits_ = 0;
  26031. target_hits_ = 0;
  26032. last_had_proxy_authz_ = false;
  26033. }
  26034. private:
  26035. Server proxy_mock_;
  26036. Server target_;
  26037. std::thread proxy_thread_;
  26038. std::thread target_thread_;
  26039. int proxy_port_ = 0;
  26040. int target_port_ = 0;
  26041. std::atomic<int> proxy_hits_{0};
  26042. std::atomic<int> target_hits_{0};
  26043. std::atomic<bool> last_had_proxy_authz_{false};
  26044. };
  26045. inline std::unique_ptr<Client> make_client(const std::string &host,
  26046. ProxyAndTargetServers &s) {
  26047. auto cli = detail::make_unique<Client>(host, s.target_port());
  26048. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  26049. cli->set_proxy("127.0.0.1", s.proxy_port());
  26050. return cli;
  26051. }
  26052. } // namespace no_proxy_test
  26053. using no_proxy_test::make_client;
  26054. using no_proxy_test::ProxyAndTargetServers;
  26055. // A stream request carries the credentials a buffered request does
  26056. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  26057. no_proxy_test::ScopedServer origin;
  26058. origin.svr().Get("/x", [](const Request &req, Response &res) {
  26059. res.set_content(req.get_header_value("Authorization"), "text/plain");
  26060. });
  26061. origin.listen();
  26062. Client cli("127.0.0.1", origin.port());
  26063. cli.set_basic_auth("user", "pass");
  26064. auto handle = cli.open_stream("GET", "/x");
  26065. ASSERT_TRUE(handle.is_valid());
  26066. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  26067. Client bearer("127.0.0.1", origin.port());
  26068. bearer.set_bearer_token_auth("tok");
  26069. auto handle2 = bearer.open_stream("GET", "/x");
  26070. ASSERT_TRUE(handle2.is_valid());
  26071. EXPECT_EQ("Bearer tok", read_all(handle2));
  26072. }
  26073. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  26074. // takes its own credentials, as for a buffered request
  26075. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  26076. std::string target, authz, proxy_authz;
  26077. no_proxy_test::ScopedServer proxy;
  26078. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26079. target = req.target;
  26080. authz = req.get_header_value("Authorization");
  26081. proxy_authz = req.get_header_value("Proxy-Authorization");
  26082. res.set_content("ok", "text/plain");
  26083. });
  26084. proxy.listen();
  26085. Client cli("origin.example", 8080);
  26086. cli.set_proxy("127.0.0.1", proxy.port());
  26087. cli.set_proxy_basic_auth("puser", "ppass");
  26088. cli.set_basic_auth("user", "pass");
  26089. auto handle = cli.open_stream("GET", "/x");
  26090. ASSERT_TRUE(handle.is_valid());
  26091. EXPECT_EQ("ok", read_all(handle));
  26092. EXPECT_EQ("http://origin.example:8080/x", target);
  26093. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  26094. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  26095. }
  26096. // In absolute-form the path follows the authority, so a path that does not
  26097. // begin with '/' would make the proxy connect to another host
  26098. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  26099. std::vector<std::string> targets;
  26100. no_proxy_test::ScopedServer proxy;
  26101. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  26102. targets.push_back(req.target);
  26103. res.set_content("ok", "text/plain");
  26104. });
  26105. proxy.listen();
  26106. Client cli("origin.example", 8080);
  26107. cli.set_proxy("127.0.0.1", proxy.port());
  26108. cli.set_basic_auth("user", "pass");
  26109. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  26110. auto res = cli.Get(path);
  26111. EXPECT_FALSE(res) << path;
  26112. auto handle = cli.open_stream("GET", path);
  26113. EXPECT_FALSE(handle.is_valid()) << path;
  26114. }
  26115. EXPECT_TRUE(targets.empty());
  26116. auto res = cli.Get("/x");
  26117. ASSERT_TRUE(res);
  26118. ASSERT_EQ(1u, targets.size());
  26119. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  26120. }
  26121. TEST(NoProxyTest, ExactHostnameBypasses) {
  26122. ProxyAndTargetServers s;
  26123. auto cli = make_client("example.com", s);
  26124. cli->set_no_proxy({"example.com"});
  26125. auto res = cli->Get("/");
  26126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26127. EXPECT_EQ(0, s.proxy_hits());
  26128. EXPECT_EQ(1, s.target_hits());
  26129. }
  26130. TEST(NoProxyTest, SubdomainBypasses) {
  26131. ProxyAndTargetServers s;
  26132. auto cli = make_client("foo.example.com", s);
  26133. cli->set_no_proxy({"example.com"});
  26134. auto res = cli->Get("/");
  26135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26136. EXPECT_EQ(0, s.proxy_hits());
  26137. EXPECT_EQ(1, s.target_hits());
  26138. }
  26139. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  26140. // Regression guard: "evilexample.com" must not be considered a subdomain
  26141. // of "example.com". Without the dot-boundary rule, a naive endsWith
  26142. // check would let traffic bypass the proxy and leak credentials direct
  26143. // to the attacker host.
  26144. ProxyAndTargetServers s;
  26145. auto cli = make_client("evilexample.com", s);
  26146. cli->set_no_proxy({"example.com"});
  26147. auto res = cli->Get("/");
  26148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26149. EXPECT_GE(s.proxy_hits(), 1);
  26150. EXPECT_EQ(0, s.target_hits());
  26151. }
  26152. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  26153. ProxyAndTargetServers s;
  26154. auto cli = make_client("example.com.evil.com", s);
  26155. cli->set_no_proxy({"example.com"});
  26156. auto res = cli->Get("/");
  26157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26158. EXPECT_GE(s.proxy_hits(), 1);
  26159. EXPECT_EQ(0, s.target_hits());
  26160. }
  26161. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  26162. ProxyAndTargetServers s;
  26163. auto cli = make_client("example.com", s);
  26164. cli->set_no_proxy({".example.com"});
  26165. auto res = cli->Get("/");
  26166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26167. EXPECT_EQ(0, s.proxy_hits());
  26168. EXPECT_EQ(1, s.target_hits());
  26169. }
  26170. TEST(NoProxyTest, CaseInsensitiveHostname) {
  26171. ProxyAndTargetServers s;
  26172. auto cli = make_client("Example.COM", s);
  26173. cli->set_no_proxy({"EXAMPLE.com"});
  26174. auto res = cli->Get("/");
  26175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26176. EXPECT_EQ(0, s.proxy_hits());
  26177. EXPECT_EQ(1, s.target_hits());
  26178. }
  26179. TEST(NoProxyTest, TrailingDotIsNormalized) {
  26180. ProxyAndTargetServers s;
  26181. auto cli = make_client("example.com.", s);
  26182. cli->set_no_proxy({"example.com"});
  26183. auto res = cli->Get("/");
  26184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26185. EXPECT_EQ(0, s.proxy_hits());
  26186. EXPECT_EQ(1, s.target_hits());
  26187. }
  26188. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  26189. // Trailing dots must be normalized on BOTH sides — host and entry.
  26190. // An implementation that only strips the host-side trailing dot would
  26191. // fail to match host "example.com" against entry "example.com." because
  26192. // a literal substring search would compare 11 chars against 12.
  26193. ProxyAndTargetServers s;
  26194. auto cli = make_client("example.com", s);
  26195. cli->set_no_proxy({"example.com."});
  26196. auto res = cli->Get("/");
  26197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26198. EXPECT_EQ(0, s.proxy_hits());
  26199. EXPECT_EQ(1, s.target_hits());
  26200. }
  26201. TEST(NoProxyTest, WildcardBypassesEverything) {
  26202. ProxyAndTargetServers s;
  26203. auto cli = make_client("anything.invalid.test", s);
  26204. cli->set_no_proxy({"*"});
  26205. auto res = cli->Get("/");
  26206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26207. EXPECT_EQ(0, s.proxy_hits());
  26208. EXPECT_EQ(1, s.target_hits());
  26209. }
  26210. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  26211. ProxyAndTargetServers s;
  26212. Client cli("127.0.0.1", s.target_port());
  26213. cli.set_proxy("127.0.0.1", s.proxy_port());
  26214. cli.set_no_proxy({"127.0.0.1"});
  26215. auto res = cli.Get("/");
  26216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26217. EXPECT_EQ(0, s.proxy_hits());
  26218. EXPECT_EQ(1, s.target_hits());
  26219. }
  26220. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  26221. ProxyAndTargetServers s;
  26222. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  26223. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  26224. cli.set_proxy("127.0.0.1", s.proxy_port());
  26225. cli.set_no_proxy({"::1"});
  26226. auto res = cli.Get("/");
  26227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26228. EXPECT_EQ(0, s.proxy_hits());
  26229. EXPECT_EQ(1, s.target_hits());
  26230. }
  26231. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  26232. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  26233. // must still be recognized as IPv6 for CIDR matching. Implementations
  26234. // that detect IPv6 only when the host begins with '[' would parse the
  26235. // host as a hostname and miss the match.
  26236. ProxyAndTargetServers s;
  26237. Client cli("fe80::1", s.target_port());
  26238. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26239. cli.set_proxy("127.0.0.1", s.proxy_port());
  26240. cli.set_no_proxy({"fe80::/10"});
  26241. auto res = cli.Get("/");
  26242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26243. EXPECT_EQ(0, s.proxy_hits());
  26244. EXPECT_EQ(1, s.target_hits());
  26245. }
  26246. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  26247. ProxyAndTargetServers s;
  26248. Client cli("::1", s.target_port());
  26249. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  26250. cli.set_proxy("127.0.0.1", s.proxy_port());
  26251. cli.set_no_proxy({"[::1]"});
  26252. auto res = cli.Get("/");
  26253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26254. EXPECT_EQ(0, s.proxy_hits());
  26255. EXPECT_EQ(1, s.target_hits());
  26256. }
  26257. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  26258. ProxyAndTargetServers s;
  26259. Client cli("fe80::1", s.target_port());
  26260. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  26261. cli.set_proxy("127.0.0.1", s.proxy_port());
  26262. cli.set_no_proxy({"[fe80::]/10"});
  26263. auto res = cli.Get("/");
  26264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26265. EXPECT_EQ(0, s.proxy_hits());
  26266. EXPECT_EQ(1, s.target_hits());
  26267. }
  26268. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  26269. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  26270. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  26271. // tricks via address-family conversion.
  26272. ProxyAndTargetServers s;
  26273. Client cli("::ffff:127.0.0.1", s.target_port());
  26274. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  26275. cli.set_proxy("127.0.0.1", s.proxy_port());
  26276. cli.set_no_proxy({"127.0.0.1"});
  26277. auto res = cli.Get("/");
  26278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26279. EXPECT_GE(s.proxy_hits(), 1);
  26280. EXPECT_EQ(0, s.target_hits());
  26281. }
  26282. TEST(NoProxyTest, IPv4CidrMatch) {
  26283. ProxyAndTargetServers s;
  26284. Client cli("127.0.0.1", s.target_port());
  26285. cli.set_proxy("127.0.0.1", s.proxy_port());
  26286. cli.set_no_proxy({"127.0.0.0/8"});
  26287. auto res = cli.Get("/");
  26288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26289. EXPECT_EQ(0, s.proxy_hits());
  26290. EXPECT_EQ(1, s.target_hits());
  26291. }
  26292. TEST(NoProxyTest, IPv4CidrNonMatch) {
  26293. ProxyAndTargetServers s;
  26294. Client cli("127.0.0.1", s.target_port());
  26295. cli.set_proxy("127.0.0.1", s.proxy_port());
  26296. cli.set_no_proxy({"10.0.0.0/8"});
  26297. auto res = cli.Get("/");
  26298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26299. EXPECT_GE(s.proxy_hits(), 1);
  26300. EXPECT_EQ(0, s.target_hits());
  26301. }
  26302. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  26303. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  26304. // IPv4 target matches.
  26305. ProxyAndTargetServers s;
  26306. Client cli("127.0.0.1", s.target_port());
  26307. cli.set_proxy("127.0.0.1", s.proxy_port());
  26308. cli.set_no_proxy({"0.0.0.0/0"});
  26309. auto res = cli.Get("/");
  26310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26311. EXPECT_EQ(0, s.proxy_hits());
  26312. EXPECT_EQ(1, s.target_hits());
  26313. }
  26314. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  26315. ProxyAndTargetServers s;
  26316. Client cli("127.0.0.1", s.target_port());
  26317. cli.set_proxy("127.0.0.1", s.proxy_port());
  26318. cli.set_no_proxy({"127.0.0.1"});
  26319. auto res = cli.Get("/");
  26320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26321. EXPECT_EQ(0, s.proxy_hits());
  26322. EXPECT_EQ(1, s.target_hits());
  26323. }
  26324. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  26325. ProxyAndTargetServers s;
  26326. Client cli("127.0.0.1", s.target_port());
  26327. cli.set_proxy("127.0.0.1", s.proxy_port());
  26328. cli.set_no_proxy({"127.0.0.0/33"});
  26329. auto res = cli.Get("/");
  26330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26331. EXPECT_GE(s.proxy_hits(), 1);
  26332. EXPECT_EQ(0, s.target_hits());
  26333. }
  26334. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  26335. // Empty prefix after the slash must be rejected, not silently treated as /32.
  26336. ProxyAndTargetServers s;
  26337. Client cli("127.0.0.1", s.target_port());
  26338. cli.set_proxy("127.0.0.1", s.proxy_port());
  26339. cli.set_no_proxy({"127.0.0.1/"});
  26340. auto res = cli.Get("/");
  26341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26342. EXPECT_GE(s.proxy_hits(), 1);
  26343. EXPECT_EQ(0, s.target_hits());
  26344. }
  26345. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  26346. ProxyAndTargetServers s;
  26347. auto cli = make_client("internal.corp", s);
  26348. cli->set_proxy_basic_auth("u", "p");
  26349. cli->set_no_proxy({"internal.corp"});
  26350. auto res = cli->Get("/");
  26351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26352. EXPECT_EQ(1, s.target_hits());
  26353. EXPECT_EQ(0, s.proxy_hits());
  26354. EXPECT_FALSE(s.last_had_proxy_authz())
  26355. << "Proxy-Authorization must not be sent direct to the target";
  26356. }
  26357. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  26358. ProxyAndTargetServers s;
  26359. auto cli = make_client("public.example", s);
  26360. cli->set_proxy_basic_auth("u", "p");
  26361. cli->set_no_proxy({"internal.corp"}); // does not match
  26362. auto res = cli->Get("/");
  26363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26364. EXPECT_GE(s.proxy_hits(), 1);
  26365. EXPECT_TRUE(s.last_had_proxy_authz());
  26366. }
  26367. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  26368. std::atomic<int> hits{0};
  26369. std::atomic<int> hits_with_authz{0};
  26370. no_proxy_test::ScopedServer proxy_mock;
  26371. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26372. hits++;
  26373. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  26374. if (req.target.find("/redir") != std::string::npos) {
  26375. res.set_redirect("http://other.example/landed");
  26376. } else {
  26377. res.set_content("via-proxy", "text/plain");
  26378. }
  26379. });
  26380. proxy_mock.listen();
  26381. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  26382. hits = 0;
  26383. hits_with_authz = 0;
  26384. Client cli("public.example", 80);
  26385. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26386. cli.set_proxy_basic_auth(c.first, c.second);
  26387. cli.set_follow_location(true);
  26388. // The redirect to another host goes through the proxy as well
  26389. auto res = cli.Get("/redir");
  26390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26391. EXPECT_EQ(2, hits.load());
  26392. EXPECT_EQ(2, hits_with_authz.load());
  26393. }
  26394. }
  26395. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  26396. ProxyAndTargetServers s;
  26397. auto cli = make_client("anything.test", s);
  26398. auto res = cli->Get("/");
  26399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26400. EXPECT_GE(s.proxy_hits(), 1);
  26401. EXPECT_EQ(0, s.target_hits());
  26402. }
  26403. TEST(NoProxyTest, PortSpecificEntryRejected) {
  26404. ProxyAndTargetServers s;
  26405. auto cli = make_client("example.com", s);
  26406. cli->set_no_proxy({"example.com:8080"});
  26407. auto res = cli->Get("/");
  26408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26409. EXPECT_GE(s.proxy_hits(), 1);
  26410. EXPECT_EQ(0, s.target_hits());
  26411. }
  26412. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  26413. ProxyAndTargetServers s;
  26414. auto cli = make_client("anything.test", s);
  26415. cli->set_no_proxy({"", " ", "\t"});
  26416. auto res = cli->Get("/");
  26417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26418. EXPECT_GE(s.proxy_hits(), 1);
  26419. EXPECT_EQ(0, s.target_hits());
  26420. }
  26421. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  26422. // An entry with leading/trailing whitespace must still match — env-style
  26423. // values are commonly pasted with stray spaces and an implementation
  26424. // that feeds the raw token directly to inet_pton would fail to match
  26425. // valid CIDRs because of the spaces.
  26426. ProxyAndTargetServers s;
  26427. Client cli("127.0.0.1", s.target_port());
  26428. cli.set_proxy("127.0.0.1", s.proxy_port());
  26429. cli.set_no_proxy({" 127.0.0.0/8 "});
  26430. auto res = cli.Get("/");
  26431. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26432. EXPECT_EQ(0, s.proxy_hits());
  26433. EXPECT_EQ(1, s.target_hits());
  26434. }
  26435. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26436. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26437. // go direct and must NOT carry Proxy-Authorization.
  26438. std::atomic<int> proxy_hits{0};
  26439. std::atomic<int> target_hits{0};
  26440. std::atomic<bool> target_saw_authz{false};
  26441. no_proxy_test::ScopedServer proxy_mock, target;
  26442. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26443. proxy_hits++;
  26444. res.status = 302;
  26445. res.set_header("Location", "http://127.0.0.1:" +
  26446. std::to_string(target.port()) + "/landed");
  26447. });
  26448. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26449. target_hits++;
  26450. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26451. res.set_content("direct", "text/plain");
  26452. });
  26453. proxy_mock.listen();
  26454. target.listen();
  26455. Client cli("public.example", target.port());
  26456. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26457. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26458. cli.set_proxy_basic_auth("u", "p");
  26459. cli.set_no_proxy({"127.0.0.1"});
  26460. cli.set_follow_location(true);
  26461. auto res = cli.Get("/redir");
  26462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26463. EXPECT_GE(proxy_hits.load(), 1);
  26464. EXPECT_GE(target_hits.load(), 1);
  26465. EXPECT_FALSE(target_saw_authz.load());
  26466. }
  26467. #ifdef CPPHTTPLIB_SSL_ENABLED
  26468. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26469. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26470. // proxy creds would be sent to the (possibly hostile) origin.
  26471. std::atomic<int> target_hits{0};
  26472. std::atomic<bool> target_saw_proxy_authz{false};
  26473. no_proxy_test::ScopedServer target;
  26474. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26475. target_hits++;
  26476. if (req.has_header("Proxy-Authorization")) {
  26477. target_saw_proxy_authz = true;
  26478. }
  26479. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26480. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26481. "nonce=\"abc\", algorithm=MD5");
  26482. });
  26483. target.listen();
  26484. // The proxy address is set to the target's port: the bypass MUST kick in;
  26485. // if it doesn't, the test still routes "via proxy" to the same server and
  26486. // the Proxy-Authorization assertion below catches the leak.
  26487. Client cli("evil.example", target.port());
  26488. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26489. cli.set_proxy("127.0.0.1", target.port());
  26490. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26491. cli.set_no_proxy({"evil.example"});
  26492. auto res = cli.Get("/x");
  26493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26494. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26495. EXPECT_EQ(1, target_hits.load());
  26496. EXPECT_FALSE(target_saw_proxy_authz.load());
  26497. }
  26498. #endif
  26499. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26500. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26501. std::atomic<int> proxy_hits{0};
  26502. std::atomic<int> bypass_hits{0};
  26503. std::atomic<bool> proxy_saw_c_url{false};
  26504. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26505. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26506. proxy_hits++;
  26507. if (req.path.find("/start") != std::string::npos) {
  26508. res.status = 302;
  26509. res.set_header("Location", "http://127.0.0.1:" +
  26510. std::to_string(bypass_server.port()) +
  26511. "/middle");
  26512. return;
  26513. }
  26514. if (req.path.find("/end") != std::string::npos) {
  26515. proxy_saw_c_url = true;
  26516. res.set_content("c-via-proxy", "text/plain");
  26517. return;
  26518. }
  26519. res.set_content("unexpected", "text/plain");
  26520. });
  26521. // public.example's "advertised" port is arbitrary (the request never lands
  26522. // there — it goes through the proxy), but use a dynamic value to stay
  26523. // friendly with sharded parallel runs.
  26524. int public_port = bypass_server.port();
  26525. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26526. bypass_hits++;
  26527. res.status = 302;
  26528. res.set_header("Location", "http://public.example:" +
  26529. std::to_string(public_port) + "/end");
  26530. });
  26531. proxy_mock.listen();
  26532. bypass_server.listen();
  26533. Client cli("public.example", public_port);
  26534. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26535. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26536. cli.set_no_proxy({"127.0.0.1"});
  26537. cli.set_follow_location(true);
  26538. auto res = cli.Get("/start");
  26539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26540. EXPECT_EQ(StatusCode::OK_200, res->status);
  26541. EXPECT_EQ("c-via-proxy", res->body);
  26542. EXPECT_GE(proxy_hits.load(), 2);
  26543. EXPECT_GE(bypass_hits.load(), 1);
  26544. EXPECT_TRUE(proxy_saw_c_url.load());
  26545. }
  26546. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26547. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26548. // request reconnects to the correct endpoint.
  26549. std::atomic<int> proxy_hits{0};
  26550. std::atomic<int> target_hits{0};
  26551. no_proxy_test::ScopedServer proxy_mock, target;
  26552. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26553. proxy_hits++;
  26554. res.set_content("via-proxy", "text/plain");
  26555. });
  26556. target.svr().Get(".*", [&](const Request &, Response &res) {
  26557. target_hits++;
  26558. res.set_content("direct", "text/plain");
  26559. });
  26560. proxy_mock.listen();
  26561. target.listen();
  26562. Client cli("public.example", target.port());
  26563. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26564. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26565. cli.set_keep_alive(true);
  26566. auto res1 = cli.Get("/a");
  26567. ASSERT_TRUE(res1);
  26568. EXPECT_EQ("via-proxy", res1->body);
  26569. EXPECT_EQ(1, proxy_hits.load());
  26570. EXPECT_EQ(0, target_hits.load());
  26571. cli.set_no_proxy({"public.example"});
  26572. auto res2 = cli.Get("/b");
  26573. ASSERT_TRUE(res2);
  26574. EXPECT_EQ("direct", res2->body);
  26575. EXPECT_EQ(1, proxy_hits.load());
  26576. EXPECT_EQ(1, target_hits.load());
  26577. }
  26578. // Forward declarations (see the base64_encode note).
  26579. namespace httplib {
  26580. namespace detail {
  26581. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26582. int shutdown_socket(socket_t sock) noexcept;
  26583. } // namespace detail
  26584. } // namespace httplib
  26585. namespace proxy_tunnel_test {
  26586. const char *const kTunnelEstablished =
  26587. "HTTP/1.1 200 Connection established\r\n\r\n";
  26588. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26589. using ConnectReply = std::function<std::string(const std::string &head)>;
  26590. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26591. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26592. class ScopedConnectProxy {
  26593. public:
  26594. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26595. : forward_port_(forward_port), reply_(std::move(reply)) {
  26596. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26597. if (listen_sock_ == INVALID_SOCKET) { return; }
  26598. auto a = loopback(0);
  26599. auto addr = reinterpret_cast<sockaddr *>(&a);
  26600. socklen_t alen = sizeof(a);
  26601. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26602. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26603. ::listen(listen_sock_, 4) != 0) {
  26604. return;
  26605. }
  26606. port_ = ntohs(a.sin_port);
  26607. th_ = std::thread([this] { run(); });
  26608. }
  26609. ~ScopedConnectProxy() {
  26610. if (th_.joinable()) {
  26611. stop_ = true;
  26612. auto wake = connect_to(port_);
  26613. th_.join();
  26614. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26615. }
  26616. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26617. }
  26618. int port() const { return port_; }
  26619. int connect_hits() const { return connect_hits_.load(); }
  26620. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26621. std::string connect_request() const {
  26622. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26623. return connect_request_;
  26624. }
  26625. private:
  26626. static sockaddr_in loopback(int port) {
  26627. sockaddr_in a{};
  26628. a.sin_family = AF_INET;
  26629. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26630. a.sin_port = htons(static_cast<unsigned short>(port));
  26631. return a;
  26632. }
  26633. static socket_t connect_to(int port) {
  26634. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26635. if (sock == INVALID_SOCKET) { return sock; }
  26636. auto a = loopback(port);
  26637. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26638. detail::close_socket(sock);
  26639. return INVALID_SOCKET;
  26640. }
  26641. return sock;
  26642. }
  26643. static bool send_all(socket_t sock, const char *data, size_t size) {
  26644. while (size > 0) {
  26645. auto n = detail::send_socket(sock, data, size, 0);
  26646. if (n <= 0) { return false; }
  26647. data += n;
  26648. size -= static_cast<size_t>(n);
  26649. }
  26650. return true;
  26651. }
  26652. void run() {
  26653. for (;;) {
  26654. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26655. if (stop_) {
  26656. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26657. return;
  26658. }
  26659. if (client == INVALID_SOCKET) { continue; }
  26660. serve(client);
  26661. detail::close_socket(client);
  26662. }
  26663. }
  26664. void serve(socket_t client) {
  26665. std::string head;
  26666. char buf[2048];
  26667. while (head.find("\r\n\r\n") == std::string::npos) {
  26668. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26669. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26670. if (n <= 0) { return; }
  26671. head.append(buf, static_cast<size_t>(n));
  26672. }
  26673. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26674. connect_hits_++;
  26675. {
  26676. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26677. connect_request_ = head;
  26678. }
  26679. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26680. if (!send_all(client, res.data(), res.size()) ||
  26681. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26682. return;
  26683. }
  26684. auto origin = connect_to(forward_port_);
  26685. if (origin == INVALID_SOCKET) { return; }
  26686. // When either side stops, shut both down so the other pump returns too.
  26687. auto pump = [&](socket_t from, socket_t to) {
  26688. char b[8192];
  26689. for (;;) {
  26690. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26691. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26692. }
  26693. detail::shutdown_socket(client);
  26694. detail::shutdown_socket(origin);
  26695. };
  26696. std::thread up([&] { pump(client, origin); });
  26697. pump(origin, client);
  26698. up.join();
  26699. detail::close_socket(origin);
  26700. }
  26701. int forward_port_;
  26702. ConnectReply reply_;
  26703. socket_t listen_sock_ = INVALID_SOCKET;
  26704. int port_ = 0;
  26705. std::thread th_;
  26706. std::atomic<bool> stop_{false};
  26707. std::atomic<int> connect_hits_{0};
  26708. mutable std::mutex connect_request_mutex_;
  26709. std::string connect_request_;
  26710. };
  26711. } // namespace proxy_tunnel_test
  26712. #ifdef CPPHTTPLIB_SSL_ENABLED
  26713. namespace proxy_tunnel_test {
  26714. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26715. class ScopedSSLServer {
  26716. public:
  26717. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26718. port_ = svr_.bind_to_any_port("127.0.0.1");
  26719. }
  26720. ~ScopedSSLServer() {
  26721. svr_.stop();
  26722. if (th_.joinable()) { th_.join(); }
  26723. }
  26724. SSLServer &svr() { return svr_; }
  26725. int port() const { return port_; }
  26726. void listen() {
  26727. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26728. svr_.wait_until_ready();
  26729. }
  26730. private:
  26731. SSLServer svr_;
  26732. std::thread th_;
  26733. int port_ = 0;
  26734. };
  26735. // Sends one request through the CONNECT proxy to the TLS origin with a
  26736. // credential configured for each hop, and checks that each credential reaches
  26737. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26738. // origin's (every header in origin_headers) on the tunnelled request.
  26739. void CredentialsStayWithTheirHop(
  26740. const std::function<void(SSLClient &)> &set_credentials,
  26741. const std::string &scheme,
  26742. const std::vector<std::string> &origin_headers = {"Authorization"},
  26743. bool stream = false) {
  26744. std::atomic<int> origin_hits{0};
  26745. std::atomic<bool> origin_saw_proxy_authz{false};
  26746. std::atomic<bool> origin_saw_headers{false};
  26747. ScopedSSLServer origin;
  26748. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26749. origin_hits++;
  26750. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26751. origin_saw_headers =
  26752. std::all_of(origin_headers.begin(), origin_headers.end(),
  26753. [&](const std::string &h) { return req.has_header(h); });
  26754. res.set_content("ok", "text/plain");
  26755. });
  26756. origin.listen();
  26757. ScopedConnectProxy proxy(origin.port());
  26758. ASSERT_NE(0, proxy.port());
  26759. // Pinned to 127.0.0.1 for the same reason as the test below.
  26760. SSLClient cli("127.0.0.1", origin.port());
  26761. cli.enable_server_certificate_verification(false);
  26762. cli.set_proxy("127.0.0.1", proxy.port());
  26763. set_credentials(cli);
  26764. if (stream) {
  26765. auto handle = cli.open_stream("GET", "/x");
  26766. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26767. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26768. } else {
  26769. auto res = cli.Get("/x");
  26770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26771. EXPECT_EQ(StatusCode::OK_200, res->status);
  26772. }
  26773. EXPECT_EQ(1, origin_hits.load());
  26774. EXPECT_EQ(1, proxy.connect_hits());
  26775. EXPECT_TRUE(origin_saw_headers.load());
  26776. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26777. << "Proxy-Authorization must not be sent inside the tunnel";
  26778. auto connect_req = proxy.connect_request();
  26779. EXPECT_NE(std::string::npos,
  26780. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26781. for (const auto &h : origin_headers) {
  26782. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26783. << h << " must not be sent to the proxy on CONNECT";
  26784. }
  26785. }
  26786. } // namespace proxy_tunnel_test
  26787. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26788. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26789. [](SSLClient &cli) {
  26790. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26791. cli.set_basic_auth("origin-user", "origin-pass");
  26792. },
  26793. "Basic");
  26794. }
  26795. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26796. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26797. [](SSLClient &cli) {
  26798. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26799. cli.set_basic_auth("origin-user", "origin-pass");
  26800. },
  26801. "Basic", {"Authorization"}, true);
  26802. }
  26803. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26804. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26805. [](SSLClient &cli) {
  26806. cli.set_proxy_bearer_token_auth("proxy-token");
  26807. cli.set_bearer_token_auth("origin-token");
  26808. },
  26809. "Bearer");
  26810. }
  26811. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26812. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26813. [](SSLClient &cli) {
  26814. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26815. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26816. {"Cookie", "sid=origin-session"},
  26817. {"X-Api-Key", "origin-key"}});
  26818. },
  26819. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26820. }
  26821. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26822. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26823. // retry; otherwise proxy creds would be sent to the origin.
  26824. std::atomic<int> origin_hits{0};
  26825. std::atomic<bool> origin_saw_proxy_authz{false};
  26826. proxy_tunnel_test::ScopedSSLServer origin;
  26827. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26828. origin_hits++;
  26829. if (req.has_header("Proxy-Authorization")) {
  26830. origin_saw_proxy_authz = true;
  26831. }
  26832. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26833. res.set_header("Proxy-Authenticate",
  26834. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26835. "algorithm=MD5");
  26836. });
  26837. origin.listen();
  26838. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26839. ASSERT_NE(0, proxy.port());
  26840. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26841. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26842. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26843. // and answer with its own status, making this test flaky.
  26844. SSLClient cli("127.0.0.1", origin.port());
  26845. cli.enable_server_certificate_verification(false);
  26846. cli.set_proxy("127.0.0.1", proxy.port());
  26847. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26848. auto res = cli.Get("/x");
  26849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26850. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26851. EXPECT_EQ(1, origin_hits.load());
  26852. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26853. EXPECT_EQ(1, proxy.connect_hits());
  26854. }
  26855. #endif
  26856. namespace proxy_tunnel_test {
  26857. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26858. // anything else gets a 407 with `challenge`.
  26859. ConnectReply require_proxy_auth(const std::string &expected,
  26860. const std::string &challenge) {
  26861. return [=](const std::string &head) -> std::string {
  26862. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26863. std::string::npos) {
  26864. return kTunnelEstablished;
  26865. }
  26866. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26867. "Proxy-Authenticate: " +
  26868. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26869. };
  26870. }
  26871. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26872. // request, then echoes.
  26873. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26874. ws.send(
  26875. "authorization:" + req.get_header_value("Authorization") +
  26876. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26877. std::string msg;
  26878. while (ws.read(msg)) {
  26879. ws.send(msg);
  26880. }
  26881. }
  26882. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26883. class ScopedWebSocketOrigin {
  26884. public:
  26885. ScopedWebSocketOrigin() {
  26886. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26887. server_.listen();
  26888. }
  26889. int port() const { return server_.port(); }
  26890. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26891. std::string url() const {
  26892. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26893. }
  26894. private:
  26895. no_proxy_test::ScopedServer server_;
  26896. };
  26897. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26898. // passed as a constructor header, and checks that each reaches only its hop.
  26899. void WebSocketCredentialsStayWithTheirHop(
  26900. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26901. const std::string &proxy_authz, const std::string &origin_authz) {
  26902. ScopedWebSocketOrigin origin;
  26903. ScopedConnectProxy proxy(
  26904. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26905. ASSERT_NE(0, proxy.port());
  26906. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26907. client.set_proxy("127.0.0.1", proxy.port());
  26908. set_proxy_credentials(client);
  26909. auto res = client.connect();
  26910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26911. std::string msg;
  26912. ASSERT_TRUE(client.read(msg));
  26913. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26914. client.close();
  26915. EXPECT_EQ(1, proxy.connect_hits());
  26916. EXPECT_EQ(std::string::npos,
  26917. proxy.connect_request().find("\r\nAuthorization: "))
  26918. << "origin credentials must not be sent to the proxy";
  26919. }
  26920. } // namespace proxy_tunnel_test
  26921. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26922. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26923. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26924. ASSERT_NE(0, proxy.port());
  26925. ws::WebSocketClient client(origin.url());
  26926. client.set_proxy("127.0.0.1", proxy.port());
  26927. auto res = client.connect();
  26928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26929. std::string msg;
  26930. ASSERT_TRUE(client.read(msg));
  26931. ASSERT_TRUE(client.send("hello"));
  26932. ASSERT_TRUE(client.read(msg));
  26933. EXPECT_EQ("hello", msg);
  26934. client.close();
  26935. EXPECT_EQ(1, proxy.connect_hits());
  26936. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26937. auto connect_req = proxy.connect_request();
  26938. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26939. EXPECT_NE(std::string::npos,
  26940. connect_req.find("\r\nHost: " + target + "\r\n"));
  26941. }
  26942. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26943. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26944. [](ws::WebSocketClient &cli) {
  26945. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26946. },
  26947. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26948. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26949. }
  26950. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26951. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26952. [](ws::WebSocketClient &cli) {
  26953. cli.set_proxy_bearer_token_auth("proxy-token");
  26954. },
  26955. "Bearer proxy-token", "Bearer origin-token");
  26956. }
  26957. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26958. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26959. proxy_tunnel_test::ScopedConnectProxy proxy(
  26960. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26961. "Basic " + detail::base64_encode("proxy-user:"),
  26962. "Basic realm=\"proxy\""));
  26963. ASSERT_NE(0, proxy.port());
  26964. ws::WebSocketClient client(origin.url());
  26965. client.set_proxy("127.0.0.1", proxy.port());
  26966. client.set_proxy_basic_auth("proxy-user", "");
  26967. auto res = client.connect();
  26968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26969. client.close();
  26970. EXPECT_EQ(1, proxy.connect_hits());
  26971. }
  26972. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26973. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26974. proxy_tunnel_test::ScopedConnectProxy proxy(
  26975. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26976. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26977. ASSERT_NE(0, proxy.port());
  26978. ws::WebSocketClient client(origin.url());
  26979. client.set_proxy("127.0.0.1", proxy.port());
  26980. auto res = client.connect();
  26981. EXPECT_FALSE(res);
  26982. EXPECT_EQ(Error::ProxyConnection, res.error());
  26983. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26984. EXPECT_EQ("Basic realm=\"proxy\"",
  26985. res.get_header_value("Proxy-Authenticate"));
  26986. EXPECT_FALSE(client.is_open());
  26987. }
  26988. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26989. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26990. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26991. ASSERT_NE(0, proxy.port());
  26992. ws::WebSocketClient client(origin.url());
  26993. client.set_proxy("127.0.0.1", proxy.port());
  26994. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26995. client.set_no_proxy({"127.0.0.1"});
  26996. auto res = client.connect();
  26997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26998. std::string msg;
  26999. ASSERT_TRUE(client.read(msg));
  27000. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27001. << "proxy credentials must not reach a bypassed origin";
  27002. client.close();
  27003. EXPECT_EQ(0, proxy.connect_hits());
  27004. }
  27005. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  27006. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27007. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  27008. ASSERT_NE(0, proxy.port());
  27009. ws::WebSocketClient client(origin.url());
  27010. client.set_proxy("127.0.0.1", proxy.port());
  27011. ASSERT_TRUE(client.connect());
  27012. ASSERT_TRUE(client.connect());
  27013. client.close();
  27014. EXPECT_EQ(2, proxy.connect_hits());
  27015. }
  27016. #ifdef CPPHTTPLIB_SSL_ENABLED
  27017. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  27018. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  27019. proxy_tunnel_test::ScopedConnectProxy proxy(
  27020. origin.port(), [](const std::string &head) -> std::string {
  27021. if (head.find(
  27022. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  27023. std::string::npos) {
  27024. return proxy_tunnel_test::kTunnelEstablished;
  27025. }
  27026. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  27027. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  27028. "nonce=\"abc\", algorithm=MD5\r\n"
  27029. "Content-Length: 0\r\n\r\n";
  27030. });
  27031. ASSERT_NE(0, proxy.port());
  27032. ws::WebSocketClient client(origin.url());
  27033. client.set_proxy("127.0.0.1", proxy.port());
  27034. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  27035. auto res = client.connect();
  27036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27037. std::string msg;
  27038. ASSERT_TRUE(client.read(msg));
  27039. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  27040. client.close();
  27041. EXPECT_EQ(2, proxy.connect_hits());
  27042. }
  27043. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  27044. proxy_tunnel_test::ScopedSSLServer origin;
  27045. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  27046. origin.listen();
  27047. proxy_tunnel_test::ScopedConnectProxy proxy(
  27048. origin.port(), proxy_tunnel_test::require_proxy_auth(
  27049. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  27050. ASSERT_NE(0, proxy.port());
  27051. ws::WebSocketClient client(
  27052. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  27053. client.enable_server_certificate_verification(false);
  27054. client.set_proxy("127.0.0.1", proxy.port());
  27055. client.set_proxy_bearer_token_auth("proxy-token");
  27056. auto res = client.connect();
  27057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27058. std::string msg;
  27059. ASSERT_TRUE(client.read(msg));
  27060. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  27061. << "Proxy-Authorization must not be sent inside the tunnel";
  27062. client.close();
  27063. EXPECT_EQ(1, proxy.connect_hits());
  27064. }
  27065. #endif