test.cc 925 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518
  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_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definition is linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. } // namespace tls
  68. } // namespace httplib
  69. #endif
  70. using namespace std;
  71. using namespace httplib;
  72. const char *HOST = "localhost";
  73. static int get_base_port() {
  74. const char *shard = getenv("GTEST_SHARD_INDEX");
  75. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  76. }
  77. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  78. // New standalone tests MUST use svr.bind_to_any_port() instead.
  79. const int PORT = get_base_port();
  80. const string LONG_QUERY_VALUE = string(25000, '@');
  81. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  82. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  83. const string TOO_LONG_QUERY_URL =
  84. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  85. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  86. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  87. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  88. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  89. return file.name == key;
  90. });
  91. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  92. return *it;
  93. #else
  94. if (it != items.end()) { return *it; }
  95. throw std::runtime_error("invalid multipart form data name error");
  96. #endif
  97. }
  98. static void read_file(const std::string &path, std::string &out) {
  99. std::ifstream fs(path, std::ios_base::binary);
  100. if (!fs) {
  101. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  102. return;
  103. #else
  104. throw std::runtime_error("File not found: " + path);
  105. #endif
  106. }
  107. fs.seekg(0, std::ios_base::end);
  108. auto size = fs.tellg();
  109. fs.seekg(0);
  110. out.resize(static_cast<size_t>(size));
  111. fs.read(&out[0], static_cast<std::streamsize>(size));
  112. }
  113. class UnixSocketTest : public ::testing::Test {
  114. protected:
  115. void TearDown() override { std::remove(pathname_.c_str()); }
  116. void client_GET(const std::string &addr) {
  117. httplib::Client cli{addr};
  118. cli.set_address_family(AF_UNIX);
  119. ASSERT_TRUE(cli.is_valid());
  120. const auto &result = cli.Get(pattern_);
  121. ASSERT_TRUE(result) << "error: " << result.error();
  122. const auto &resp = result.value();
  123. EXPECT_EQ(resp.status, StatusCode::OK_200);
  124. EXPECT_EQ(resp.body, content_);
  125. }
  126. static std::string make_sock_path() {
  127. const char *shard = getenv("GTEST_SHARD_INDEX");
  128. return shard ? std::string("./httplib-server-") + shard + ".sock"
  129. : "./httplib-server.sock";
  130. }
  131. const std::string pathname_{make_sock_path()};
  132. const std::string pattern_{"/hi"};
  133. const std::string content_{"Hello World!"};
  134. };
  135. TEST_F(UnixSocketTest, pathname) {
  136. httplib::Server svr;
  137. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  138. res.set_content(content_, "text/plain");
  139. });
  140. std::thread t{[&] {
  141. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  142. }};
  143. auto se = detail::scope_exit([&] {
  144. svr.stop();
  145. t.join();
  146. ASSERT_FALSE(svr.is_running());
  147. });
  148. svr.wait_until_ready();
  149. ASSERT_TRUE(svr.is_running());
  150. client_GET(pathname_);
  151. }
  152. #if defined(__linux__) || \
  153. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  154. TEST_F(UnixSocketTest, PeerPid) {
  155. httplib::Server svr;
  156. std::string remote_port_val;
  157. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  158. res.set_content(content_, "text/plain");
  159. remote_port_val = std::to_string(req.remote_port);
  160. });
  161. std::thread t{[&] {
  162. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  163. }};
  164. auto se = detail::scope_exit([&] {
  165. svr.stop();
  166. t.join();
  167. ASSERT_FALSE(svr.is_running());
  168. });
  169. svr.wait_until_ready();
  170. ASSERT_TRUE(svr.is_running());
  171. client_GET(pathname_);
  172. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  173. }
  174. #endif
  175. #ifdef __linux__
  176. TEST_F(UnixSocketTest, abstract) {
  177. constexpr char svr_path[]{"\x00httplib-server.sock"};
  178. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  179. httplib::Server svr;
  180. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  181. res.set_content(content_, "text/plain");
  182. });
  183. std::thread t{[&] {
  184. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  185. }};
  186. auto se = detail::scope_exit([&] {
  187. svr.stop();
  188. t.join();
  189. ASSERT_FALSE(svr.is_running());
  190. });
  191. svr.wait_until_ready();
  192. ASSERT_TRUE(svr.is_running());
  193. client_GET(abstract_addr);
  194. }
  195. #endif
  196. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  197. httplib::Server svr;
  198. std::string received_host_header;
  199. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  200. // Capture the Host header sent by the client
  201. auto host_iter = req.headers.find("Host");
  202. if (host_iter != req.headers.end()) {
  203. received_host_header = host_iter->second;
  204. }
  205. res.set_content(content_, "text/plain");
  206. });
  207. std::thread t{[&] {
  208. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  209. }};
  210. auto se = detail::scope_exit([&] {
  211. svr.stop();
  212. t.join();
  213. ASSERT_FALSE(svr.is_running());
  214. });
  215. svr.wait_until_ready();
  216. ASSERT_TRUE(svr.is_running());
  217. // Test that Host header is automatically set to "localhost" for Unix socket
  218. // connections
  219. httplib::Client cli{pathname_};
  220. cli.set_address_family(AF_UNIX);
  221. ASSERT_TRUE(cli.is_valid());
  222. const auto &result = cli.Get(pattern_);
  223. ASSERT_TRUE(result) << "error: " << result.error();
  224. const auto &resp = result.value();
  225. EXPECT_EQ(resp.status, StatusCode::OK_200);
  226. EXPECT_EQ(resp.body, content_);
  227. // Verify that Host header was automatically set to "localhost"
  228. EXPECT_EQ(received_host_header, "localhost");
  229. }
  230. #ifndef _WIN32
  231. TEST(SocketStream, wait_writable_UNIX) {
  232. int fds[2];
  233. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  234. const auto asSocketStream = [&](socket_t fd,
  235. std::function<bool(Stream &)> func) {
  236. return detail::process_client_socket(
  237. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  238. };
  239. asSocketStream(fds[0], [&](Stream &s0) {
  240. EXPECT_EQ(s0.socket(), fds[0]);
  241. EXPECT_TRUE(s0.wait_writable());
  242. EXPECT_TRUE(s0.is_peer_alive());
  243. EXPECT_EQ(0, close(fds[1]));
  244. EXPECT_FALSE(s0.is_peer_alive());
  245. return true;
  246. });
  247. EXPECT_EQ(0, close(fds[0]));
  248. }
  249. TEST(SocketStream, wait_writable_INET) {
  250. sockaddr_in addr;
  251. memset(&addr, 0, sizeof(addr));
  252. addr.sin_family = AF_INET;
  253. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  254. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  255. int disconnected_svr_sock = -1;
  256. std::thread svr{[&] {
  257. const int s = socket(AF_INET, SOCK_STREAM, 0);
  258. ASSERT_LE(0, s);
  259. // PORT + 1 is shared with the SSL redirect tests and with
  260. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  261. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  262. // because that happens on a worker thread the ASSERT does not stop the
  263. // test: it runs on and fails at the disconnected_svr_sock check instead.
  264. default_socket_options(s);
  265. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  266. ASSERT_EQ(0, listen(s, 1));
  267. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  268. ASSERT_EQ(0, close(s));
  269. }};
  270. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  271. std::thread cli{[&] {
  272. const int s = socket(AF_INET, SOCK_STREAM, 0);
  273. ASSERT_LE(0, s);
  274. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  275. ASSERT_EQ(0, close(s));
  276. }};
  277. cli.join();
  278. svr.join();
  279. ASSERT_NE(disconnected_svr_sock, -1);
  280. const auto asSocketStream = [&](socket_t fd,
  281. std::function<bool(Stream &)> func) {
  282. return detail::process_client_socket(
  283. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  284. };
  285. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  286. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  287. // wait_writable() returns true because select_write() only checks if the
  288. // send buffer has space. Peer disconnection is detected later by send().
  289. EXPECT_TRUE(ss.wait_writable());
  290. return true;
  291. });
  292. ASSERT_EQ(0, close(disconnected_svr_sock));
  293. }
  294. #endif // #ifndef _WIN32
  295. TEST(SetSocketOptTest, TcpNoDelay) {
  296. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  297. ASSERT_NE(sock, INVALID_SOCKET);
  298. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  299. int val = 0;
  300. socklen_t len = sizeof(val);
  301. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  302. reinterpret_cast<char *>(&val), &len));
  303. EXPECT_NE(val, 0);
  304. detail::close_socket(sock);
  305. }
  306. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  307. // accept() reports failures through WSAGetLastError() on Windows and through
  308. // errno everywhere else. Asking the wrong one is what made the accept loop
  309. // treat every recoverable failure as fatal on Windows.
  310. struct Classification {
  311. bool resource;
  312. bool transient;
  313. };
  314. auto classify = [](int err) {
  315. #ifdef _WIN32
  316. WSASetLastError(err);
  317. #else
  318. errno = err;
  319. #endif
  320. // Read both before asserting: an assertion may clobber the error slot.
  321. Classification c;
  322. c.resource = detail::is_accept_resource_error();
  323. c.transient = detail::is_accept_transient_error();
  324. return c;
  325. };
  326. #ifdef _WIN32
  327. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  328. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  329. WSAECONNRESET, WSAECONNABORTED};
  330. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  331. #else
  332. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  333. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  334. ECONNABORTED};
  335. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  336. #endif
  337. for (auto err : resource_errors) {
  338. const auto c = classify(err);
  339. EXPECT_TRUE(c.resource) << "error " << err;
  340. EXPECT_FALSE(c.transient) << "error " << err;
  341. }
  342. for (auto err : transient_errors) {
  343. const auto c = classify(err);
  344. EXPECT_TRUE(c.transient) << "error " << err;
  345. EXPECT_FALSE(c.resource) << "error " << err;
  346. }
  347. for (auto err : fatal_errors) {
  348. const auto c = classify(err);
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. EXPECT_FALSE(c.transient) << "error " << err;
  351. }
  352. #ifdef _WIN32
  353. WSASetLastError(0);
  354. #else
  355. errno = 0;
  356. #endif
  357. }
  358. TEST(ClientTest, MoveConstructible) {
  359. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  360. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  361. }
  362. TEST(ClientTest, MoveAssignable) {
  363. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  365. }
  366. #ifdef _WIN32
  367. TEST(StartupTest, WSAStartup) {
  368. WSADATA wsaData;
  369. int ret = WSAStartup(0x0002, &wsaData);
  370. ASSERT_EQ(0, ret);
  371. }
  372. #endif
  373. TEST(DecodePathTest, PercentCharacter) {
  374. EXPECT_EQ(
  375. decode_path_component(
  376. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  377. U8("descrip=Gastos áéíóúñÑ 6"));
  378. }
  379. TEST(DecodePathTest, PercentCharacterNUL) {
  380. string expected;
  381. expected.push_back('x');
  382. expected.push_back('\0');
  383. expected.push_back('x');
  384. EXPECT_EQ(decode_path_component("x%00x"), expected);
  385. }
  386. TEST(DecodePathTest, UnicodeEncoding) {
  387. // %u0041 = 'A' (1-byte UTF-8)
  388. EXPECT_EQ("A", decode_path_component("%u0041"));
  389. // %u00E9 = 'é' (2-byte UTF-8)
  390. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  391. // %u3042 = 'あ' (3-byte UTF-8)
  392. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  393. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  394. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  395. // %uD800 = surrogate (invalid, silently dropped)
  396. EXPECT_EQ("", decode_path_component("%uD800"));
  397. }
  398. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  399. // A sign or whitespace inside the two-character escape window must not be
  400. // accepted as a valid percent-encoding; the sequence is passed through
  401. // literally, matching decode_uri_component / decode_path_component.
  402. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  403. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  404. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  405. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  406. // Well-formed escapes still decode.
  407. EXPECT_EQ("-", decode_query_component("%2D", false));
  408. EXPECT_EQ("A", decode_query_component("%41", false));
  409. }
  410. TEST(SanitizeFilenameTest, VariousPatterns) {
  411. // Path traversal
  412. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  413. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  414. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  415. // Normal and edge cases
  416. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  417. EXPECT_EQ("filename.txt",
  418. httplib::sanitize_filename("/path/to/filename.txt"));
  419. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  420. EXPECT_EQ("", httplib::sanitize_filename(".."));
  421. EXPECT_EQ("", httplib::sanitize_filename(""));
  422. // Null bytes stripped
  423. EXPECT_EQ("safe.txt",
  424. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  425. // Whitespace-only rejected
  426. EXPECT_EQ("", httplib::sanitize_filename(" "));
  427. }
  428. // Forward declaration (see the base64_encode note below): split builds move the
  429. // definition into httplib.cc, so re-declaring it here lets the test link.
  430. namespace httplib {
  431. namespace detail {
  432. bool is_chunked_transfer_encoding(const Headers &headers);
  433. } // namespace detail
  434. } // namespace httplib
  435. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  436. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  437. auto make = [](std::initializer_list<const char *> lines) {
  438. Headers h;
  439. for (auto te : lines) {
  440. if (te) { h.emplace("Transfer-Encoding", te); }
  441. }
  442. return h;
  443. };
  444. // Sole coding, matched case-insensitively.
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  446. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  448. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  450. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  452. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  455. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  456. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  457. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  458. // were received, into one list. Headers preserves that order, so the answer
  459. // is decided by the last coding of the last line and the order the lines
  460. // arrived in is significant.
  461. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  463. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  464. // The split can fall anywhere in the list.
  465. EXPECT_TRUE(
  466. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  467. EXPECT_FALSE(
  468. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  469. // A trailing line naming no coding leaves the list ending in nothing, so it
  470. // must not inherit the chunked from the line before it.
  471. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  472. }
  473. // Forward declarations (see the base64_encode note below).
  474. namespace httplib {
  475. namespace detail {
  476. bool parse_status_line(const char *line, std::string &version, int &status,
  477. std::string &reason);
  478. std::string file_extension(const std::string &path);
  479. std::string
  480. find_content_type(const std::string &path,
  481. const std::map<std::string, std::string> &user_data,
  482. const std::string &default_content_type);
  483. bool can_compress_content_type(const std::string &content_type);
  484. bool is_prohibited_header_name(const std::string &name);
  485. } // namespace detail
  486. } // namespace httplib
  487. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  488. struct {
  489. const char *line;
  490. const char *version;
  491. int status;
  492. const char *reason;
  493. } cases[] = {
  494. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  495. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  496. // The reason phrase may be empty, or left out along with its space.
  497. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  498. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  499. };
  500. for (const auto &c : cases) {
  501. std::string version;
  502. int status = 0;
  503. std::string reason = "unset";
  504. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  505. << c.line;
  506. EXPECT_EQ(c.version, version);
  507. EXPECT_EQ(c.status, status);
  508. EXPECT_EQ(c.reason, reason);
  509. }
  510. }
  511. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  512. const char *lines[] = {
  513. "HTTP/2 200 OK\r\n",
  514. "HTTP/1.2 200 OK\r\n",
  515. "HTTP/1.1 20 OK\r\n",
  516. "HTTP/1.1 2000 OK\r\n",
  517. "HTTP/1.1 2x0 OK\r\n",
  518. "HTTP/1.1 200 OK\r\n",
  519. "HTTP/1.1 200OK\r\n",
  520. "HTTP/1.1 200 O\rK\r\n",
  521. "HTTP/1.1 200 OK",
  522. "HTTP/1.1 200 OK\r\nX",
  523. "",
  524. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  525. "HTTP/1.1 200 OK\n",
  526. #endif
  527. };
  528. for (auto line : lines) {
  529. std::string version;
  530. int status = 0;
  531. std::string reason;
  532. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  533. << line;
  534. }
  535. }
  536. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  537. // Long enough to overflow the stack when matched with std::regex.
  538. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  539. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  540. std::string version;
  541. int status = 0;
  542. std::string reason;
  543. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  544. EXPECT_EQ(200, status);
  545. EXPECT_EQ(long_reason, reason);
  546. }
  547. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  548. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  549. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  550. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  551. EXPECT_EQ("", detail::file_extension("noext"));
  552. EXPECT_EQ("", detail::file_extension("a."));
  553. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  554. EXPECT_EQ("", detail::file_extension("a.b-c"));
  555. // Long enough to overflow the stack when matched with std::regex.
  556. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  557. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  558. }
  559. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  560. detail::case_ignore::hash hash;
  561. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  562. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  563. // Long enough to overflow the stack if hashed one call per character.
  564. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  565. }
  566. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  567. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  568. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  569. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  570. // Same 26-bit hash as html, svg and js.
  571. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  572. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  573. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  574. }
  575. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  576. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  577. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  578. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  579. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  580. // Same 26-bit hash as application/json.
  581. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  582. }
  583. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  584. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  585. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  586. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  587. // Same 26-bit hash as REMOTE_ADDR.
  588. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  589. }
  590. // Forward declaration: in split builds split.py strips `inline` and moves the
  591. // definition into httplib.cc, so detail::base64_encode is not visible from the
  592. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  593. // in both header-only and split builds.
  594. namespace httplib {
  595. namespace detail {
  596. std::string base64_encode(const std::string &in);
  597. } // namespace detail
  598. } // namespace httplib
  599. TEST(Base64EncodeTest, KnownAnswers) {
  600. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  601. // where the accumulator's top bit is already set before the next shift.
  602. EXPECT_EQ("", detail::base64_encode(""));
  603. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  604. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  605. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  606. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  607. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  608. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  609. // High bytes keep the top bit set across several rounds.
  610. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  611. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  612. }
  613. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  614. string unescapedCharacters = "-_.!~*'()";
  615. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  616. }
  617. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  618. string reservedCharacters = ";,/?:@&=+$";
  619. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  620. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  621. }
  622. TEST(ClientQueryOrder, PreserveOrder) {
  623. // This test reproduces Issue #2259: client may reorder query parameters
  624. // when sending a GET request. The expected behavior is that the client
  625. // preserves the original query string order when the caller supplied it
  626. // as part of the path.
  627. Server svr;
  628. svr.Get("/", [&](const Request &req, Response &res) {
  629. // Echo back the raw target so the test can assert ordering
  630. res.set_content(req.target, "text/plain");
  631. });
  632. std::thread t{[&] { svr.listen(HOST, PORT); }};
  633. auto se = detail::scope_exit([&] {
  634. svr.stop();
  635. t.join();
  636. ASSERT_FALSE(svr.is_running());
  637. });
  638. svr.wait_until_ready();
  639. Client cli(HOST, PORT);
  640. ASSERT_TRUE(cli.is_valid());
  641. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  642. auto res = cli.Get(original);
  643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  644. // Expect the echoed target to exactly match the original path (order
  645. // preserved)
  646. EXPECT_EQ(res->body, original);
  647. }
  648. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  649. string chineseCharacters = U8("中国語");
  650. string russianCharacters = U8("дом");
  651. string brazilianCharacters = U8("óculos");
  652. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  653. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  654. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  655. "%D0%B4%D0%BE%D0%BC");
  656. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  657. }
  658. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  659. string unescapedCharacters = "-_.!~*'()";
  660. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  661. }
  662. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  663. string reservedCharacters = ";,/?:@&=+$";
  664. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  665. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  666. }
  667. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  668. string chineseCharacters = U8("中国語");
  669. string russianCharacters = U8("дом");
  670. string brazilianCharacters = U8("óculos");
  671. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  672. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  673. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  674. "%D0%B4%D0%BE%D0%BC");
  675. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  676. }
  677. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  678. // Issue #2082 use case: encoding path component with ampersand
  679. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  680. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  681. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  682. }
  683. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  684. string unescapedCharacters = "-_.!~*'()";
  685. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  686. }
  687. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  688. string reservedCharacters = ";,/?:@&=+$#";
  689. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  690. }
  691. TEST(EncodeUriTest, TestUTF8Characters) {
  692. string chineseCharacters = U8("中国語");
  693. string russianCharacters = U8("дом");
  694. string brazilianCharacters = U8("óculos");
  695. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  696. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  697. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  698. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  699. }
  700. TEST(EncodeUriTest, TestCompleteUri) {
  701. string uri =
  702. "https://example.com/path/to/resource?query=value&param=test#fragment";
  703. EXPECT_EQ(
  704. httplib::encode_uri(uri),
  705. "https://example.com/path/to/resource?query=value&param=test#fragment");
  706. }
  707. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  708. string uri =
  709. "https://example.com/path with spaces/file name.html?q=hello world";
  710. EXPECT_EQ(httplib::encode_uri(uri),
  711. "https://example.com/path%20with%20spaces/"
  712. "file%20name.html?q=hello%20world");
  713. }
  714. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  715. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  716. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  717. }
  718. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  719. string unescapedCharacters = "-_.!~*'()";
  720. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  721. }
  722. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  723. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  724. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  725. string encodedBrazilian = "%C3%B3culos";
  726. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  727. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  728. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  729. }
  730. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  731. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  732. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  733. "Piri Tommy Villiers - on & on");
  734. }
  735. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  736. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  737. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  738. }
  739. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  740. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  741. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  742. }
  743. TEST(DecodeUriTest, TestUTF8Characters) {
  744. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  745. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  746. string encodedBrazilian = "%C3%B3culos";
  747. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  748. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  749. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  750. }
  751. TEST(DecodeUriTest, TestCompleteUri) {
  752. string encodedUri = "https://example.com/path%20with%20spaces/"
  753. "file%20name.html?q=hello%20world";
  754. EXPECT_EQ(
  755. httplib::decode_uri(encodedUri),
  756. "https://example.com/path with spaces/file name.html?q=hello world");
  757. }
  758. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  759. string original =
  760. "https://example.com/path with spaces/file name.html?q=hello world";
  761. string encoded = httplib::encode_uri(original);
  762. string decoded = httplib::decode_uri(encoded);
  763. EXPECT_EQ(decoded, original);
  764. }
  765. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  766. // decode_uri is the inverse of encode_uri: an escaped reserved character
  767. // stays encoded so it is not promoted into a real delimiter, while
  768. // non-reserved escapes still decode (like JS decodeURI).
  769. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  770. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  771. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  772. "%3F%3A%40%26%3D%2B%24%2C%3B");
  773. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  774. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  775. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  776. "http://example.com/a%2Fb");
  777. // decode_uri_component still decodes the reserved character.
  778. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  779. }
  780. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  781. string original = "Piri Tommy Villiers - on & on";
  782. string encoded = httplib::encode_uri_component(original);
  783. string decoded = httplib::decode_uri_component(encoded);
  784. EXPECT_EQ(decoded, original);
  785. }
  786. TEST(TrimTests, TrimStringTests) {
  787. EXPECT_EQ("abc", detail::trim_copy("abc"));
  788. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  789. EXPECT_TRUE(detail::trim_copy("").empty());
  790. }
  791. TEST(AsciiTest, LocaleIndependentClassification) {
  792. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  793. // which consult the global C locale: std::isalnum(0xC5) can return true
  794. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  795. // helpers must classify every byte by the ASCII grammar alone.
  796. for (int i = 0; i < 256; i++) {
  797. auto c = static_cast<char>(i);
  798. auto is_digit = i >= '0' && i <= '9';
  799. auto is_upper = i >= 'A' && i <= 'Z';
  800. auto is_lower = i >= 'a' && i <= 'z';
  801. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  802. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  803. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  804. << "byte " << i;
  805. }
  806. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  807. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  808. // Non-ASCII bytes must be percent-encoded, never passed through as
  809. // alphanumeric.
  810. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  811. }
  812. TEST(FromCharsTest, Double) {
  813. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  814. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  815. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  816. auto parse = [](const std::string &s, double &v) {
  817. return detail::from_chars(s.data(), s.data() + s.size(), v);
  818. };
  819. double v = -1.0;
  820. // Representative quality values.
  821. EXPECT_EQ(parse("0", v).ec, std::errc{});
  822. EXPECT_DOUBLE_EQ(v, 0.0);
  823. EXPECT_EQ(parse("1", v).ec, std::errc{});
  824. EXPECT_DOUBLE_EQ(v, 1.0);
  825. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  826. EXPECT_DOUBLE_EQ(v, 0.8);
  827. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  828. EXPECT_DOUBLE_EQ(v, 0.001);
  829. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  830. EXPECT_DOUBLE_EQ(v, 1.0);
  831. // A missing integer or fractional part is tolerated.
  832. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  833. EXPECT_DOUBLE_EQ(v, 0.5);
  834. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  835. EXPECT_DOUBLE_EQ(v, 5.0);
  836. // Values outside [0, 1] still parse; the caller range-checks them.
  837. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  838. EXPECT_DOUBLE_EQ(v, 123.456);
  839. // Stops at the first byte that is not part of the number and reports where.
  840. std::string trailing = "0.9, text/html";
  841. auto r = parse(trailing, v);
  842. EXPECT_EQ(r.ec, std::errc{});
  843. EXPECT_DOUBLE_EQ(v, 0.9);
  844. EXPECT_EQ(*r.ptr, ',');
  845. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  846. // outright, and an 'e'/'E' simply ends the number.
  847. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  848. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  849. std::string exp_input = "1.5e3";
  850. r = parse(exp_input, v);
  851. EXPECT_EQ(r.ec, std::errc{});
  852. EXPECT_DOUBLE_EQ(v, 1.5);
  853. EXPECT_EQ(*r.ptr, 'e');
  854. // Invalid inputs.
  855. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  856. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  857. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  858. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  859. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  860. // Pathological but well-formed inputs must stay bounded (no overflow, no
  861. // out-of-bounds table access) and stay within [0, 1] for the caller.
  862. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  863. std::errc{});
  864. EXPECT_DOUBLE_EQ(v, 0.0);
  865. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  866. std::errc{});
  867. EXPECT_GE(v, 0.0);
  868. EXPECT_LE(v, 1.0);
  869. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  870. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  871. }
  872. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  873. // Simple case without quality values
  874. std::vector<std::string> result1;
  875. EXPECT_TRUE(detail::parse_accept_header(
  876. "text/html,application/json,text/plain", result1));
  877. EXPECT_EQ(result1.size(), 3U);
  878. EXPECT_EQ(result1[0], "text/html");
  879. EXPECT_EQ(result1[1], "application/json");
  880. EXPECT_EQ(result1[2], "text/plain");
  881. // With quality values
  882. std::vector<std::string> result2;
  883. EXPECT_TRUE(detail::parse_accept_header(
  884. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  885. EXPECT_EQ(result2.size(), 3U);
  886. EXPECT_EQ(result2[0], "application/json"); // highest q value
  887. EXPECT_EQ(result2[1], "text/html");
  888. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  889. }
  890. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  891. // Mixed with and without quality values
  892. std::vector<std::string> result;
  893. EXPECT_TRUE(detail::parse_accept_header(
  894. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  895. EXPECT_EQ(result.size(), 3U);
  896. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  897. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  898. EXPECT_EQ(result[2], "application/json"); // q=0.5
  899. }
  900. TEST(ParseAcceptHeaderTest, EdgeCases) {
  901. // Empty header
  902. std::vector<std::string> empty_result;
  903. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  904. EXPECT_TRUE(empty_result.empty());
  905. // Single type
  906. std::vector<std::string> single_result;
  907. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  908. EXPECT_EQ(single_result.size(), 1U);
  909. EXPECT_EQ(single_result[0], "application/json");
  910. // Wildcard types
  911. std::vector<std::string> wildcard_result;
  912. EXPECT_TRUE(detail::parse_accept_header(
  913. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  914. EXPECT_EQ(wildcard_result.size(), 3U);
  915. EXPECT_EQ(wildcard_result[0], "application/json");
  916. EXPECT_EQ(wildcard_result[1], "text/*");
  917. EXPECT_EQ(wildcard_result[2], "*/*");
  918. }
  919. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  920. // Common browser Accept header
  921. std::vector<std::string> browser_result;
  922. EXPECT_TRUE(
  923. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  924. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  925. browser_result));
  926. EXPECT_EQ(browser_result.size(), 6U);
  927. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  928. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  929. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  930. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  931. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  932. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  933. // API client header
  934. std::vector<std::string> api_result;
  935. EXPECT_TRUE(detail::parse_accept_header(
  936. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  937. api_result));
  938. EXPECT_EQ(api_result.size(), 3U);
  939. EXPECT_EQ(api_result[0], "application/json");
  940. EXPECT_EQ(api_result[1], "application/xml");
  941. EXPECT_EQ(api_result[2], "text/plain");
  942. }
  943. TEST(ParseAcceptHeaderTest, SpecialCases) {
  944. // Quality value with 3 decimal places
  945. std::vector<std::string> decimal_result;
  946. EXPECT_TRUE(detail::parse_accept_header(
  947. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  948. EXPECT_EQ(decimal_result.size(), 2U);
  949. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  950. EXPECT_EQ(decimal_result[1], "text/html");
  951. // Zero quality (should still be included but with lowest priority)
  952. std::vector<std::string> zero_q_result;
  953. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  954. zero_q_result));
  955. EXPECT_EQ(zero_q_result.size(), 2U);
  956. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  957. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  958. // No spaces around commas
  959. std::vector<std::string> no_space_result;
  960. EXPECT_TRUE(detail::parse_accept_header(
  961. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  962. no_space_result));
  963. EXPECT_EQ(no_space_result.size(), 3U);
  964. EXPECT_EQ(no_space_result[0], "text/html");
  965. EXPECT_EQ(no_space_result[1], "application/json");
  966. EXPECT_EQ(no_space_result[2], "text/plain");
  967. }
  968. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  969. // Quality values always use '.' as the decimal separator, so parsing must
  970. // not depend on the process locale. An embedding application may have
  971. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  972. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  973. std::string saved = cur ? cur : "C";
  974. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  975. "fr_FR.UTF-8"};
  976. bool switched = false;
  977. for (const auto loc : comma_locales) {
  978. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  979. std::localeconv()->decimal_point[0] == ',') {
  980. switched = true;
  981. break;
  982. }
  983. }
  984. if (!switched) {
  985. std::setlocale(LC_NUMERIC, saved.c_str());
  986. GTEST_SKIP() << "no comma-decimal locale available on this host";
  987. }
  988. // The higher-weighted type appears later in the list, so a correct parse
  989. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  990. // sensitive parse reads both weights as 0 and leaves the original order.
  991. std::vector<std::string> result;
  992. EXPECT_TRUE(detail::parse_accept_header(
  993. "application/json;q=0.1,text/html;q=0.9", result));
  994. ASSERT_EQ(result.size(), 2U);
  995. EXPECT_EQ(result[0], "text/html");
  996. EXPECT_EQ(result[1], "application/json");
  997. std::setlocale(LC_NUMERIC, saved.c_str());
  998. }
  999. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1000. std::vector<std::string> result;
  1001. // Invalid quality value (> 1.0)
  1002. EXPECT_FALSE(
  1003. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1004. // Invalid quality value (< 0.0)
  1005. EXPECT_FALSE(
  1006. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1007. // Invalid quality value (not a number)
  1008. EXPECT_FALSE(detail::parse_accept_header(
  1009. "text/html;q=invalid,application/json", result));
  1010. // A valid numeric prefix does not make the entire quality value valid.
  1011. EXPECT_FALSE(detail::parse_accept_header(
  1012. "text/html;q=0.5junk,application/json", result));
  1013. // Empty quality value
  1014. EXPECT_FALSE(
  1015. detail::parse_accept_header("text/html;q=,application/json", result));
  1016. // Invalid media type format (no slash and not wildcard)
  1017. EXPECT_FALSE(
  1018. detail::parse_accept_header("invalidtype,application/json", result));
  1019. // Valid cases should still work
  1020. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1021. EXPECT_EQ(result.size(), 1U);
  1022. EXPECT_EQ(result[0], "*/*");
  1023. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1024. EXPECT_EQ(result.size(), 1U);
  1025. EXPECT_EQ(result[0], "*");
  1026. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1027. EXPECT_EQ(result.size(), 1U);
  1028. EXPECT_EQ(result[0], "text/*");
  1029. }
  1030. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1031. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1032. // and must not be answered with 400 Bad Request.
  1033. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1034. struct {
  1035. const char *value;
  1036. std::vector<std::string> expected;
  1037. } cases[] = {
  1038. {",application/json", {"application/json"}},
  1039. {"text/html,", {"text/html"}},
  1040. {"text/html,,*/*", {"text/html", "*/*"}},
  1041. // An empty element may be spelled with whitespace in it
  1042. {"text/html, , application/json", {"text/html", "application/json"}},
  1043. // Nothing but empty elements is an empty list, which means the same
  1044. // thing as no Accept header at all
  1045. {",,,", {}},
  1046. // Quality values still apply across ignored empty elements
  1047. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1048. };
  1049. for (const auto &c : cases) {
  1050. std::vector<std::string> result;
  1051. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1052. << "value: " << c.value;
  1053. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1054. }
  1055. // An invalid entry is still rejected when empty elements surround it
  1056. std::vector<std::string> result;
  1057. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1058. }
  1059. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1060. // or ';' inside one does not end the list element or the parameter. Section
  1061. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1062. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1063. struct {
  1064. const char *value;
  1065. std::vector<std::string> expected;
  1066. } cases[] = {
  1067. {"text/html;profile=\"a,b\",application/json",
  1068. {"text/html", "application/json"}},
  1069. // A "q=" inside a quoted value is not the weight
  1070. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1071. {"text/html", "application/json"}},
  1072. // The weight after a quoted value still applies
  1073. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1074. {"application/json", "text/html"}},
  1075. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1076. {"application/json", "text/html"}},
  1077. {"text/html;profile=\"a\\\"b\",application/json",
  1078. {"text/html", "application/json"}},
  1079. // An escaped backslash does not escape the '"' after it
  1080. {"text/html;profile=\"a\\\\\",application/json",
  1081. {"text/html", "application/json"}},
  1082. };
  1083. for (const auto &c : cases) {
  1084. std::vector<std::string> result;
  1085. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1086. << "value: " << c.value;
  1087. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1088. }
  1089. }
  1090. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1091. Server svr;
  1092. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1093. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1094. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1095. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1096. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1097. res.set_content("ok", "text/plain");
  1098. });
  1099. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1100. EXPECT_TRUE(false);
  1101. res.set_content("bad request", "text/plain");
  1102. });
  1103. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1104. auto se = detail::scope_exit([&] {
  1105. svr.stop();
  1106. listen_thread.join();
  1107. ASSERT_FALSE(svr.is_running());
  1108. });
  1109. svr.wait_until_ready();
  1110. Client cli("localhost", PORT);
  1111. {
  1112. auto res = cli.Get(
  1113. "/accept_ok",
  1114. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1116. EXPECT_EQ(StatusCode::OK_200, res->status);
  1117. }
  1118. {
  1119. auto res = cli.Get("/accept_bad_request",
  1120. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1122. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1123. }
  1124. }
  1125. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1126. Server svr;
  1127. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1128. res.set_content("ok", "text/plain");
  1129. });
  1130. std::atomic<int> start_count{0};
  1131. std::atomic<bool> running_when_called{false};
  1132. svr.set_start_handler([&]() {
  1133. running_when_called = svr.is_running();
  1134. start_count++;
  1135. });
  1136. auto port = svr.bind_to_any_port(HOST);
  1137. std::thread t([&]() { svr.listen_after_bind(); });
  1138. auto se = detail::scope_exit([&] {
  1139. svr.stop();
  1140. t.join();
  1141. ASSERT_FALSE(svr.is_running());
  1142. });
  1143. svr.wait_until_ready();
  1144. // A successful request proves the accept loop is running, which the start
  1145. // handler precedes; so by now the handler must have run exactly once.
  1146. Client cli(HOST, port);
  1147. cli.set_connection_timeout(std::chrono::seconds(5));
  1148. auto res = cli.Get("/");
  1149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1150. EXPECT_EQ(StatusCode::OK_200, res->status);
  1151. EXPECT_EQ(1, start_count.load());
  1152. EXPECT_TRUE(running_when_called.load());
  1153. }
  1154. TEST(DivideTest, DivideStringTests) {
  1155. auto divide = [](const std::string &str, char d) {
  1156. std::string lhs;
  1157. std::string rhs;
  1158. detail::divide(str, d,
  1159. [&](const char *lhs_data, std::size_t lhs_size,
  1160. const char *rhs_data, std::size_t rhs_size) {
  1161. lhs.assign(lhs_data, lhs_size);
  1162. rhs.assign(rhs_data, rhs_size);
  1163. });
  1164. return std::make_pair(std::move(lhs), std::move(rhs));
  1165. };
  1166. {
  1167. const auto res = divide("", '=');
  1168. EXPECT_EQ(res.first, "");
  1169. EXPECT_EQ(res.second, "");
  1170. }
  1171. {
  1172. const auto res = divide("=", '=');
  1173. EXPECT_EQ(res.first, "");
  1174. EXPECT_EQ(res.second, "");
  1175. }
  1176. {
  1177. const auto res = divide(" ", '=');
  1178. EXPECT_EQ(res.first, " ");
  1179. EXPECT_EQ(res.second, "");
  1180. }
  1181. {
  1182. const auto res = divide("a", '=');
  1183. EXPECT_EQ(res.first, "a");
  1184. EXPECT_EQ(res.second, "");
  1185. }
  1186. {
  1187. const auto res = divide("a=", '=');
  1188. EXPECT_EQ(res.first, "a");
  1189. EXPECT_EQ(res.second, "");
  1190. }
  1191. {
  1192. const auto res = divide("=b", '=');
  1193. EXPECT_EQ(res.first, "");
  1194. EXPECT_EQ(res.second, "b");
  1195. }
  1196. {
  1197. const auto res = divide("a=b", '=');
  1198. EXPECT_EQ(res.first, "a");
  1199. EXPECT_EQ(res.second, "b");
  1200. }
  1201. {
  1202. const auto res = divide("a=b=", '=');
  1203. EXPECT_EQ(res.first, "a");
  1204. EXPECT_EQ(res.second, "b=");
  1205. }
  1206. {
  1207. const auto res = divide("a=b=c", '=');
  1208. EXPECT_EQ(res.first, "a");
  1209. EXPECT_EQ(res.second, "b=c");
  1210. }
  1211. }
  1212. TEST(SplitTest, ParseQueryString) {
  1213. string s = "key1=val1&key2=val2&key3=val3";
  1214. Params dic;
  1215. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1216. [&](const char *b, const char *e) {
  1217. string key, val;
  1218. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1219. if (key.empty()) {
  1220. key.assign(b2, e2);
  1221. } else {
  1222. val.assign(b2, e2);
  1223. }
  1224. });
  1225. dic.emplace(key, val);
  1226. });
  1227. EXPECT_EQ("val1", dic.find("key1")->second);
  1228. EXPECT_EQ("val2", dic.find("key2")->second);
  1229. EXPECT_EQ("val3", dic.find("key3")->second);
  1230. }
  1231. TEST(SplitTest, ParseInvalidQueryTests) {
  1232. {
  1233. string s = " ";
  1234. Params dict;
  1235. detail::parse_query_text(s, dict);
  1236. EXPECT_TRUE(dict.empty());
  1237. }
  1238. {
  1239. string s = " = =";
  1240. Params dict;
  1241. detail::parse_query_text(s, dict);
  1242. EXPECT_TRUE(dict.empty());
  1243. }
  1244. }
  1245. TEST(ParseQueryTest, ParseQueryString) {
  1246. {
  1247. std::string s = "key1=val1&key2=val2&key3=val3";
  1248. Params dic;
  1249. detail::parse_query_text(s, dic);
  1250. EXPECT_EQ("val1", dic.find("key1")->second);
  1251. EXPECT_EQ("val2", dic.find("key2")->second);
  1252. EXPECT_EQ("val3", dic.find("key3")->second);
  1253. }
  1254. {
  1255. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1256. Params dic;
  1257. detail::parse_query_text(s, dic);
  1258. EXPECT_EQ("", dic.find("key1")->second);
  1259. EXPECT_EQ("val1", dic.find("key2")->second);
  1260. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1261. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1262. }
  1263. }
  1264. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1265. Params dic;
  1266. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1267. dic.emplace("key1", "val1");
  1268. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1269. dic.emplace("key2", "val2");
  1270. dic.emplace("key3", "val3");
  1271. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1272. }
  1273. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1274. Params params;
  1275. params.emplace("a", "1");
  1276. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1277. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1278. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1279. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1280. // Long enough to overflow the stack when matched with std::regex.
  1281. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1282. EXPECT_EQ("/p?" + long_query + "&a=1",
  1283. append_query_params("/p?" + long_query, params));
  1284. }
  1285. // Joins every entry of a Headers or Params into "key=value " so a whole
  1286. // traversal can be compared in one assertion. Both are instantiations of the
  1287. // same insertion-ordered container, so one helper serves both.
  1288. template <typename Map> static std::string entries_to_string(const Map &m) {
  1289. std::string s;
  1290. for (const auto &entry : m) {
  1291. s += entry.first + "=" + entry.second + " ";
  1292. }
  1293. return s;
  1294. }
  1295. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1296. // Params used to be a std::multimap, which sorted by name and handed the
  1297. // caller's query back alphabetised. A client signing its query string could
  1298. // not reproduce the order it asked for.
  1299. Params dic;
  1300. dic.emplace("zulu", "1");
  1301. dic.emplace("alpha", "2");
  1302. dic.emplace("mike", "3");
  1303. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1304. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1305. }
  1306. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1307. Params dic;
  1308. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1309. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1310. }
  1311. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1312. Request req;
  1313. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1314. req.params);
  1315. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1316. EXPECT_EQ("first", req.get_param_value("tag"));
  1317. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1318. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1319. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1320. EXPECT_EQ("", req.get_param_value("tag", 3));
  1321. }
  1322. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1323. // Params shares its container with Headers, which matches field names
  1324. // case-insensitively. Parameter names must not pick that up.
  1325. Params dic;
  1326. dic.emplace("Key", "upper");
  1327. dic.emplace("key", "lower");
  1328. EXPECT_EQ(2U, dic.size());
  1329. EXPECT_EQ(1U, dic.count("Key"));
  1330. EXPECT_EQ(1U, dic.count("key"));
  1331. EXPECT_EQ("upper", dic.find("Key")->second);
  1332. EXPECT_EQ("lower", dic.find("key")->second);
  1333. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1334. }
  1335. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1336. Server svr;
  1337. std::string order;
  1338. svr.Get("/order", [&](const Request &req, Response &res) {
  1339. order = entries_to_string(req.params);
  1340. res.set_content("ok", "text/plain");
  1341. });
  1342. auto port = svr.bind_to_any_port(HOST);
  1343. thread t = thread([&] { svr.listen_after_bind(); });
  1344. auto se = detail::scope_exit([&] {
  1345. svr.stop();
  1346. t.join();
  1347. ASSERT_FALSE(svr.is_running());
  1348. });
  1349. svr.wait_until_ready();
  1350. Client cli(HOST, port);
  1351. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1352. ASSERT_TRUE(res);
  1353. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1354. }
  1355. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1356. Server svr;
  1357. std::string field_order, file_order;
  1358. svr.Post("/order", [&](const Request &req, Response &res) {
  1359. for (const auto &field : req.form.fields) {
  1360. field_order += field.first + "=" + field.second.content + " ";
  1361. }
  1362. for (const auto &file : req.form.files) {
  1363. file_order += file.first + "=" + file.second.filename + " ";
  1364. }
  1365. res.set_content("ok", "text/plain");
  1366. });
  1367. auto port = svr.bind_to_any_port(HOST);
  1368. thread t = thread([&] { svr.listen_after_bind(); });
  1369. auto se = detail::scope_exit([&] {
  1370. svr.stop();
  1371. t.join();
  1372. ASSERT_FALSE(svr.is_running());
  1373. });
  1374. svr.wait_until_ready();
  1375. UploadFormDataItems items = {
  1376. {"zulu", "1", "", ""},
  1377. {"alpha", "2", "", ""},
  1378. {"mike", "3", "", ""},
  1379. {"zebra", "z", "z.txt", "text/plain"},
  1380. {"apple", "a", "a.txt", "text/plain"},
  1381. };
  1382. Client cli(HOST, port);
  1383. auto res = cli.Post("/order", items);
  1384. ASSERT_TRUE(res);
  1385. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1386. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1387. }
  1388. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1389. Server svr;
  1390. std::vector<std::string> values;
  1391. std::string first, second, out_of_range, order;
  1392. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1393. values = req.form.get_fields("tag");
  1394. first = req.form.get_field("tag", 0);
  1395. second = req.form.get_field("tag", 1);
  1396. out_of_range = req.form.get_field("tag", 2);
  1397. for (const auto &field : req.form.fields) {
  1398. order += field.first + "=" + field.second.content + " ";
  1399. }
  1400. res.set_content("ok", "text/plain");
  1401. });
  1402. auto port = svr.bind_to_any_port(HOST);
  1403. thread t = thread([&] { svr.listen_after_bind(); });
  1404. auto se = detail::scope_exit([&] {
  1405. svr.stop();
  1406. t.join();
  1407. ASSERT_FALSE(svr.is_running());
  1408. });
  1409. svr.wait_until_ready();
  1410. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1411. // not adjacent in the container.
  1412. UploadFormDataItems items = {
  1413. {"tag", "first", "", ""},
  1414. {"other", "x", "", ""},
  1415. {"tag", "second", "", ""},
  1416. };
  1417. Client cli(HOST, port);
  1418. auto res = cli.Post("/repeated", items);
  1419. ASSERT_TRUE(res);
  1420. ASSERT_EQ(2U, values.size());
  1421. EXPECT_EQ("first", values[0]);
  1422. EXPECT_EQ("second", values[1]);
  1423. EXPECT_EQ("first", first);
  1424. EXPECT_EQ("second", second);
  1425. // std::multimap already kept entries sharing a name in insertion order, so
  1426. // everything above passes without this change too. The whole traversal is
  1427. // what tells the two apart: sorting by name would hoist "other" to the front
  1428. // and the two "tag" parts would end up adjacent.
  1429. EXPECT_EQ("tag=first other=x tag=second ", order);
  1430. // Advancing past the last entry of a name used to run off the container;
  1431. // the container's saturating increment makes it return the default instead.
  1432. EXPECT_EQ("", out_of_range);
  1433. }
  1434. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1435. // Server::read_content() keeps a FormFields::iterator alive across the
  1436. // content callbacks that fill the part it points at. The container is
  1437. // vector-backed, so a later emplace can reallocate and invalidate an older
  1438. // iterator; 64 parts grow the vector through seven reallocations, which
  1439. // checks that every part's content still lands in its own entry.
  1440. const size_t part_count = 64;
  1441. // One formula for both the parts sent and the values expected back, so the
  1442. // two cannot drift apart.
  1443. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1444. auto content_of = [](size_t i) {
  1445. return std::string(64, static_cast<char>('a' + (i % 26)));
  1446. };
  1447. Server svr;
  1448. std::vector<std::pair<std::string, std::string>> received;
  1449. svr.Post("/many", [&](const Request &req, Response &res) {
  1450. for (const auto &field : req.form.fields) {
  1451. received.emplace_back(field.first, field.second.content);
  1452. }
  1453. res.set_content("ok", "text/plain");
  1454. });
  1455. auto port = svr.bind_to_any_port(HOST);
  1456. thread t = thread([&] { svr.listen_after_bind(); });
  1457. auto se = detail::scope_exit([&] {
  1458. svr.stop();
  1459. t.join();
  1460. ASSERT_FALSE(svr.is_running());
  1461. });
  1462. svr.wait_until_ready();
  1463. UploadFormDataItems items;
  1464. for (size_t i = 0; i < part_count; i++) {
  1465. items.push_back({name_of(i), content_of(i), "", ""});
  1466. }
  1467. Client cli(HOST, port);
  1468. auto res = cli.Post("/many", items);
  1469. ASSERT_TRUE(res);
  1470. ASSERT_EQ(part_count, received.size());
  1471. for (size_t i = 0; i < part_count; i++) {
  1472. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1473. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1474. }
  1475. }
  1476. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1477. string content_type = "multipart/form-data; boundary=something";
  1478. string boundary;
  1479. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1480. EXPECT_TRUE(ret);
  1481. EXPECT_EQ(boundary, "something");
  1482. }
  1483. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1484. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1485. string boundary;
  1486. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1487. EXPECT_TRUE(ret);
  1488. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1489. }
  1490. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1491. string content_type =
  1492. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1493. string boundary;
  1494. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1495. EXPECT_TRUE(ret);
  1496. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1497. }
  1498. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1499. string content_type =
  1500. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1501. string boundary;
  1502. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1503. EXPECT_TRUE(ret);
  1504. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1505. }
  1506. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1507. const string boundary(70, 'a');
  1508. string content_type = "multipart/form-data; boundary=" + boundary;
  1509. string parsed;
  1510. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1511. EXPECT_TRUE(ret);
  1512. EXPECT_EQ(parsed, boundary);
  1513. }
  1514. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1515. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1516. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1517. string parsed;
  1518. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1519. EXPECT_FALSE(ret);
  1520. }
  1521. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1522. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1523. // is 72 characters on the wire and still valid.
  1524. const string boundary(70, 'a');
  1525. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1526. string parsed;
  1527. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1528. EXPECT_EQ(parsed, boundary);
  1529. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1530. parsed.clear();
  1531. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1532. }
  1533. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1534. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1535. // The parameter parser must not treat that '=' as the key/value separator.
  1536. string content_type =
  1537. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1538. "charset=UTF-8";
  1539. string parsed;
  1540. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1541. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1542. }
  1543. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1544. // A ';' inside the quoted-string is part of the value, not a parameter
  1545. // separator, so it must not truncate the boundary.
  1546. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1547. string parsed;
  1548. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1549. EXPECT_EQ(parsed, "a;b");
  1550. }
  1551. TEST(ParseDispositionParamsTest, QuotedValues) {
  1552. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1553. // ';' and '=' are ordinary characters inside one.
  1554. struct {
  1555. const char *value;
  1556. std::vector<std::pair<const char *, const char *>> expected;
  1557. } cases[] = {
  1558. {"name=\"file1\"; filename=\"a.txt\"",
  1559. {{"name", "file1"}, {"filename", "a.txt"}}},
  1560. // Whitespace around '=' and ';' is still trimmed
  1561. {"name=\"file2\" ;filename = \"a.html\"",
  1562. {{"name", "file2"}, {"filename", "a.html"}}},
  1563. // '=' inside the value used to leave only the text after the last one
  1564. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1565. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1566. {"name=\"x=y\"", {{"name", "x=y"}}},
  1567. // ';' inside the value used to truncate the pair and leave a bogus one
  1568. {"name=\"file3\"; filename=\"a;b.txt\"",
  1569. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1570. // An unquoted value keeps working, and so does filename*
  1571. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1572. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1573. // A parameter with no key is dropped rather than turned into one whose
  1574. // key is the value
  1575. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1576. // An escaped quote does not end the value
  1577. {"name=\"a\\\"; filename=evil.php\"",
  1578. {{"name", "a\"; filename=evil.php"}}},
  1579. // Other backslashes, as in a Windows path, are kept
  1580. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1581. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1582. };
  1583. for (const auto &c : cases) {
  1584. Params params;
  1585. detail::parse_disposition_params(c.value, params);
  1586. for (const auto &kv : c.expected) {
  1587. auto it = params.find(kv.first);
  1588. ASSERT_NE(it, params.end())
  1589. << "value: " << c.value << ", key: " << kv.first;
  1590. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1591. }
  1592. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1593. }
  1594. }
  1595. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1596. Server svr;
  1597. std::string filename;
  1598. std::string content;
  1599. svr.Post("/upload", [&](const Request &req, Response &) {
  1600. const auto &file = req.form.get_file("file");
  1601. filename = file.filename;
  1602. content = file.content;
  1603. });
  1604. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1605. auto se = detail::scope_exit([&] {
  1606. svr.stop();
  1607. thread.join();
  1608. ASSERT_FALSE(svr.is_running());
  1609. });
  1610. svr.wait_until_ready();
  1611. std::string body = "--B\r\n"
  1612. "Content-Disposition: form-data; name=\"file\"; "
  1613. "filename=\"a.txt\"\r\n"
  1614. "Content-Type: text/plain\r\n"
  1615. "\r\n"
  1616. "hello\r\n"
  1617. "--B--\r\n";
  1618. Client cli(HOST, PORT);
  1619. auto res = cli.Post(
  1620. "/upload",
  1621. [&](size_t offset, DataSink &sink) {
  1622. if (offset < body.size()) {
  1623. sink.write(&body[offset], 1);
  1624. } else {
  1625. sink.done();
  1626. }
  1627. return true;
  1628. },
  1629. "multipart/form-data; boundary=B");
  1630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1631. EXPECT_EQ(StatusCode::OK_200, res->status);
  1632. EXPECT_EQ("a.txt", filename);
  1633. EXPECT_EQ("hello", content);
  1634. }
  1635. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1636. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1637. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1638. Server svr;
  1639. std::string field_value, file_name, file_filename;
  1640. bool has_field = false, has_file = false;
  1641. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1642. has_field = req.form.has_field("x=y");
  1643. field_value = req.form.get_field("x=y");
  1644. has_file = req.form.has_file("file1");
  1645. const auto &file = req.form.get_file("file1");
  1646. file_name = file.name;
  1647. file_filename = file.filename;
  1648. res.set_content("ok", "text/plain");
  1649. });
  1650. auto port = svr.bind_to_any_port(HOST);
  1651. thread t = thread([&] { svr.listen_after_bind(); });
  1652. auto se = detail::scope_exit([&] {
  1653. svr.stop();
  1654. t.join();
  1655. ASSERT_FALSE(svr.is_running());
  1656. });
  1657. svr.wait_until_ready();
  1658. UploadFormDataItems items = {
  1659. {"x=y", "field-value", "", ""},
  1660. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1661. };
  1662. Client cli(HOST, port);
  1663. auto res = cli.Post("/quoted", items);
  1664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1665. ASSERT_EQ(StatusCode::OK_200, res->status);
  1666. EXPECT_TRUE(has_field);
  1667. EXPECT_EQ("field-value", field_value);
  1668. EXPECT_TRUE(has_file);
  1669. EXPECT_EQ("file1", file_name);
  1670. EXPECT_EQ("a;b=report.pdf", file_filename);
  1671. }
  1672. TEST(GetHeaderValueTest, DefaultValue) {
  1673. Headers headers = {{"Dummy", "Dummy"}};
  1674. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1675. EXPECT_STREQ("text/plain", val);
  1676. }
  1677. TEST(GetHeaderValueTest, DefaultValueInt) {
  1678. Headers headers = {{"Dummy", "Dummy"}};
  1679. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1680. EXPECT_EQ(100ull, val);
  1681. }
  1682. TEST(GetHeaderValueTest, RegularValue) {
  1683. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1684. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1685. EXPECT_STREQ("text/html", val);
  1686. }
  1687. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1688. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1689. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1690. EXPECT_STREQ("text/html", val);
  1691. }
  1692. TEST(GetHeaderValueTest, SetContent) {
  1693. Response res;
  1694. res.set_content("html", "text/html");
  1695. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1696. res.set_content("text", "text/plain");
  1697. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1698. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1699. }
  1700. TEST(GetHeaderValueTest, RegularValueInt) {
  1701. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1702. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1703. EXPECT_EQ(100ull, val);
  1704. }
  1705. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1706. Headers headers = {{"Content-Length", "x"}};
  1707. auto is_invalid_value = false;
  1708. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1709. is_invalid_value);
  1710. EXPECT_EQ(0ull, val);
  1711. EXPECT_TRUE(is_invalid_value);
  1712. }
  1713. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1714. // An all-digit value that overflows size_t must be reported as invalid, not
  1715. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1716. // a large length to a small one on 32-bit builds, leaving the framing length
  1717. // wrong while is_invalid_value stayed false.
  1718. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1719. auto is_invalid_value = false;
  1720. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1721. is_invalid_value);
  1722. EXPECT_TRUE(is_invalid_value);
  1723. // A well-formed length is unaffected.
  1724. Headers ok = {{"Content-Length", "1234"}};
  1725. is_invalid_value = false;
  1726. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1727. is_invalid_value);
  1728. EXPECT_EQ(1234ull, val);
  1729. EXPECT_FALSE(is_invalid_value);
  1730. }
  1731. TEST(GetHeaderValueTest, Range) {
  1732. {
  1733. Headers headers = {make_range_header({{1, -1}})};
  1734. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1735. EXPECT_STREQ("bytes=1-", val);
  1736. }
  1737. {
  1738. Headers headers = {make_range_header({{-1, 1}})};
  1739. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1740. EXPECT_STREQ("bytes=-1", val);
  1741. }
  1742. {
  1743. Headers headers = {make_range_header({{1, 10}})};
  1744. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1745. EXPECT_STREQ("bytes=1-10", val);
  1746. }
  1747. {
  1748. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1749. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1750. EXPECT_STREQ("bytes=1-10, 100-", val);
  1751. }
  1752. {
  1753. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1754. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1755. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1756. }
  1757. {
  1758. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1759. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1760. EXPECT_STREQ("bytes=0-0, -1", val);
  1761. }
  1762. }
  1763. TEST(BearerTokenAuthTest, SchemeValidation) {
  1764. // A value shorter than "Bearer " must not throw from the fixed-length
  1765. // substr, and a non-Bearer scheme must not be reported as a token.
  1766. struct {
  1767. const char *value;
  1768. const char *expected;
  1769. } cases[] = {
  1770. {"x", ""},
  1771. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1772. {"Bearer abc123", "abc123"},
  1773. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1774. };
  1775. for (const auto &c : cases) {
  1776. Request req;
  1777. req.set_header("Authorization", c.value);
  1778. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1779. }
  1780. }
  1781. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1782. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1783. // to depend on the standard library (libstdc++ handed back duplicates in
  1784. // reverse insertion order, libc++ in insertion order).
  1785. Request req;
  1786. req.set_header("Accept-Encoding", "gzip");
  1787. req.set_header("Accept-Encoding", "deflate");
  1788. req.set_header("Accept-Encoding", "br");
  1789. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1790. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1791. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1792. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1793. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1794. }
  1795. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1796. Request req;
  1797. req.set_header("X-Test", "only");
  1798. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1799. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1800. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1801. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1802. }
  1803. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1804. Request req;
  1805. req.set_header("X-First", "1");
  1806. req.set_header("X-Test", "2");
  1807. req.params.emplace("first", "1");
  1808. req.params.emplace("test", "2");
  1809. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1810. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1811. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1812. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1813. // The second one is negative when read as a signed value
  1814. const auto max_id = (std::numeric_limits<size_t>::max)();
  1815. for (auto id : {max_id / 2, max_id}) {
  1816. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1817. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1818. EXPECT_EQ("", req.get_param_value("test", id));
  1819. EXPECT_EQ("", req.form.get_field("test", id));
  1820. EXPECT_EQ("", req.form.get_file("test", id).content);
  1821. }
  1822. }
  1823. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1824. Headers headers;
  1825. headers.emplace("Host", "example.com");
  1826. headers.emplace("Accept-Encoding", "gzip");
  1827. headers.emplace("User-Agent", "test");
  1828. headers.emplace("Accept-Encoding", "deflate");
  1829. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1830. "Accept-Encoding=deflate ",
  1831. entries_to_string(headers));
  1832. }
  1833. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1834. Headers headers = {{"Content-Type", "text/html"},
  1835. {"CONTENT-TYPE", "text/xml"}};
  1836. EXPECT_EQ(2U, headers.count("content-type"));
  1837. auto it = headers.find("content-type");
  1838. ASSERT_TRUE(it != headers.end());
  1839. EXPECT_EQ("text/html", it->second);
  1840. }
  1841. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1842. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1843. // drop only those fields and leave everything positioned between them.
  1844. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1845. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1846. auto rng = headers.equal_range("a");
  1847. headers.erase(rng.first, rng.second);
  1848. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1849. }
  1850. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1851. Headers headers = {
  1852. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1853. EXPECT_EQ(3U, headers.erase("A"));
  1854. EXPECT_EQ(0U, headers.count("A"));
  1855. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1856. }
  1857. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1858. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1859. headers.emplace_front("Host", "example.com");
  1860. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1861. entries_to_string(headers));
  1862. }
  1863. TEST(ParseHeaderValueTest, Range) {
  1864. {
  1865. Ranges ranges;
  1866. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1867. EXPECT_TRUE(ret);
  1868. EXPECT_EQ(1u, ranges.size());
  1869. EXPECT_EQ(1u, ranges[0].first);
  1870. EXPECT_EQ(-1, ranges[0].second);
  1871. }
  1872. {
  1873. Ranges ranges;
  1874. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1875. EXPECT_TRUE(ret);
  1876. EXPECT_EQ(1u, ranges.size());
  1877. EXPECT_EQ(-1, ranges[0].first);
  1878. EXPECT_EQ(1u, ranges[0].second);
  1879. }
  1880. {
  1881. Ranges ranges;
  1882. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1883. EXPECT_TRUE(ret);
  1884. EXPECT_EQ(1u, ranges.size());
  1885. EXPECT_EQ(1u, ranges[0].first);
  1886. EXPECT_EQ(10u, ranges[0].second);
  1887. }
  1888. {
  1889. Ranges ranges;
  1890. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1891. EXPECT_FALSE(ret);
  1892. }
  1893. {
  1894. Ranges ranges;
  1895. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1896. EXPECT_TRUE(ret);
  1897. EXPECT_EQ(2u, ranges.size());
  1898. EXPECT_EQ(1u, ranges[0].first);
  1899. EXPECT_EQ(10u, ranges[0].second);
  1900. EXPECT_EQ(100u, ranges[1].first);
  1901. EXPECT_EQ(-1, ranges[1].second);
  1902. }
  1903. {
  1904. Ranges ranges;
  1905. auto ret =
  1906. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1907. EXPECT_TRUE(ret);
  1908. EXPECT_EQ(3u, ranges.size());
  1909. EXPECT_EQ(1u, ranges[0].first);
  1910. EXPECT_EQ(10u, ranges[0].second);
  1911. EXPECT_EQ(100u, ranges[1].first);
  1912. EXPECT_EQ(200u, ranges[1].second);
  1913. EXPECT_EQ(300u, ranges[2].first);
  1914. EXPECT_EQ(400u, ranges[2].second);
  1915. }
  1916. {
  1917. Ranges ranges;
  1918. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1919. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1920. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1921. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1922. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1923. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1924. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1925. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1926. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1927. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1928. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1929. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1930. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1931. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1932. EXPECT_FALSE(
  1933. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1934. EXPECT_TRUE(ranges.empty());
  1935. }
  1936. {
  1937. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1938. // remainder of the representation, so it stays accepted.
  1939. Ranges ranges;
  1940. auto ret =
  1941. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1942. EXPECT_TRUE(ret);
  1943. ASSERT_EQ(1u, ranges.size());
  1944. EXPECT_EQ(0, ranges[0].first);
  1945. EXPECT_EQ(-1, ranges[0].second);
  1946. }
  1947. // RFC 9110 14.1: range unit names are case-insensitive.
  1948. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  1949. Ranges ranges;
  1950. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  1951. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  1952. }
  1953. }
  1954. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1955. Request req;
  1956. req.set_header("Accept-Encoding", "gzip");
  1957. Response res;
  1958. res.set_header("Content-Type", "text/plain");
  1959. auto ret = detail::encoding_type(req, res);
  1960. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1961. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1962. #else
  1963. EXPECT_TRUE(ret == detail::EncodingType::None);
  1964. #endif
  1965. }
  1966. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1967. Request req;
  1968. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1969. Response res;
  1970. res.set_header("Content-Type", "text/plain");
  1971. auto ret = detail::encoding_type(req, res);
  1972. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1973. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1974. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1975. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1976. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1977. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1978. #else
  1979. EXPECT_TRUE(ret == detail::EncodingType::None);
  1980. #endif
  1981. }
  1982. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1983. Request req;
  1984. req.set_header("Accept-Encoding",
  1985. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1986. Response res;
  1987. res.set_header("Content-Type", "text/plain");
  1988. auto ret = detail::encoding_type(req, res);
  1989. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1990. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1991. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1992. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1993. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1994. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1995. #else
  1996. EXPECT_TRUE(ret == detail::EncodingType::None);
  1997. #endif
  1998. }
  1999. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2000. // All supported encodings rejected with q=0 should return None
  2001. Request req;
  2002. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2003. Response res;
  2004. res.set_header("Content-Type", "text/plain");
  2005. auto ret = detail::encoding_type(req, res);
  2006. EXPECT_TRUE(ret == detail::EncodingType::None);
  2007. }
  2008. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2009. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2010. Request req;
  2011. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2012. Response res;
  2013. res.set_header("Content-Type", "text/plain");
  2014. auto ret = detail::encoding_type(req, res);
  2015. EXPECT_TRUE(ret == detail::EncodingType::None);
  2016. }
  2017. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2018. Request req;
  2019. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2020. Response res;
  2021. res.set_header("Content-Type", "text/plain");
  2022. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2023. }
  2024. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2025. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2026. Request req;
  2027. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2028. Response res;
  2029. res.set_header("Content-Type", "text/plain");
  2030. auto ret = detail::encoding_type(req, res);
  2031. EXPECT_TRUE(ret == detail::EncodingType::None);
  2032. }
  2033. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2034. // RFC 7231: Accept-Encoding values are case-insensitive
  2035. Request req;
  2036. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2037. Response res;
  2038. res.set_header("Content-Type", "text/plain");
  2039. auto ret = detail::encoding_type(req, res);
  2040. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2041. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2042. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2043. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2044. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2045. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2046. #else
  2047. EXPECT_TRUE(ret == detail::EncodingType::None);
  2048. #endif
  2049. }
  2050. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2051. // q value should determine priority, not hardcoded order
  2052. Request req;
  2053. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2054. Response res;
  2055. res.set_header("Content-Type", "text/plain");
  2056. auto ret = detail::encoding_type(req, res);
  2057. // gzip has highest q=1.0, so it should be selected even though
  2058. // br and zstd are also supported
  2059. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2060. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2061. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2062. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2063. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2064. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2065. #else
  2066. EXPECT_TRUE(ret == detail::EncodingType::None);
  2067. #endif
  2068. }
  2069. TEST(BufferStreamTest, read) {
  2070. detail::BufferStream strm1;
  2071. Stream &strm = strm1;
  2072. EXPECT_EQ(5, strm.write("hello"));
  2073. char buf[512];
  2074. EXPECT_EQ(2, strm.read(buf, 2));
  2075. EXPECT_EQ('h', buf[0]);
  2076. EXPECT_EQ('e', buf[1]);
  2077. EXPECT_EQ(2, strm.read(buf, 2));
  2078. EXPECT_EQ('l', buf[0]);
  2079. EXPECT_EQ('l', buf[1]);
  2080. EXPECT_EQ(1, strm.read(buf, 1));
  2081. EXPECT_EQ('o', buf[0]);
  2082. EXPECT_EQ(0, strm.read(buf, 1));
  2083. }
  2084. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2085. auto host = "www.httpwatch.com";
  2086. auto ip = hosted_at(host);
  2087. EXPECT_EQ("23.96.13.243", ip);
  2088. std::vector<std::string> addrs;
  2089. hosted_at(host, addrs);
  2090. EXPECT_EQ(1u, addrs.size());
  2091. }
  2092. #if 0 // It depends on each test environment...
  2093. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2094. auto host = "www.youtube.com";
  2095. std::vector<std::string> addrs;
  2096. hosted_at(host, addrs);
  2097. EXPECT_EQ(20u, addrs.size());
  2098. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2099. EXPECT_TRUE(it != addrs.end());
  2100. }
  2101. #endif
  2102. class ChunkedEncodingTest : public ::testing::Test {
  2103. protected:
  2104. ChunkedEncodingTest()
  2105. : cli_(HOST, PORT)
  2106. #ifdef CPPHTTPLIB_SSL_ENABLED
  2107. ,
  2108. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2109. #endif
  2110. {
  2111. cli_.set_connection_timeout(2);
  2112. #ifdef CPPHTTPLIB_SSL_ENABLED
  2113. cli_.enable_server_certificate_verification(false);
  2114. #endif
  2115. }
  2116. virtual void SetUp() {
  2117. read_file("./image.jpg", image_data_);
  2118. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2119. res.set_content("Hello World!", "text/plain");
  2120. });
  2121. svr_.Get(
  2122. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2123. res.set_chunked_content_provider(
  2124. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2125. size_t remaining = image_data_.size() - offset;
  2126. if (remaining == 0) {
  2127. sink.done();
  2128. } else {
  2129. constexpr size_t CHUNK_SIZE = 1024;
  2130. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2131. sink.write(&image_data_[offset], send_size);
  2132. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2133. }
  2134. return true;
  2135. });
  2136. });
  2137. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2138. svr_.wait_until_ready();
  2139. }
  2140. virtual void TearDown() {
  2141. svr_.stop();
  2142. if (!request_threads_.empty()) {
  2143. std::this_thread::sleep_for(std::chrono::seconds(1));
  2144. for (auto &t : request_threads_) {
  2145. t.join();
  2146. }
  2147. }
  2148. t_.join();
  2149. }
  2150. #ifdef CPPHTTPLIB_SSL_ENABLED
  2151. SSLClient cli_;
  2152. SSLServer svr_;
  2153. #else
  2154. Client cli_;
  2155. Server svr_;
  2156. #endif
  2157. thread t_;
  2158. std::vector<thread> request_threads_;
  2159. std::string image_data_;
  2160. };
  2161. TEST_F(ChunkedEncodingTest, NormalGet) {
  2162. auto res = cli_.Get("/chunked");
  2163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2164. std::string out;
  2165. read_file("./image.jpg", out);
  2166. EXPECT_EQ(StatusCode::OK_200, res->status);
  2167. EXPECT_EQ(out, res->body);
  2168. }
  2169. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2170. std::string body;
  2171. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2172. body.append(data, data_length);
  2173. return true;
  2174. });
  2175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2176. std::string out;
  2177. read_file("./image.jpg", out);
  2178. EXPECT_EQ(StatusCode::OK_200, res->status);
  2179. EXPECT_EQ(out, body);
  2180. }
  2181. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2182. std::string body;
  2183. auto res = cli_.Get(
  2184. "/chunked",
  2185. [&](const Response &response) {
  2186. EXPECT_EQ(StatusCode::OK_200, response.status);
  2187. return true;
  2188. },
  2189. [&](const char *data, size_t data_length) {
  2190. body.append(data, data_length);
  2191. return true;
  2192. });
  2193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2194. std::string out;
  2195. read_file("./image.jpg", out);
  2196. EXPECT_EQ(StatusCode::OK_200, res->status);
  2197. EXPECT_EQ(out, body);
  2198. }
  2199. TEST(RangeTest, FromHTTPBin_Online) {
  2200. auto host = "httpbingo.org";
  2201. auto path = std::string{"/range/32"};
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. auto port = 443;
  2204. SSLClient cli(host, port);
  2205. #else
  2206. auto port = 80;
  2207. Client cli(host, port);
  2208. #endif
  2209. cli.set_connection_timeout(5);
  2210. {
  2211. auto res = cli.Get(path);
  2212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2213. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2214. EXPECT_EQ(StatusCode::OK_200, res->status);
  2215. }
  2216. {
  2217. Headers headers = {make_range_header({{1, -1}})};
  2218. auto res = cli.Get(path, headers);
  2219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2220. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2221. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2222. }
  2223. {
  2224. Headers headers = {make_range_header({{1, 10}})};
  2225. auto res = cli.Get(path, headers);
  2226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2227. EXPECT_EQ("bcdefghijk", res->body);
  2228. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2229. }
  2230. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2231. // entire resource, while the original httpbin returned 200. Both are
  2232. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2233. {
  2234. Headers headers = {make_range_header({{0, 31}})};
  2235. auto res = cli.Get(path, headers);
  2236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2237. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2238. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2239. res->status == StatusCode::PartialContent_206);
  2240. }
  2241. {
  2242. Headers headers = {make_range_header({{0, -1}})};
  2243. auto res = cli.Get(path, headers);
  2244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2245. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2246. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2247. res->status == StatusCode::PartialContent_206);
  2248. }
  2249. // go-httpbin returns 206 with clamped range for over-range requests,
  2250. // while the original httpbin returned 416. Both behaviors are observed
  2251. // in real servers, so we only verify the request succeeds.
  2252. {
  2253. Headers headers = {make_range_header({{0, 32}})};
  2254. auto res = cli.Get(path, headers);
  2255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2256. }
  2257. }
  2258. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2259. auto host = "unresolvableaddress.local";
  2260. auto path = std::string{"/"};
  2261. #ifdef CPPHTTPLIB_SSL_ENABLED
  2262. auto port = 443;
  2263. SSLClient cli(host, port);
  2264. #else
  2265. auto port = 80;
  2266. Client cli(host, port);
  2267. #endif
  2268. cli.set_connection_timeout(1);
  2269. {
  2270. auto res = cli.Get(path);
  2271. ASSERT_FALSE(res);
  2272. }
  2273. std::this_thread::sleep_for(std::chrono::seconds(8));
  2274. }
  2275. #if defined(__linux__) && defined(__GLIBC__) && \
  2276. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2277. // Forward declaration: in split builds split.py strips `inline` and moves the
  2278. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2279. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2280. // against the symbol in both header-only and split builds.
  2281. namespace httplib {
  2282. namespace detail {
  2283. int getaddrinfo_with_timeout(const char *node, const char *service,
  2284. const struct addrinfo *hints,
  2285. struct addrinfo **res, time_t timeout_sec);
  2286. } // namespace detail
  2287. } // namespace httplib
  2288. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2289. //
  2290. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2291. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2292. // gai_suspend() call hits the connection timeout the function calls
  2293. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2294. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2295. // still alive and still references the now-destroyed stack frame.
  2296. //
  2297. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2298. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2299. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2300. // and runs them in a container.
  2301. namespace {
  2302. bool should_run_issue_2431_tests() {
  2303. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2304. return v && *v && std::string(v) != "0";
  2305. }
  2306. std::string unique_unresolvable_host(int n) {
  2307. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2308. // glibc still asks the configured nameserver — which is exactly the path
  2309. // we want to exercise. A unique label per call avoids the resolver cache.
  2310. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2311. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2312. std::to_string(n) + ".invalid";
  2313. }
  2314. } // namespace
  2315. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2316. if (!should_run_issue_2431_tests()) {
  2317. GTEST_SKIP()
  2318. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2319. }
  2320. for (int i = 0; i < 8; ++i) {
  2321. struct addrinfo hints;
  2322. memset(&hints, 0, sizeof(hints));
  2323. hints.ai_family = AF_UNSPEC;
  2324. hints.ai_socktype = SOCK_STREAM;
  2325. auto host = unique_unresolvable_host(i);
  2326. struct addrinfo *result = nullptr;
  2327. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2328. &result, /*timeout_sec=*/1);
  2329. if (rc == 0 && result) { freeaddrinfo(result); }
  2330. }
  2331. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2332. // stack region they still believe holds their gaicb.
  2333. std::this_thread::sleep_for(std::chrono::seconds(3));
  2334. }
  2335. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2336. if (!should_run_issue_2431_tests()) {
  2337. GTEST_SKIP()
  2338. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2339. }
  2340. std::atomic<bool> stop{false};
  2341. std::vector<std::thread> threads;
  2342. for (int t = 0; t < 8; ++t) {
  2343. threads.emplace_back([t, &stop] {
  2344. int i = 0;
  2345. while (!stop.load(std::memory_order_relaxed)) {
  2346. struct addrinfo hints;
  2347. memset(&hints, 0, sizeof(hints));
  2348. hints.ai_family = AF_UNSPEC;
  2349. hints.ai_socktype = SOCK_STREAM;
  2350. auto host = unique_unresolvable_host(t * 100000 + i++);
  2351. struct addrinfo *result = nullptr;
  2352. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2353. &result, /*timeout_sec=*/1);
  2354. if (rc == 0 && result) { freeaddrinfo(result); }
  2355. }
  2356. });
  2357. }
  2358. std::this_thread::sleep_for(std::chrono::seconds(8));
  2359. stop.store(true, std::memory_order_relaxed);
  2360. for (auto &th : threads) {
  2361. th.join();
  2362. }
  2363. std::this_thread::sleep_for(std::chrono::seconds(3));
  2364. }
  2365. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2366. if (!should_run_issue_2431_tests()) {
  2367. GTEST_SKIP()
  2368. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2369. }
  2370. std::atomic<bool> stop{false};
  2371. std::vector<std::thread> threads;
  2372. for (int t = 0; t < 8; ++t) {
  2373. threads.emplace_back([t, &stop] {
  2374. int i = 0;
  2375. while (!stop.load(std::memory_order_relaxed)) {
  2376. auto host = unique_unresolvable_host(t * 100000 + i++);
  2377. Client cli(host, 80);
  2378. cli.set_connection_timeout(1, 0);
  2379. cli.set_read_timeout(1, 0);
  2380. cli.set_write_timeout(1, 0);
  2381. (void)cli.Get("/");
  2382. }
  2383. });
  2384. }
  2385. std::this_thread::sleep_for(std::chrono::seconds(8));
  2386. stop.store(true, std::memory_order_relaxed);
  2387. for (auto &th : threads) {
  2388. th.join();
  2389. }
  2390. std::this_thread::sleep_for(std::chrono::seconds(3));
  2391. }
  2392. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2393. TEST(ConnectionErrorTest, InvalidHost) {
  2394. auto host = "-abcde.com";
  2395. #ifdef CPPHTTPLIB_SSL_ENABLED
  2396. auto port = 443;
  2397. SSLClient cli(host, port);
  2398. #else
  2399. auto port = 80;
  2400. Client cli(host, port);
  2401. #endif
  2402. cli.set_connection_timeout(std::chrono::seconds(2));
  2403. auto res = cli.Get("/");
  2404. ASSERT_TRUE(!res);
  2405. EXPECT_EQ(Error::Connection, res.error());
  2406. }
  2407. TEST(ConnectionErrorTest, InvalidHost2) {
  2408. auto host = "httpcan.org/";
  2409. #ifdef CPPHTTPLIB_SSL_ENABLED
  2410. SSLClient cli(host);
  2411. #else
  2412. Client cli(host);
  2413. #endif
  2414. cli.set_connection_timeout(std::chrono::seconds(2));
  2415. auto res = cli.Get("/");
  2416. ASSERT_TRUE(!res);
  2417. EXPECT_EQ(Error::Connection, res.error());
  2418. }
  2419. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2420. auto host = "httpcan.org/";
  2421. #ifdef CPPHTTPLIB_SSL_ENABLED
  2422. SSLClient cli(host);
  2423. #else
  2424. Client cli(host);
  2425. #endif
  2426. cli.set_connection_timeout(std::chrono::seconds(2));
  2427. auto res = cli.Get("/");
  2428. ASSERT_TRUE(!res);
  2429. stringstream s;
  2430. s << "error code: " << res.error();
  2431. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2432. }
  2433. TEST(ConnectionErrorTest, InvalidPort) {
  2434. auto host = "localhost";
  2435. auto port = 44380;
  2436. #ifdef CPPHTTPLIB_SSL_ENABLED
  2437. SSLClient cli(host, port);
  2438. #else
  2439. Client cli(host, port);
  2440. #endif
  2441. cli.set_connection_timeout(std::chrono::seconds(2));
  2442. auto res = cli.Get("/");
  2443. ASSERT_TRUE(!res);
  2444. EXPECT_TRUE(Error::Connection == res.error() ||
  2445. Error::ConnectionTimeout == res.error());
  2446. }
  2447. TEST(ConnectionErrorTest, Timeout_Online) {
  2448. auto host = "google.com";
  2449. #ifdef CPPHTTPLIB_SSL_ENABLED
  2450. auto port = 44380;
  2451. SSLClient cli(host, port);
  2452. #else
  2453. auto port = 8080;
  2454. Client cli(host, port);
  2455. #endif
  2456. cli.set_connection_timeout(std::chrono::seconds(2));
  2457. // only probe one address type so that the error reason
  2458. // correlates to the timed-out IPv4, not the unsupported
  2459. // IPv6 connection attempt
  2460. cli.set_address_family(AF_INET);
  2461. auto res = cli.Get("/");
  2462. ASSERT_TRUE(!res);
  2463. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2464. }
  2465. TEST(CancelTest, NoCancel_Online) {
  2466. auto host = "httpbingo.org";
  2467. auto path = std::string{"/range/32"};
  2468. #ifdef CPPHTTPLIB_SSL_ENABLED
  2469. auto port = 443;
  2470. SSLClient cli(host, port);
  2471. #else
  2472. auto port = 80;
  2473. Client cli(host, port);
  2474. #endif
  2475. cli.set_connection_timeout(std::chrono::seconds(5));
  2476. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2478. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2479. EXPECT_EQ(StatusCode::OK_200, res->status);
  2480. }
  2481. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2482. // Use /bytes with a large payload so that the DownloadProgress callback
  2483. // (which only fires for Content-Length responses) is invoked before the
  2484. // entire body is received, giving cancellation a chance to fire.
  2485. auto host = "httpbingo.org";
  2486. auto path = std::string{"/bytes/524288"};
  2487. #ifdef CPPHTTPLIB_SSL_ENABLED
  2488. auto port = 443;
  2489. SSLClient cli(host, port);
  2490. #else
  2491. auto port = 80;
  2492. Client cli(host, port);
  2493. #endif
  2494. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2495. cli.set_connection_timeout(std::chrono::seconds(5));
  2496. ASSERT_TRUE(!res);
  2497. EXPECT_EQ(Error::Canceled, res.error());
  2498. }
  2499. TEST(CancelTest, WithCancelLargePayload_Online) {
  2500. auto host = "httpbingo.org";
  2501. auto path = std::string{"/bytes/524288"};
  2502. #ifdef CPPHTTPLIB_SSL_ENABLED
  2503. auto port = 443;
  2504. SSLClient cli(host, port);
  2505. #else
  2506. auto port = 80;
  2507. Client cli(host, port);
  2508. #endif
  2509. cli.set_connection_timeout(std::chrono::seconds(5));
  2510. uint32_t count = 0;
  2511. auto res =
  2512. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2513. ASSERT_TRUE(!res);
  2514. EXPECT_EQ(Error::Canceled, res.error());
  2515. }
  2516. TEST(CancelTest, NoCancelPost) {
  2517. Server svr;
  2518. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2519. res.set_content("Hello World!", "text/plain");
  2520. });
  2521. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2522. auto se = detail::scope_exit([&] {
  2523. svr.stop();
  2524. thread.join();
  2525. ASSERT_FALSE(svr.is_running());
  2526. });
  2527. svr.wait_until_ready();
  2528. Client cli(HOST, PORT);
  2529. cli.set_connection_timeout(std::chrono::seconds(5));
  2530. auto res =
  2531. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2532. "application/json", [](uint64_t, uint64_t) { return true; });
  2533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2534. EXPECT_EQ("Hello World!", res->body);
  2535. EXPECT_EQ(StatusCode::OK_200, res->status);
  2536. }
  2537. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2538. Server svr;
  2539. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2540. res.set_content("Hello World!", "text/plain");
  2541. });
  2542. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2543. auto se = detail::scope_exit([&] {
  2544. svr.stop();
  2545. thread.join();
  2546. ASSERT_FALSE(svr.is_running());
  2547. });
  2548. svr.wait_until_ready();
  2549. Client cli(HOST, PORT);
  2550. cli.set_connection_timeout(std::chrono::seconds(5));
  2551. auto res =
  2552. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2553. "application/json", [](uint64_t, uint64_t) { return false; });
  2554. ASSERT_TRUE(!res);
  2555. EXPECT_EQ(Error::Canceled, res.error());
  2556. }
  2557. TEST(CancelTest, WithCancelLargePayloadPost) {
  2558. Server svr;
  2559. svr.set_payload_max_length(200 * 1024 * 1024);
  2560. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2561. res.set_content(LARGE_DATA, "text/plain");
  2562. });
  2563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2564. auto se = detail::scope_exit([&] {
  2565. svr.stop();
  2566. thread.join();
  2567. ASSERT_FALSE(svr.is_running());
  2568. });
  2569. svr.wait_until_ready();
  2570. Client cli(HOST, PORT);
  2571. cli.set_payload_max_length(200 * 1024 * 1024);
  2572. cli.set_connection_timeout(std::chrono::seconds(5));
  2573. auto res =
  2574. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2575. "application/json", [](uint64_t, uint64_t) { return false; });
  2576. ASSERT_TRUE(!res);
  2577. EXPECT_EQ(Error::Canceled, res.error());
  2578. }
  2579. TEST(CancelTest, NoCancelPut) {
  2580. Server svr;
  2581. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2582. res.set_content("Hello World!", "text/plain");
  2583. });
  2584. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2585. auto se = detail::scope_exit([&] {
  2586. svr.stop();
  2587. thread.join();
  2588. ASSERT_FALSE(svr.is_running());
  2589. });
  2590. svr.wait_until_ready();
  2591. Client cli(HOST, PORT);
  2592. cli.set_connection_timeout(std::chrono::seconds(5));
  2593. auto res =
  2594. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2595. "application/json", [](uint64_t, uint64_t) { return true; });
  2596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2597. EXPECT_EQ("Hello World!", res->body);
  2598. EXPECT_EQ(StatusCode::OK_200, res->status);
  2599. }
  2600. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2601. Server svr;
  2602. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2603. res.set_content("Hello World!", "text/plain");
  2604. });
  2605. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2606. auto se = detail::scope_exit([&] {
  2607. svr.stop();
  2608. thread.join();
  2609. ASSERT_FALSE(svr.is_running());
  2610. });
  2611. svr.wait_until_ready();
  2612. Client cli(HOST, PORT);
  2613. cli.set_connection_timeout(std::chrono::seconds(5));
  2614. auto res =
  2615. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2616. "application/json", [](uint64_t, uint64_t) { return false; });
  2617. ASSERT_TRUE(!res);
  2618. EXPECT_EQ(Error::Canceled, res.error());
  2619. }
  2620. TEST(CancelTest, WithCancelLargePayloadPut) {
  2621. Server svr;
  2622. svr.set_payload_max_length(200 * 1024 * 1024);
  2623. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2624. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  2635. cli.set_connection_timeout(std::chrono::seconds(5));
  2636. auto res =
  2637. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2638. "application/json", [](uint64_t, uint64_t) { return false; });
  2639. ASSERT_TRUE(!res);
  2640. EXPECT_EQ(Error::Canceled, res.error());
  2641. }
  2642. TEST(CancelTest, NoCancelPatch) {
  2643. Server svr;
  2644. svr.Patch("/", [&](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.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2658. "application/json", [](uint64_t, uint64_t) { return true; });
  2659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2660. EXPECT_EQ("Hello World!", res->body);
  2661. EXPECT_EQ(StatusCode::OK_200, res->status);
  2662. }
  2663. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2664. Server svr;
  2665. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2666. res.set_content("Hello World!", "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_connection_timeout(std::chrono::seconds(5));
  2677. auto res =
  2678. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2679. "application/json", [](uint64_t, uint64_t) { return false; });
  2680. ASSERT_TRUE(!res);
  2681. EXPECT_EQ(Error::Canceled, res.error());
  2682. }
  2683. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2684. Server svr;
  2685. svr.set_payload_max_length(200 * 1024 * 1024);
  2686. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2687. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  2698. cli.set_connection_timeout(std::chrono::seconds(5));
  2699. auto res =
  2700. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2701. "application/json", [](uint64_t, uint64_t) { return false; });
  2702. ASSERT_TRUE(!res);
  2703. EXPECT_EQ(Error::Canceled, res.error());
  2704. }
  2705. TEST(CancelTest, NoCancelDelete) {
  2706. Server svr;
  2707. svr.Delete("/", [&](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.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2721. "application/json", [](uint64_t, uint64_t) { return true; });
  2722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2723. EXPECT_EQ("Hello World!", res->body);
  2724. EXPECT_EQ(StatusCode::OK_200, res->status);
  2725. }
  2726. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2727. Server svr;
  2728. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2729. res.set_content("Hello World!", "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_connection_timeout(std::chrono::seconds(5));
  2740. auto res =
  2741. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2742. "application/json", [](uint64_t, uint64_t) { return false; });
  2743. ASSERT_TRUE(!res);
  2744. EXPECT_EQ(Error::Canceled, res.error());
  2745. }
  2746. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2747. Server svr;
  2748. svr.set_payload_max_length(200 * 1024 * 1024);
  2749. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2750. res.set_content(LARGE_DATA, "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_payload_max_length(200 * 1024 * 1024);
  2761. cli.set_connection_timeout(std::chrono::seconds(5));
  2762. auto res =
  2763. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2764. "application/json", [](uint64_t, uint64_t) { return false; });
  2765. ASSERT_TRUE(!res);
  2766. EXPECT_EQ(Error::Canceled, res.error());
  2767. }
  2768. static std::string remove_whitespace(const std::string &input) {
  2769. std::string output;
  2770. output.reserve(input.size());
  2771. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2772. [](unsigned char c) { return !std::isspace(c); });
  2773. return output;
  2774. }
  2775. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2776. auto host = "httpbingo.org";
  2777. auto path = std::string{"/basic-auth/hello/world"};
  2778. #ifdef CPPHTTPLIB_SSL_ENABLED
  2779. auto port = 443;
  2780. SSLClient cli(host, port);
  2781. #else
  2782. auto port = 80;
  2783. Client cli(host, port);
  2784. #endif
  2785. {
  2786. auto res = cli.Get(path);
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2789. }
  2790. {
  2791. auto res = cli.Get(
  2792. path, Headers{make_basic_authentication_header("hello", "world")});
  2793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2794. auto body = remove_whitespace(res->body);
  2795. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2796. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2797. EXPECT_EQ(StatusCode::OK_200, res->status);
  2798. }
  2799. {
  2800. cli.set_basic_auth("hello", "world");
  2801. auto res = cli.Get(path);
  2802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2803. auto body = remove_whitespace(res->body);
  2804. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2805. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2806. EXPECT_EQ(StatusCode::OK_200, res->status);
  2807. }
  2808. {
  2809. cli.set_basic_auth("hello", "bad");
  2810. auto res = cli.Get(path);
  2811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2812. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2813. }
  2814. {
  2815. cli.set_basic_auth("bad", "world");
  2816. auto res = cli.Get(path);
  2817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2818. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2819. }
  2820. }
  2821. #ifdef CPPHTTPLIB_SSL_ENABLED
  2822. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2823. auto host = "httpbingo.org";
  2824. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2825. auto paths = std::vector<std::string>{
  2826. "/digest-auth/auth/hello/world/MD5",
  2827. "/digest-auth/auth/hello/world/SHA-256",
  2828. };
  2829. auto port = 443;
  2830. SSLClient cli(host, port);
  2831. {
  2832. auto res = cli.Get(unauth_path);
  2833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2834. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2835. }
  2836. {
  2837. cli.set_digest_auth("hello", "world");
  2838. for (const auto &path : paths) {
  2839. auto res = cli.Get(path.c_str());
  2840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2841. auto body = remove_whitespace(res->body);
  2842. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2843. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2844. EXPECT_EQ(StatusCode::OK_200, res->status);
  2845. }
  2846. cli.set_digest_auth("hello", "bad");
  2847. for (const auto &path : paths) {
  2848. auto res = cli.Get(path.c_str());
  2849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2850. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2851. }
  2852. }
  2853. }
  2854. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2855. // comma-separated list of challenges, and each challenge may itself carry a
  2856. // comma-separated auth-param list, so a server can legally offer Basic
  2857. // before Digest, either as two field lines or packed into one. Runs one 401
  2858. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2859. // value() joins them in receipt order) and checks that the retry carries a
  2860. // well-formed Digest Authorization header naming expected_realm.
  2861. static void
  2862. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2863. const std::string &expected_realm) {
  2864. std::atomic<int> hits{0};
  2865. Server svr;
  2866. svr.Get("/x", [&](const Request &req, Response &res) {
  2867. if (++hits == 1) {
  2868. res.status = StatusCode::Unauthorized_401;
  2869. for (const auto &challenge : challenges) {
  2870. res.set_header("WWW-Authenticate", challenge);
  2871. }
  2872. } else {
  2873. auto authorization = req.get_header_value("Authorization");
  2874. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2875. EXPECT_NE(std::string::npos,
  2876. authorization.find("realm=\"" + expected_realm + "\""));
  2877. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2878. res.set_content("ok", "text/plain");
  2879. }
  2880. });
  2881. auto port = svr.bind_to_any_port(HOST);
  2882. std::thread t([&]() { svr.listen_after_bind(); });
  2883. auto se = detail::scope_exit([&] {
  2884. svr.stop();
  2885. t.join();
  2886. });
  2887. svr.wait_until_ready();
  2888. Client cli(HOST, port);
  2889. cli.set_digest_auth("hello", "world");
  2890. auto res = cli.Get("/x");
  2891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2892. EXPECT_EQ(2, hits.load());
  2893. }
  2894. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2895. static const char *kDigestChallenge =
  2896. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2897. "algorithm=MD5";
  2898. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2899. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2900. "testrealm");
  2901. }
  2902. // Same challenge list with the schemes in the opposite order, to make sure
  2903. // the fix above didn't just special-case "Basic first".
  2904. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2905. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2906. "testrealm");
  2907. }
  2908. // A comma inside a quoted auth-param value must not be mistaken for the
  2909. // separator between two challenges (or two auth-params).
  2910. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2911. run_digest_challenge_list_test(
  2912. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2913. "algorithm=MD5"},
  2914. "test,realm");
  2915. }
  2916. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2917. // make_digest_authentication_header() dereferences both unconditionally, so
  2918. // a server sending a challenge missing either one must not be treated as
  2919. // usable -- doing so used to crash the client with std::out_of_range.
  2920. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2921. Server svr;
  2922. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2923. res.status = StatusCode::Unauthorized_401;
  2924. res.set_header("WWW-Authenticate", challenge);
  2925. });
  2926. auto port = svr.bind_to_any_port(HOST);
  2927. std::thread t([&]() { svr.listen_after_bind(); });
  2928. auto se = detail::scope_exit([&] {
  2929. svr.stop();
  2930. t.join();
  2931. });
  2932. svr.wait_until_ready();
  2933. Client cli(HOST, port);
  2934. cli.set_digest_auth("hello", "world");
  2935. auto res = cli.Get("/x");
  2936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2937. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2938. }
  2939. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2940. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2941. }
  2942. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2943. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2944. }
  2945. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2946. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2947. }
  2948. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  2949. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  2950. // when storing the values, so the header builder has to re-escape them (and
  2951. // keep algorithm a bare token); otherwise the value breaks out of its
  2952. // quoted-string and injects extra auth-params into the client's Authorization.
  2953. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  2954. std::atomic<int> hits{0};
  2955. std::string authorization;
  2956. Server svr;
  2957. svr.Get("/x", [&](const Request &req, Response &res) {
  2958. if (++hits == 1) {
  2959. res.status = StatusCode::Unauthorized_401;
  2960. // On the wire the quotes embedded in the values are backslash-escaped.
  2961. res.set_header("WWW-Authenticate",
  2962. "Digest realm=\"testrealm\", "
  2963. "nonce=\"n\\\"; injected=\\\"x\", "
  2964. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  2965. } else {
  2966. authorization = req.get_header_value("Authorization");
  2967. res.set_content("ok", "text/plain");
  2968. }
  2969. });
  2970. auto port = svr.bind_to_any_port(HOST);
  2971. std::thread t([&]() { svr.listen_after_bind(); });
  2972. auto se = detail::scope_exit([&] {
  2973. svr.stop();
  2974. t.join();
  2975. });
  2976. svr.wait_until_ready();
  2977. Client cli(HOST, port);
  2978. cli.set_digest_auth("hello", "world");
  2979. auto res = cli.Get("/x");
  2980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2981. EXPECT_EQ(2, hits.load());
  2982. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2983. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  2984. // inside its quoted-string rather than starting an "injected" auth-param.
  2985. EXPECT_NE(std::string::npos,
  2986. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  2987. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  2988. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  2989. }
  2990. #endif
  2991. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2992. auto host = "google.com";
  2993. auto another_host = "example.com";
  2994. auto wrong_ip = "0.0.0.0";
  2995. #ifdef CPPHTTPLIB_SSL_ENABLED
  2996. SSLClient cli(host);
  2997. #else
  2998. Client cli(host);
  2999. #endif
  3000. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3001. auto res = cli.Get("/");
  3002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3003. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3004. }
  3005. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3006. auto host = "google.com";
  3007. auto wrong_ip = "0.0.0.0";
  3008. #ifdef CPPHTTPLIB_SSL_ENABLED
  3009. SSLClient cli(host);
  3010. #else
  3011. Client cli(host);
  3012. #endif
  3013. cli.set_hostname_addr_map({{host, wrong_ip}});
  3014. auto res = cli.Get("/");
  3015. ASSERT_TRUE(!res);
  3016. EXPECT_EQ(Error::Connection, res.error());
  3017. }
  3018. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3019. // A mapped value that is not an IP literal must be resolved. "localhost"
  3020. // resolves from the hosts file, so this test needs no external DNS.
  3021. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3022. auto host = "target.invalid";
  3023. Server svr;
  3024. std::string received_host;
  3025. svr.Get("/hi", [&](const Request &req, Response &res) {
  3026. received_host = req.get_header_value("Host");
  3027. res.set_content("Hello World!", "text/plain");
  3028. });
  3029. auto port = svr.bind_to_any_port(HOST);
  3030. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3031. auto se = detail::scope_exit([&] {
  3032. svr.stop();
  3033. thread.join();
  3034. ASSERT_FALSE(svr.is_running());
  3035. });
  3036. svr.wait_until_ready();
  3037. Client cli(host, port);
  3038. cli.set_hostname_addr_map({{host, HOST}});
  3039. auto res = cli.Get("/hi");
  3040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3041. EXPECT_EQ(StatusCode::OK_200, res->status);
  3042. // The mapping only redirects the connection; the identity stays host_.
  3043. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3044. }
  3045. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3046. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3047. auto host = "target.invalid";
  3048. Server svr;
  3049. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3050. res.set_content("Hello World!", "text/plain");
  3051. });
  3052. auto port = svr.bind_to_any_port("127.0.0.1");
  3053. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3054. auto se = detail::scope_exit([&] {
  3055. svr.stop();
  3056. thread.join();
  3057. ASSERT_FALSE(svr.is_running());
  3058. });
  3059. svr.wait_until_ready();
  3060. Client cli(host, port);
  3061. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3062. auto res = cli.Get("/hi");
  3063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3064. EXPECT_EQ(StatusCode::OK_200, res->status);
  3065. }
  3066. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3067. // An empty mapped value must leave host_ as the connection target. Without
  3068. // that guard the empty value would become the host argument, getaddrinfo
  3069. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3070. // loopback - silently connecting somewhere the caller never asked for.
  3071. // The server listens on loopback, so such a fallback would succeed and is
  3072. // therefore observable as a failure of this test.
  3073. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3074. Server svr;
  3075. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3076. res.set_content("Hello World!", "text/plain");
  3077. });
  3078. auto port = svr.bind_to_any_port(HOST);
  3079. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3080. auto se = detail::scope_exit([&] {
  3081. svr.stop();
  3082. thread.join();
  3083. ASSERT_FALSE(svr.is_running());
  3084. });
  3085. svr.wait_until_ready();
  3086. Client cli(blackhole, port);
  3087. cli.set_hostname_addr_map({{blackhole, ""}});
  3088. cli.set_connection_timeout(1);
  3089. auto res = cli.Get("/hi");
  3090. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3091. }
  3092. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3093. auto host = "httpbingo.org";
  3094. auto path = std::string{"/absolute-redirect/3"};
  3095. #ifdef CPPHTTPLIB_SSL_ENABLED
  3096. SSLClient cli(host);
  3097. #else
  3098. Client cli(host);
  3099. #endif
  3100. cli.set_follow_location(true);
  3101. auto res = cli.Get(path);
  3102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3103. EXPECT_EQ(StatusCode::OK_200, res->status);
  3104. }
  3105. TEST(RedirectTest, Redirect_Online) {
  3106. auto host = "httpbingo.org";
  3107. auto path = std::string{"/redirect/3"};
  3108. #ifdef CPPHTTPLIB_SSL_ENABLED
  3109. SSLClient cli(host);
  3110. #else
  3111. Client cli(host);
  3112. #endif
  3113. cli.set_follow_location(true);
  3114. auto res = cli.Get(path);
  3115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3116. EXPECT_EQ(StatusCode::OK_200, res->status);
  3117. }
  3118. TEST(RelativeRedirectTest, Redirect_Online) {
  3119. auto host = "httpbingo.org";
  3120. auto path = std::string{"/relative-redirect/3"};
  3121. #ifdef CPPHTTPLIB_SSL_ENABLED
  3122. SSLClient cli(host);
  3123. #else
  3124. Client cli(host);
  3125. #endif
  3126. cli.set_follow_location(true);
  3127. auto res = cli.Get(path);
  3128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3129. EXPECT_EQ(StatusCode::OK_200, res->status);
  3130. }
  3131. TEST(TooManyRedirectTest, Redirect_Online) {
  3132. auto host = "httpbingo.org";
  3133. auto path = std::string{"/redirect/21"};
  3134. #ifdef CPPHTTPLIB_SSL_ENABLED
  3135. SSLClient cli(host);
  3136. #else
  3137. Client cli(host);
  3138. #endif
  3139. cli.set_follow_location(true);
  3140. auto res = cli.Get(path);
  3141. ASSERT_TRUE(!res);
  3142. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3143. }
  3144. #ifdef CPPHTTPLIB_SSL_ENABLED
  3145. TEST(YahooRedirectTest, Redirect_Online) {
  3146. Client cli("yahoo.com");
  3147. auto res = cli.Get("/");
  3148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3149. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3150. cli.set_follow_location(true);
  3151. res = cli.Get("/");
  3152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3153. EXPECT_EQ(StatusCode::OK_200, res->status);
  3154. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3155. }
  3156. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3157. #define REDIR_HOST "httpbingo.org"
  3158. #define REDIR_PATH "/redirect-to"
  3159. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3160. SSLClient cli(REDIR_HOST);
  3161. cli.set_follow_location(true);
  3162. auto res =
  3163. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3165. EXPECT_EQ(StatusCode::OK_200, res->status);
  3166. }
  3167. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3168. SSLClient cli(REDIR_HOST);
  3169. cli.set_follow_location(true);
  3170. Params params;
  3171. params.emplace("url", "http://example.com");
  3172. params.emplace("status_code", "302");
  3173. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3175. EXPECT_EQ(StatusCode::OK_200, res->status);
  3176. }
  3177. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3178. SSLClient cli(REDIR_HOST);
  3179. cli.set_follow_location(true);
  3180. Params params;
  3181. params.emplace("url", "http://example.com");
  3182. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3184. EXPECT_EQ(StatusCode::OK_200, res->status);
  3185. }
  3186. TEST(UrlWithSpace, Redirect_Online) {
  3187. SSLClient cli("edge.forgecdn.net");
  3188. cli.set_follow_location(true);
  3189. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3191. EXPECT_EQ(StatusCode::OK_200, res->status);
  3192. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3193. }
  3194. #endif
  3195. #if !defined(_WIN32) && !defined(_WIN64)
  3196. TEST(ReceiveSignals, Signal) {
  3197. auto setupSignalHandlers = []() {
  3198. struct sigaction act;
  3199. sigemptyset(&act.sa_mask);
  3200. act.sa_flags = SA_SIGINFO;
  3201. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3202. switch (sig) {
  3203. case SIGINT:
  3204. default: break;
  3205. }
  3206. };
  3207. ::sigaction(SIGINT, &act, nullptr);
  3208. };
  3209. Server svr;
  3210. int port = 0;
  3211. auto thread = std::thread([&]() {
  3212. setupSignalHandlers();
  3213. port = svr.bind_to_any_port(HOST);
  3214. svr.listen_after_bind();
  3215. });
  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. ASSERT_TRUE(svr.is_running());
  3223. pthread_kill(thread.native_handle(), SIGINT);
  3224. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3225. ASSERT_TRUE(svr.is_running());
  3226. }
  3227. #endif
  3228. TEST(RedirectToDifferentPort, Redirect) {
  3229. Server svr1;
  3230. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3231. res.set_content("Hello World!", "text/plain");
  3232. });
  3233. int svr1_port = 0;
  3234. auto thread1 = std::thread([&]() {
  3235. svr1_port = svr1.bind_to_any_port(HOST);
  3236. svr1.listen_after_bind();
  3237. });
  3238. Server svr2;
  3239. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3240. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3241. });
  3242. int svr2_port = 0;
  3243. auto thread2 = std::thread([&]() {
  3244. svr2_port = svr2.bind_to_any_port(HOST);
  3245. svr2.listen_after_bind();
  3246. });
  3247. auto se = detail::scope_exit([&] {
  3248. svr2.stop();
  3249. thread2.join();
  3250. svr1.stop();
  3251. thread1.join();
  3252. ASSERT_FALSE(svr2.is_running());
  3253. ASSERT_FALSE(svr1.is_running());
  3254. });
  3255. svr1.wait_until_ready();
  3256. svr2.wait_until_ready();
  3257. Client cli("localhost", svr2_port);
  3258. cli.set_follow_location(true);
  3259. auto res = cli.Get("/2");
  3260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3261. EXPECT_EQ(StatusCode::OK_200, res->status);
  3262. EXPECT_EQ("Hello World!", res->body);
  3263. }
  3264. // GET /redir on one server redirects to /target on another port, so the
  3265. // client follows it with a new client.
  3266. static Result
  3267. GetThroughRedirectToDifferentPort(Server::Handler target,
  3268. const std::function<void(Client &)> &setup,
  3269. const Headers &headers = Headers()) {
  3270. Server target_svr;
  3271. target_svr.Get("/target", target);
  3272. int target_port = 0;
  3273. auto target_thread = std::thread([&]() {
  3274. target_port = target_svr.bind_to_any_port(HOST);
  3275. target_svr.listen_after_bind();
  3276. });
  3277. Server origin_svr;
  3278. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3279. res.set_redirect(
  3280. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3281. });
  3282. int origin_port = 0;
  3283. auto origin_thread = std::thread([&]() {
  3284. origin_port = origin_svr.bind_to_any_port(HOST);
  3285. origin_svr.listen_after_bind();
  3286. });
  3287. auto se = detail::scope_exit([&] {
  3288. origin_svr.stop();
  3289. origin_thread.join();
  3290. target_svr.stop();
  3291. target_thread.join();
  3292. });
  3293. target_svr.wait_until_ready();
  3294. origin_svr.wait_until_ready();
  3295. Client cli("localhost", origin_port);
  3296. cli.set_follow_location(true);
  3297. setup(cli);
  3298. return cli.Get("/redir", headers);
  3299. }
  3300. static void
  3301. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3302. std::string captured_authorization;
  3303. auto result = GetThroughRedirectToDifferentPort(
  3304. [&](const Request &req, Response &res) {
  3305. captured_authorization = req.get_header_value("Authorization");
  3306. res.set_content("OK", "text/plain");
  3307. },
  3308. set_auth);
  3309. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3310. EXPECT_EQ(StatusCode::OK_200, result->status);
  3311. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3312. EXPECT_TRUE(captured_authorization.empty());
  3313. }
  3314. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3315. TestDoNotForwardCredentialsOnRedirect(
  3316. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3317. }
  3318. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3319. TestDoNotForwardCredentialsOnRedirect(
  3320. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3321. }
  3322. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3323. std::string captured_cookie;
  3324. auto result = GetThroughRedirectToDifferentPort(
  3325. [&](const Request &req, Response &res) {
  3326. captured_cookie = req.get_header_value("Cookie");
  3327. res.set_content("OK", "text/plain");
  3328. },
  3329. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3330. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3331. EXPECT_EQ(StatusCode::OK_200, result->status);
  3332. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3333. EXPECT_TRUE(captured_cookie.empty());
  3334. }
  3335. TEST(RedirectToSamePort, ForwardCookie) {
  3336. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3337. // header so that ordinary session flows keep working.
  3338. Server svr;
  3339. std::string captured_cookie;
  3340. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3341. res.set_redirect("/target", 302);
  3342. });
  3343. svr.Get("/target", [&](const Request &req, Response &res) {
  3344. captured_cookie = req.get_header_value("Cookie");
  3345. res.set_content("OK", "text/plain");
  3346. });
  3347. auto port = svr.bind_to_any_port(HOST);
  3348. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3349. auto se = detail::scope_exit([&] {
  3350. svr.stop();
  3351. thread.join();
  3352. ASSERT_FALSE(svr.is_running());
  3353. });
  3354. svr.wait_until_ready();
  3355. Client cli(HOST, port);
  3356. cli.set_follow_location(true);
  3357. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3358. auto res = cli.Get("/redir", headers);
  3359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3360. EXPECT_EQ(StatusCode::OK_200, res->status);
  3361. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3362. }
  3363. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3364. std::string authorization;
  3365. std::string trace_id;
  3366. auto result = GetThroughRedirectToDifferentPort(
  3367. [&](const Request &req, Response &res) {
  3368. authorization = req.get_header_value("Authorization");
  3369. trace_id = req.get_header_value("X-Trace-Id");
  3370. res.set_content("OK", "text/plain");
  3371. },
  3372. [](Client &cli) {
  3373. cli.set_default_headers(
  3374. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3375. });
  3376. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3377. EXPECT_EQ(StatusCode::OK_200, result->status);
  3378. // Like a header given with the request, a default one goes along unless it
  3379. // carries credentials (RFC 9110 15.4).
  3380. EXPECT_TRUE(authorization.empty());
  3381. EXPECT_EQ("42", trace_id);
  3382. }
  3383. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3384. auto result = GetThroughRedirectToDifferentPort(
  3385. [](const Request &, Response &res) {
  3386. res.set_content(std::string(2048, 'x'), "text/plain");
  3387. },
  3388. [](Client &cli) { cli.set_payload_max_length(1024); });
  3389. EXPECT_FALSE(result);
  3390. }
  3391. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3392. auto result = GetThroughRedirectToDifferentPort(
  3393. [](const Request &req, Response &res) {
  3394. // Answer after a second, or once the client gives up.
  3395. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3396. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3397. }
  3398. res.set_content("late", "text/plain");
  3399. },
  3400. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3401. ASSERT_FALSE(result);
  3402. EXPECT_EQ(Error::Read, result.error());
  3403. }
  3404. #ifdef CPPHTTPLIB_SSL_ENABLED
  3405. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3406. auto result = GetThroughRedirectToDifferentPort(
  3407. [](const Request &, Response &res) {
  3408. res.status = StatusCode::Unauthorized_401;
  3409. res.set_header("WWW-Authenticate",
  3410. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3411. },
  3412. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3413. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3414. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3415. }
  3416. #endif
  3417. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3418. Server svr;
  3419. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3420. // Port number that overflows int — should not crash
  3421. res.set_redirect("http://localhost:99999999999999999999/target");
  3422. });
  3423. auto port = svr.bind_to_any_port(HOST);
  3424. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3425. auto se = detail::scope_exit([&] {
  3426. svr.stop();
  3427. thread.join();
  3428. ASSERT_FALSE(svr.is_running());
  3429. });
  3430. svr.wait_until_ready();
  3431. Client cli(HOST, port);
  3432. cli.set_follow_location(true);
  3433. auto res = cli.Get("/redir");
  3434. // Should fail gracefully, not crash (no valid response due to bad port)
  3435. EXPECT_FALSE(res);
  3436. }
  3437. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3438. Server svr;
  3439. auto port = svr.bind_to_any_port(HOST);
  3440. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3441. // The server's own port followed by junk must not be followed
  3442. res.set_redirect("http://" + std::string(HOST) + ":" +
  3443. std::to_string(port) + "junk/target");
  3444. });
  3445. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3446. res.set_content("target", "text/plain");
  3447. });
  3448. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3449. auto se = detail::scope_exit([&] {
  3450. svr.stop();
  3451. thread.join();
  3452. ASSERT_FALSE(svr.is_running());
  3453. });
  3454. svr.wait_until_ready();
  3455. Client cli(HOST, port);
  3456. cli.set_follow_location(true);
  3457. auto res = cli.Get("/redir");
  3458. EXPECT_FALSE(res);
  3459. }
  3460. TEST(RedirectFromPageWithContent, Redirect) {
  3461. Server svr;
  3462. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3463. res.set_content("___", "text/plain");
  3464. res.set_redirect("/2");
  3465. });
  3466. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3467. res.set_content("Hello World!", "text/plain");
  3468. });
  3469. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3470. auto se = detail::scope_exit([&] {
  3471. svr.stop();
  3472. th.join();
  3473. ASSERT_FALSE(svr.is_running());
  3474. });
  3475. svr.wait_until_ready();
  3476. {
  3477. Client cli("localhost", PORT);
  3478. cli.set_follow_location(true);
  3479. std::string body;
  3480. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3481. body.append(data, data_length);
  3482. return true;
  3483. });
  3484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3485. EXPECT_EQ(StatusCode::OK_200, res->status);
  3486. EXPECT_EQ("Hello World!", body);
  3487. }
  3488. {
  3489. Client cli("localhost", PORT);
  3490. std::string body;
  3491. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3492. body.append(data, data_length);
  3493. return true;
  3494. });
  3495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3496. EXPECT_EQ(StatusCode::Found_302, res->status);
  3497. EXPECT_EQ("___", body);
  3498. }
  3499. }
  3500. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3501. Server svr;
  3502. auto port_str = std::to_string(PORT);
  3503. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3504. auto expected_host = "[::1]:" + port_str;
  3505. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3506. res.set_content("___", "text/plain");
  3507. // res.set_redirect("/2");
  3508. res.set_redirect(redirect_url);
  3509. });
  3510. svr.Get("/2", [&](const Request &req, Response &res) {
  3511. auto host_header = req.headers.find("Host");
  3512. ASSERT_TRUE(host_header != req.headers.end());
  3513. EXPECT_EQ(expected_host, host_header->second);
  3514. res.set_content("Hello World!", "text/plain");
  3515. });
  3516. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3517. auto se = detail::scope_exit([&] {
  3518. svr.stop();
  3519. th.join();
  3520. ASSERT_FALSE(svr.is_running());
  3521. });
  3522. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3523. // actually starts anything, so the condition !svr.is_running() will
  3524. // always remain true, and the loop never stops.
  3525. // This basically counts how many milliseconds have passed since the
  3526. // call to svr.listen(), and if after 5 seconds nothing started yet
  3527. // aborts the test.
  3528. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3529. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3530. ASSERT_LT(milliseconds, 5000U);
  3531. }
  3532. {
  3533. Client cli("::1", PORT);
  3534. cli.set_follow_location(true);
  3535. std::string body;
  3536. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3537. body.append(data, data_length);
  3538. return true;
  3539. });
  3540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3541. EXPECT_EQ(StatusCode::OK_200, res->status);
  3542. EXPECT_EQ("Hello World!", body);
  3543. }
  3544. {
  3545. Client cli("::1", PORT);
  3546. std::string body;
  3547. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3548. body.append(data, data_length);
  3549. return true;
  3550. });
  3551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3552. EXPECT_EQ(StatusCode::Found_302, res->status);
  3553. EXPECT_EQ("___", body);
  3554. }
  3555. }
  3556. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3557. Server svr;
  3558. svr.Get("/foo", [](const Request &req, Response &res) {
  3559. auto a = req.params.find("a");
  3560. if (a != req.params.end()) {
  3561. res.set_content((*a).second, "text/plain");
  3562. res.status = StatusCode::OK_200;
  3563. } else {
  3564. res.status = StatusCode::BadRequest_400;
  3565. }
  3566. });
  3567. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3568. auto se = detail::scope_exit([&] {
  3569. svr.stop();
  3570. thread.join();
  3571. ASSERT_FALSE(svr.is_running());
  3572. });
  3573. svr.wait_until_ready();
  3574. {
  3575. Client cli(HOST, PORT);
  3576. cli.set_path_encode(false);
  3577. auto res = cli.Get("/foo?a=explicitly+encoded");
  3578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3579. EXPECT_EQ(StatusCode::OK_200, res->status);
  3580. // This expects it back with a space, as the `+` won't have been
  3581. // url-encoded, and server-side the params get decoded turning `+`
  3582. // into spaces.
  3583. EXPECT_EQ("explicitly encoded", res->body);
  3584. }
  3585. }
  3586. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3587. // When path encoding is disabled the client must transmit the supplied
  3588. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3589. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3590. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3591. // than a space (0x20). Assert on the raw wire target to catch this.
  3592. Server svr;
  3593. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3594. svr.Get("/foo", [&](const Request &req, Response &res) {
  3595. EXPECT_EQ(expected_target, req.target);
  3596. res.status = StatusCode::OK_200;
  3597. });
  3598. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3599. auto se = detail::scope_exit([&] {
  3600. svr.stop();
  3601. thread.join();
  3602. ASSERT_FALSE(svr.is_running());
  3603. });
  3604. svr.wait_until_ready();
  3605. {
  3606. Client cli(HOST, PORT);
  3607. cli.set_path_encode(false);
  3608. auto res = cli.Get(expected_target.c_str());
  3609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3610. EXPECT_EQ(StatusCode::OK_200, res->status);
  3611. }
  3612. }
  3613. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3614. // `open_stream()` used to skip the path encoding that the buffered send
  3615. // path applies, so the same `path` produced different bytes in the request
  3616. // line depending on which API was used. Assert the two agree.
  3617. Server svr;
  3618. std::string target;
  3619. svr.Get(".*", [&](const Request &req, Response &res) {
  3620. target = req.target;
  3621. res.status = StatusCode::OK_200;
  3622. });
  3623. auto port = svr.bind_to_any_port(HOST);
  3624. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3625. auto se = detail::scope_exit([&] {
  3626. svr.stop();
  3627. thread.join();
  3628. ASSERT_FALSE(svr.is_running());
  3629. });
  3630. svr.wait_until_ready();
  3631. struct {
  3632. const char *path;
  3633. const char *expected;
  3634. } cases[] = {
  3635. {"/a b?x=1", "/a%20b?x=1"},
  3636. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3637. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3638. };
  3639. for (const auto &c : cases) {
  3640. Client cli(HOST, port);
  3641. target.clear();
  3642. auto res = cli.Get(c.path);
  3643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3644. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3645. auto buffered_target = target;
  3646. target.clear();
  3647. auto handle = cli.open_stream("GET", c.path);
  3648. EXPECT_TRUE(handle.is_valid())
  3649. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3650. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3651. }
  3652. }
  3653. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3654. // The `set_path_encode(false)` contract — transmit the supplied target
  3655. // verbatim — must hold for the streaming API too.
  3656. Server svr;
  3657. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3658. std::string target;
  3659. svr.Get("/foo", [&](const Request &req, Response &res) {
  3660. target = req.target;
  3661. res.status = StatusCode::OK_200;
  3662. });
  3663. auto port = svr.bind_to_any_port(HOST);
  3664. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3665. auto se = detail::scope_exit([&] {
  3666. svr.stop();
  3667. thread.join();
  3668. ASSERT_FALSE(svr.is_running());
  3669. });
  3670. svr.wait_until_ready();
  3671. {
  3672. Client cli(HOST, port);
  3673. cli.set_path_encode(false);
  3674. auto handle = cli.open_stream("GET", expected_target);
  3675. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3676. EXPECT_EQ(expected_target, target);
  3677. }
  3678. }
  3679. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3680. // With path encoding enabled a CR/LF in the target is percent-encoded
  3681. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3682. // write_request_line still backstops `set_path_encode(false)`, which is
  3683. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3684. Server svr;
  3685. // Captured before routing: the decoded path contains a newline, which a
  3686. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3687. std::string target;
  3688. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3689. target = req.target;
  3690. res.status = StatusCode::OK_200;
  3691. return Server::HandlerResponse::Handled;
  3692. });
  3693. auto port = svr.bind_to_any_port(HOST);
  3694. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3695. auto se = detail::scope_exit([&] {
  3696. svr.stop();
  3697. thread.join();
  3698. ASSERT_FALSE(svr.is_running());
  3699. });
  3700. svr.wait_until_ready();
  3701. {
  3702. Client cli(HOST, port);
  3703. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3704. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3705. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3706. }
  3707. }
  3708. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3709. // Every control character is percent-encoded, not just CR/LF, so the target
  3710. // passes the request-target check in write_request_line.
  3711. Server svr;
  3712. std::string target;
  3713. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3714. target = req.target;
  3715. res.status = StatusCode::OK_200;
  3716. return Server::HandlerResponse::Handled;
  3717. });
  3718. auto port = svr.bind_to_any_port(HOST);
  3719. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3720. auto se = detail::scope_exit([&] {
  3721. svr.stop();
  3722. thread.join();
  3723. ASSERT_FALSE(svr.is_running());
  3724. });
  3725. svr.wait_until_ready();
  3726. {
  3727. Client cli(HOST, port);
  3728. auto res = cli.Get("/a\tb\x1b\x7f");
  3729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3730. EXPECT_EQ("/a%09b%1B%7F", target);
  3731. }
  3732. }
  3733. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3734. // Nothing may reach the wire: a raw CR/LF target would split the request
  3735. // line and inject headers.
  3736. Server svr;
  3737. // Pre-routing so that "not called" means nothing reached the server at all,
  3738. // rather than merely failing to match a handler pattern.
  3739. auto handler_called = false;
  3740. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3741. handler_called = true;
  3742. res.status = StatusCode::OK_200;
  3743. return Server::HandlerResponse::Handled;
  3744. });
  3745. auto port = svr.bind_to_any_port(HOST);
  3746. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3747. auto se = detail::scope_exit([&] {
  3748. svr.stop();
  3749. thread.join();
  3750. ASSERT_FALSE(svr.is_running());
  3751. });
  3752. svr.wait_until_ready();
  3753. {
  3754. Client cli(HOST, port);
  3755. cli.set_path_encode(false);
  3756. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3757. EXPECT_FALSE(handle.is_valid());
  3758. EXPECT_EQ(Error::Write, handle.error);
  3759. EXPECT_FALSE(handler_called);
  3760. }
  3761. }
  3762. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3763. // Which of the two branches runs is decided by whether the query component
  3764. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3765. // an empty query and must still fall back to building one from
  3766. // `req.params`, while a non-empty query must win over `req.params`.
  3767. Server svr;
  3768. std::string target;
  3769. svr.Get("/foo", [&](const Request &req, Response &res) {
  3770. target = req.target;
  3771. res.status = StatusCode::OK_200;
  3772. });
  3773. auto port = svr.bind_to_any_port(HOST);
  3774. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3775. auto se = detail::scope_exit([&] {
  3776. svr.stop();
  3777. thread.join();
  3778. ASSERT_FALSE(svr.is_running());
  3779. });
  3780. svr.wait_until_ready();
  3781. {
  3782. // Trailing `?` -> empty query component -> `req.params` is used.
  3783. Client cli(HOST, port);
  3784. Request req;
  3785. req.method = "GET";
  3786. req.path = "/foo?";
  3787. req.params.emplace("a", "1");
  3788. target.clear();
  3789. auto res = cli.send(req);
  3790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3791. EXPECT_EQ("/foo?a=1", target);
  3792. }
  3793. {
  3794. // Non-empty query in `req.path` -> `req.params` is not appended.
  3795. Client cli(HOST, port);
  3796. Request req;
  3797. req.method = "GET";
  3798. req.path = "/foo?b=2";
  3799. req.params.emplace("a", "1");
  3800. target.clear();
  3801. auto res = cli.send(req);
  3802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3803. EXPECT_EQ("/foo?b=2", target);
  3804. }
  3805. }
  3806. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3807. Server svr;
  3808. svr.Get("/", [](const Request &req, Response &) {
  3809. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3810. });
  3811. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3812. auto se = detail::scope_exit([&] {
  3813. svr.stop();
  3814. thread.join();
  3815. ASSERT_FALSE(svr.is_running());
  3816. });
  3817. svr.wait_until_ready();
  3818. {
  3819. Client cli(HOST, PORT);
  3820. cli.set_path_encode(false);
  3821. auto res = cli.Get("/?something=%0A");
  3822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3823. EXPECT_EQ(StatusCode::OK_200, res->status);
  3824. }
  3825. }
  3826. TEST(BindServerTest, BindDualStack) {
  3827. Server svr;
  3828. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3829. res.set_content("Hello World!", "text/plain");
  3830. });
  3831. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3832. auto se = detail::scope_exit([&] {
  3833. svr.stop();
  3834. thread.join();
  3835. ASSERT_FALSE(svr.is_running());
  3836. });
  3837. svr.wait_until_ready();
  3838. {
  3839. Client cli("127.0.0.1", PORT);
  3840. auto res = cli.Get("/1");
  3841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3842. EXPECT_EQ(StatusCode::OK_200, res->status);
  3843. EXPECT_EQ("Hello World!", res->body);
  3844. }
  3845. {
  3846. Client cli("::1", PORT);
  3847. auto res = cli.Get("/1");
  3848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3849. EXPECT_EQ(StatusCode::OK_200, res->status);
  3850. EXPECT_EQ("Hello World!", res->body);
  3851. }
  3852. }
  3853. TEST(BindServerTest, BindAndListenSeparately) {
  3854. Server svr;
  3855. int port = svr.bind_to_any_port("0.0.0.0");
  3856. ASSERT_TRUE(svr.is_valid());
  3857. ASSERT_TRUE(port > 0);
  3858. svr.stop();
  3859. }
  3860. // Reports whether anything is still listening on a loopback port. A plain
  3861. // connect() is used instead of a Client request because a socket left bound by
  3862. // mistake accepts the connection into its backlog and never answers, which
  3863. // would hang the test instead of failing it.
  3864. static bool is_loopback_port_accepting(int port) {
  3865. sockaddr_in addr{};
  3866. addr.sin_family = AF_INET;
  3867. addr.sin_port = htons(static_cast<uint16_t>(port));
  3868. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3869. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3870. EXPECT_NE(sock, INVALID_SOCKET);
  3871. if (sock == INVALID_SOCKET) { return false; }
  3872. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3873. static_cast<socklen_t>(sizeof(addr)));
  3874. detail::close_socket(sock);
  3875. return ret == 0;
  3876. }
  3877. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3878. Server svr;
  3879. auto port = svr.bind_to_any_port("127.0.0.1");
  3880. ASSERT_TRUE(port > 0);
  3881. svr.stop();
  3882. // bind_to_any_port() already called listen(2), so until stop() closed the
  3883. // descriptor the port kept accepting connections into the backlog. ASSERT
  3884. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3885. // below blocks forever in the accept loop.
  3886. ASSERT_FALSE(is_loopback_port_accepting(port));
  3887. // Nothing is left to accept on, so listen_after_bind() must report failure
  3888. // instead of returning success without ever serving.
  3889. EXPECT_FALSE(svr.listen_after_bind());
  3890. // The failed listen marks the server decommissioned, so a waiter returns
  3891. // instead of spinning forever.
  3892. svr.wait_until_ready();
  3893. }
  3894. #ifdef CPPHTTPLIB_SSL_ENABLED
  3895. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3896. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3897. CLIENT_CA_CERT_DIR);
  3898. int port = svr.bind_to_any_port("0.0.0.0");
  3899. ASSERT_TRUE(svr.is_valid());
  3900. ASSERT_TRUE(port > 0);
  3901. svr.stop();
  3902. }
  3903. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3904. // or a rejected CustomRoute() registration would not stop the server binding.
  3905. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3906. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3907. CLIENT_CA_CERT_DIR);
  3908. ASSERT_TRUE(svr.is_valid());
  3909. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3910. EXPECT_FALSE(svr.is_valid());
  3911. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3912. }
  3913. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3914. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3915. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3916. int port = svr.bind_to_any_port("0.0.0.0");
  3917. ASSERT_TRUE(svr.is_valid());
  3918. ASSERT_TRUE(port > 0);
  3919. svr.stop();
  3920. }
  3921. TEST(BindServerTest, UpdateCertsPem) {
  3922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3923. int port = svr.bind_to_any_port("0.0.0.0");
  3924. ASSERT_TRUE(svr.is_valid());
  3925. ASSERT_TRUE(port > 0);
  3926. // Read PEM files
  3927. std::string cert_pem, key_pem, ca_pem;
  3928. read_file(SERVER_CERT_FILE, cert_pem);
  3929. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3930. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3931. // Update server certificates using PEM API
  3932. ASSERT_TRUE(
  3933. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3934. ASSERT_TRUE(svr.is_valid());
  3935. svr.stop();
  3936. }
  3937. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3938. // Start server with client CA (enables client auth)
  3939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3940. ASSERT_TRUE(svr.is_valid());
  3941. bool handler_called = false;
  3942. svr.Get("/test", [&](const Request &req, Response &res) {
  3943. handler_called = true;
  3944. // Verify client certificate is present
  3945. auto cert = req.peer_cert();
  3946. EXPECT_TRUE(static_cast<bool>(cert));
  3947. res.set_content("ok", "text/plain");
  3948. });
  3949. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3950. auto se = detail::scope_exit([&] {
  3951. svr.stop();
  3952. t.join();
  3953. ASSERT_FALSE(svr.is_running());
  3954. });
  3955. svr.wait_until_ready();
  3956. // Read PEM files
  3957. std::string cert_pem, key_pem, ca_pem;
  3958. read_file(SERVER_CERT_FILE, cert_pem);
  3959. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3960. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3961. // Update server certificates and client CA using PEM API while server running
  3962. ASSERT_TRUE(
  3963. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3964. // Connect with client certificate
  3965. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3966. cli.enable_server_certificate_verification(false);
  3967. cli.set_connection_timeout(30);
  3968. auto res = cli.Get("/test");
  3969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3970. ASSERT_EQ(StatusCode::OK_200, res->status);
  3971. ASSERT_TRUE(handler_called);
  3972. EXPECT_EQ("ok", res->body);
  3973. }
  3974. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  3975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3976. ASSERT_TRUE(svr.is_valid());
  3977. svr.Get("/test", [](const Request &, Response &res) {
  3978. res.set_content("ok", "text/plain");
  3979. });
  3980. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3981. auto se = detail::scope_exit([&] {
  3982. svr.stop();
  3983. t.join();
  3984. ASSERT_FALSE(svr.is_running());
  3985. });
  3986. svr.wait_until_ready();
  3987. // A connection that sends no ClientHello keeps its handshake in progress,
  3988. // once the server has had a moment to start it.
  3989. auto error = Error::Success;
  3990. auto sock = detail::create_client_socket(
  3991. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  3992. /*connection_timeout_sec=*/5, 0,
  3993. /*read_timeout_sec=*/5, 0,
  3994. /*write_timeout_sec=*/5, 0, std::string(), error);
  3995. ASSERT_NE(INVALID_SOCKET, sock);
  3996. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  3997. std::string cert_pem, key_pem;
  3998. read_file(SERVER_CERT_FILE, cert_pem);
  3999. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4000. auto update = std::async(std::launch::async, [&]() {
  4001. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4002. });
  4003. EXPECT_EQ(std::future_status::timeout,
  4004. update.wait_for(std::chrono::milliseconds(200)));
  4005. detail::close_socket(sock);
  4006. EXPECT_TRUE(update.get());
  4007. SSLClient cli(HOST, PORT);
  4008. cli.enable_server_certificate_verification(false);
  4009. auto res = cli.Get("/test");
  4010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4011. EXPECT_EQ(StatusCode::OK_200, res->status);
  4012. }
  4013. #endif
  4014. TEST(ErrorHandlerTest, ContentLength) {
  4015. Server svr;
  4016. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4017. res.status = StatusCode::OK_200;
  4018. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4019. "text/html"); // <= Content-Length still 13
  4020. });
  4021. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4022. res.set_content("Hello World!\n", "text/plain");
  4023. res.status = 524;
  4024. });
  4025. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4026. auto se = detail::scope_exit([&] {
  4027. svr.stop();
  4028. thread.join();
  4029. ASSERT_FALSE(svr.is_running());
  4030. });
  4031. svr.wait_until_ready();
  4032. {
  4033. Client cli(HOST, PORT);
  4034. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4036. EXPECT_EQ(StatusCode::OK_200, res->status);
  4037. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4038. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4039. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4040. }
  4041. }
  4042. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4043. TEST(ExceptionTest, WithoutExceptionHandler) {
  4044. Server svr;
  4045. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4046. throw std::runtime_error("exception...");
  4047. });
  4048. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4049. throw std::runtime_error("exception\r\n...");
  4050. });
  4051. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4052. auto se = detail::scope_exit([&] {
  4053. svr.stop();
  4054. listen_thread.join();
  4055. ASSERT_FALSE(svr.is_running());
  4056. });
  4057. svr.wait_until_ready();
  4058. Client cli("localhost", PORT);
  4059. {
  4060. auto res = cli.Get("/exception");
  4061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4062. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4063. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4064. }
  4065. {
  4066. auto res = cli.Get("/unknown");
  4067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4068. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4069. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4070. }
  4071. }
  4072. TEST(ExceptionTest, WithExceptionHandler) {
  4073. Server svr;
  4074. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4075. std::exception_ptr ep) {
  4076. EXPECT_FALSE(ep == nullptr);
  4077. try {
  4078. std::rethrow_exception(ep);
  4079. } catch (std::exception &e) {
  4080. EXPECT_EQ("abc", std::string(e.what()));
  4081. } catch (...) {}
  4082. res.status = StatusCode::InternalServerError_500;
  4083. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4084. "text/html"); // <= Content-Length still 13 at this point
  4085. });
  4086. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4087. res.set_content("Hello World!\n", "text/plain");
  4088. throw std::runtime_error("abc");
  4089. });
  4090. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4091. auto se = detail::scope_exit([&] {
  4092. svr.stop();
  4093. thread.join();
  4094. ASSERT_FALSE(svr.is_running());
  4095. });
  4096. svr.wait_until_ready();
  4097. for (size_t i = 0; i < 10; i++) {
  4098. Client cli(HOST, PORT);
  4099. for (size_t j = 0; j < 100; j++) {
  4100. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4102. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4103. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4104. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4105. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4106. }
  4107. cli.set_keep_alive(true);
  4108. for (size_t j = 0; j < 100; j++) {
  4109. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4111. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4112. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4113. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4114. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4115. }
  4116. }
  4117. }
  4118. TEST(ExceptionTest, AndErrorHandler) {
  4119. Server svr;
  4120. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4121. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4122. });
  4123. svr.set_exception_handler(
  4124. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4125. EXPECT_FALSE(ep == nullptr);
  4126. try {
  4127. std::rethrow_exception(ep);
  4128. } catch (std::exception &e) {
  4129. res.set_content(e.what(), "text/html");
  4130. } catch (...) {}
  4131. res.status = StatusCode::InternalServerError_500;
  4132. });
  4133. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4134. throw std::runtime_error("EXCEPTION");
  4135. });
  4136. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4137. res.set_content("ERROR", "text/html");
  4138. res.status = StatusCode::InternalServerError_500;
  4139. });
  4140. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4141. auto se = detail::scope_exit([&] {
  4142. svr.stop();
  4143. thread.join();
  4144. ASSERT_FALSE(svr.is_running());
  4145. });
  4146. svr.wait_until_ready();
  4147. Client cli(HOST, PORT);
  4148. {
  4149. auto res = cli.Get("/exception");
  4150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4151. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4152. EXPECT_EQ("EXCEPTION", res->body);
  4153. }
  4154. {
  4155. auto res = cli.Get("/error");
  4156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4157. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4158. EXPECT_EQ("ERROR", res->body);
  4159. }
  4160. {
  4161. auto res = cli.Get("/invalid");
  4162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4163. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4164. EXPECT_EQ("NOT_FOUND", res->body);
  4165. }
  4166. }
  4167. #endif
  4168. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4169. // process_request() wraps only routing() in a try/catch, so an exception from
  4170. // any other user callback used to unwind into the task queue - which does not
  4171. // catch - and terminate the process. Each test below runs the server on a
  4172. // single worker thread: a guard that catches the exception but still loses the
  4173. // thread would otherwise be hidden by a spare worker serving the follow-up
  4174. // request. Note that a regression here aborts the whole test binary rather
  4175. // than failing one test.
  4176. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4177. Server svr;
  4178. svr.new_task_queue = [] { return new ThreadPool(1); };
  4179. std::atomic<int> reported{0};
  4180. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4181. if (err == Error::UserCallbackException) { reported++; }
  4182. });
  4183. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4184. res.set_content_provider(
  4185. 1024, "text/plain",
  4186. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4187. sink.write("hello", 5);
  4188. throw std::runtime_error("from the content provider");
  4189. });
  4190. });
  4191. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4192. res.set_content("ok", "text/plain");
  4193. });
  4194. auto port = svr.bind_to_any_port(HOST);
  4195. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4196. auto se = detail::scope_exit([&] {
  4197. svr.stop();
  4198. listen_thread.join();
  4199. ASSERT_FALSE(svr.is_running());
  4200. });
  4201. svr.wait_until_ready();
  4202. {
  4203. Client cli(HOST, port);
  4204. cli.set_read_timeout(5, 0);
  4205. EXPECT_FALSE(cli.Get("/throw"));
  4206. }
  4207. EXPECT_TRUE(svr.is_running());
  4208. EXPECT_EQ(1, reported.load());
  4209. // A request on a fresh connection is still served.
  4210. {
  4211. Client cli(HOST, port);
  4212. auto res = cli.Get("/ok");
  4213. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4214. EXPECT_EQ(StatusCode::OK_200, res->status);
  4215. EXPECT_EQ("ok", res->body);
  4216. }
  4217. }
  4218. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4219. Server svr;
  4220. svr.new_task_queue = [] { return new ThreadPool(1); };
  4221. std::atomic<bool> should_throw{true};
  4222. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4223. res.set_content("hi", "text/plain");
  4224. });
  4225. svr.set_post_routing_handler(
  4226. [&](const Request & /*req*/, Response & /*res*/) {
  4227. if (should_throw) {
  4228. throw std::runtime_error("from the post-routing handler");
  4229. }
  4230. });
  4231. auto port = svr.bind_to_any_port(HOST);
  4232. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4233. auto se = detail::scope_exit([&] {
  4234. svr.stop();
  4235. listen_thread.join();
  4236. ASSERT_FALSE(svr.is_running());
  4237. });
  4238. svr.wait_until_ready();
  4239. {
  4240. Client cli(HOST, port);
  4241. cli.set_read_timeout(5, 0);
  4242. EXPECT_FALSE(cli.Get("/hi"));
  4243. }
  4244. EXPECT_TRUE(svr.is_running());
  4245. should_throw = false;
  4246. {
  4247. Client cli(HOST, port);
  4248. auto res = cli.Get("/hi");
  4249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4250. EXPECT_EQ(StatusCode::OK_200, res->status);
  4251. EXPECT_EQ("hi", res->body);
  4252. }
  4253. }
  4254. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4255. // The guard reports the caught exception through the error logger, which is
  4256. // a user callback too. A logger that throws has to be contained as well, or
  4257. // the process would terminate from inside the catch.
  4258. Server svr;
  4259. svr.new_task_queue = [] { return new ThreadPool(1); };
  4260. std::atomic<int> reported{0};
  4261. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4262. if (err == Error::UserCallbackException) {
  4263. reported++;
  4264. throw std::runtime_error("from the error logger");
  4265. }
  4266. });
  4267. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4268. res.set_content_provider(
  4269. 1024, "text/plain",
  4270. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4271. sink.write("hello", 5);
  4272. throw std::runtime_error("from the content provider");
  4273. });
  4274. });
  4275. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4276. res.set_content("ok", "text/plain");
  4277. });
  4278. auto port = svr.bind_to_any_port(HOST);
  4279. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4280. auto se = detail::scope_exit([&] {
  4281. svr.stop();
  4282. listen_thread.join();
  4283. ASSERT_FALSE(svr.is_running());
  4284. });
  4285. svr.wait_until_ready();
  4286. {
  4287. Client cli(HOST, port);
  4288. cli.set_read_timeout(5, 0);
  4289. EXPECT_FALSE(cli.Get("/throw"));
  4290. }
  4291. EXPECT_TRUE(svr.is_running());
  4292. EXPECT_EQ(1, reported.load());
  4293. {
  4294. Client cli(HOST, port);
  4295. auto res = cli.Get("/ok");
  4296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4297. EXPECT_EQ(StatusCode::OK_200, res->status);
  4298. EXPECT_EQ("ok", res->body);
  4299. }
  4300. }
  4301. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4302. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4303. // so the exception unwinds through the ws::WebSocket object on its way to
  4304. // the guard. None of the HTTP cases above cross that.
  4305. Server svr;
  4306. svr.new_task_queue = [] { return new ThreadPool(1); };
  4307. std::atomic<int> reported{0};
  4308. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4309. if (err == Error::UserCallbackException) { reported++; }
  4310. });
  4311. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4312. throw std::runtime_error("from the WebSocket handler");
  4313. });
  4314. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4315. res.set_content("ok", "text/plain");
  4316. });
  4317. auto port = svr.bind_to_any_port(HOST);
  4318. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4319. auto se = detail::scope_exit([&] {
  4320. svr.stop();
  4321. listen_thread.join();
  4322. ASSERT_FALSE(svr.is_running());
  4323. });
  4324. svr.wait_until_ready();
  4325. {
  4326. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4327. "/ws");
  4328. auto res = client.connect();
  4329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4330. // The server dropped the connection instead of dying.
  4331. std::string msg;
  4332. EXPECT_FALSE(client.read(msg));
  4333. client.close();
  4334. }
  4335. EXPECT_TRUE(svr.is_running());
  4336. EXPECT_EQ(1, reported.load());
  4337. {
  4338. Client cli(HOST, port);
  4339. auto res = cli.Get("/ok");
  4340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4341. EXPECT_EQ(StatusCode::OK_200, res->status);
  4342. EXPECT_EQ("ok", res->body);
  4343. }
  4344. }
  4345. #ifdef CPPHTTPLIB_SSL_ENABLED
  4346. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4347. // SSLServer::process_and_close_socket() is a separate overload with its own
  4348. // guard, so it is exercised on its own.
  4349. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4350. ASSERT_TRUE(svr.is_valid());
  4351. svr.new_task_queue = [] { return new ThreadPool(1); };
  4352. std::atomic<int> reported{0};
  4353. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4354. if (err == Error::UserCallbackException) { reported++; }
  4355. });
  4356. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4357. res.set_content_provider(
  4358. 1024, "text/plain",
  4359. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4360. sink.write("hello", 5);
  4361. throw std::runtime_error("from the content provider");
  4362. });
  4363. });
  4364. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4365. res.set_content("ok", "text/plain");
  4366. });
  4367. auto port = svr.bind_to_any_port(HOST);
  4368. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4369. auto se = detail::scope_exit([&] {
  4370. svr.stop();
  4371. listen_thread.join();
  4372. ASSERT_FALSE(svr.is_running());
  4373. });
  4374. svr.wait_until_ready();
  4375. {
  4376. SSLClient cli(HOST, port);
  4377. cli.enable_server_certificate_verification(false);
  4378. cli.set_read_timeout(5, 0);
  4379. EXPECT_FALSE(cli.Get("/throw"));
  4380. }
  4381. EXPECT_TRUE(svr.is_running());
  4382. EXPECT_EQ(1, reported.load());
  4383. {
  4384. SSLClient cli(HOST, port);
  4385. cli.enable_server_certificate_verification(false);
  4386. auto res = cli.Get("/ok");
  4387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4388. EXPECT_EQ(StatusCode::OK_200, res->status);
  4389. EXPECT_EQ("ok", res->body);
  4390. }
  4391. }
  4392. #endif
  4393. #endif
  4394. TEST(NoContentTest, ContentLength) {
  4395. Server svr;
  4396. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4397. res.status = StatusCode::NoContent_204;
  4398. });
  4399. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4400. auto se = detail::scope_exit([&] {
  4401. svr.stop();
  4402. thread.join();
  4403. ASSERT_FALSE(svr.is_running());
  4404. });
  4405. svr.wait_until_ready();
  4406. {
  4407. Client cli(HOST, PORT);
  4408. auto res = cli.Get("/hi");
  4409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4410. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4411. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4412. }
  4413. }
  4414. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4415. #ifdef CPPHTTPLIB_SSL_ENABLED
  4416. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4417. ASSERT_TRUE(svr.is_valid());
  4418. #else
  4419. Server svr;
  4420. #endif
  4421. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4422. if (req.path == "/routing_handler") {
  4423. res.set_header("PRE_ROUTING", "on");
  4424. res.set_content("Routing Handler", "text/plain");
  4425. return httplib::Server::HandlerResponse::Handled;
  4426. }
  4427. return httplib::Server::HandlerResponse::Unhandled;
  4428. });
  4429. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4430. res.set_content("Error", "text/html");
  4431. });
  4432. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4433. if (req.path == "/routing_handler") {
  4434. res.set_header("POST_ROUTING", "on");
  4435. }
  4436. });
  4437. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4438. res.set_content("Hello World!\n", "text/plain");
  4439. });
  4440. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4441. auto se = detail::scope_exit([&] {
  4442. svr.stop();
  4443. thread.join();
  4444. ASSERT_FALSE(svr.is_running());
  4445. });
  4446. svr.wait_until_ready();
  4447. {
  4448. #ifdef CPPHTTPLIB_SSL_ENABLED
  4449. SSLClient cli(HOST, PORT);
  4450. cli.enable_server_certificate_verification(false);
  4451. #else
  4452. Client cli(HOST, PORT);
  4453. #endif
  4454. auto res = cli.Get("/routing_handler");
  4455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4456. EXPECT_EQ(StatusCode::OK_200, res->status);
  4457. EXPECT_EQ("Routing Handler", res->body);
  4458. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4459. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4460. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4461. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4462. }
  4463. {
  4464. #ifdef CPPHTTPLIB_SSL_ENABLED
  4465. SSLClient cli(HOST, PORT);
  4466. cli.enable_server_certificate_verification(false);
  4467. #else
  4468. Client cli(HOST, PORT);
  4469. #endif
  4470. auto res = cli.Get("/hi");
  4471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4472. EXPECT_EQ(StatusCode::OK_200, res->status);
  4473. EXPECT_EQ("Hello World!\n", res->body);
  4474. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4475. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4476. }
  4477. {
  4478. #ifdef CPPHTTPLIB_SSL_ENABLED
  4479. SSLClient cli(HOST, PORT);
  4480. cli.enable_server_certificate_verification(false);
  4481. #else
  4482. Client cli(HOST, PORT);
  4483. #endif
  4484. auto res = cli.Get("/aaa");
  4485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4486. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4487. EXPECT_EQ("Error", res->body);
  4488. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4489. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4490. }
  4491. }
  4492. TEST(RequestHandlerTest, PreRequestHandler) {
  4493. auto route_path = "/user/:user";
  4494. Server svr;
  4495. svr.Get("/hi", [](const Request &, Response &res) {
  4496. res.set_content("hi", "text/plain");
  4497. });
  4498. svr.Get(route_path, [](const Request &req, Response &res) {
  4499. res.set_content(req.path_params.at("user"), "text/plain");
  4500. });
  4501. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4502. if (req.matched_route == route_path) {
  4503. auto user = req.path_params.at("user");
  4504. if (user != "john") {
  4505. res.status = StatusCode::Forbidden_403;
  4506. res.set_content("error", "text/html");
  4507. return Server::HandlerResponse::Handled;
  4508. }
  4509. }
  4510. return Server::HandlerResponse::Unhandled;
  4511. });
  4512. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4513. auto se = detail::scope_exit([&] {
  4514. svr.stop();
  4515. thread.join();
  4516. ASSERT_FALSE(svr.is_running());
  4517. });
  4518. svr.wait_until_ready();
  4519. Client cli(HOST, PORT);
  4520. {
  4521. auto res = cli.Get("/hi");
  4522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4523. EXPECT_EQ(StatusCode::OK_200, res->status);
  4524. EXPECT_EQ("hi", res->body);
  4525. }
  4526. {
  4527. auto res = cli.Get("/user/john");
  4528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4529. EXPECT_EQ(StatusCode::OK_200, res->status);
  4530. EXPECT_EQ("john", res->body);
  4531. }
  4532. {
  4533. auto res = cli.Get("/user/invalid-user");
  4534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4535. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4536. EXPECT_EQ("error", res->body);
  4537. }
  4538. }
  4539. // The pre-request handler must run before the request body is read, so a
  4540. // rejected request never forces the server to buffer a (potentially large)
  4541. // body. Here the posted body is larger than the payload limit: if the body
  4542. // were read first the server would answer 413, but because the pre-request
  4543. // handler runs first it answers 403 and the body is never read.
  4544. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4545. Server svr;
  4546. svr.set_payload_max_length(8);
  4547. auto handler_ran = false;
  4548. svr.Post("/reject", [&](const Request &req, Response &res) {
  4549. handler_ran = true;
  4550. res.set_content(req.body, "text/plain");
  4551. });
  4552. svr.Post("/accept", [](const Request &req, Response &res) {
  4553. res.set_content(req.body, "text/plain");
  4554. });
  4555. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4556. if (req.matched_route == "/reject") {
  4557. res.status = StatusCode::Forbidden_403;
  4558. res.set_content("denied", "text/plain");
  4559. return Server::HandlerResponse::Handled;
  4560. }
  4561. return Server::HandlerResponse::Unhandled;
  4562. });
  4563. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4564. auto se = detail::scope_exit([&] {
  4565. svr.stop();
  4566. thread.join();
  4567. ASSERT_FALSE(svr.is_running());
  4568. });
  4569. svr.wait_until_ready();
  4570. Client cli(HOST, PORT);
  4571. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4572. // rejects with 403 before the body is read, so 413 is never reached.
  4573. {
  4574. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4576. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4577. EXPECT_EQ("denied", res->body);
  4578. EXPECT_FALSE(handler_ran);
  4579. }
  4580. // An approved route still reads the body and enforces the payload limit.
  4581. {
  4582. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4584. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4585. }
  4586. }
  4587. TEST(UserDataTest, BasicOperations) {
  4588. httplib::UserData ud;
  4589. // Initially empty
  4590. EXPECT_FALSE(ud.has("key"));
  4591. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4592. // set and get
  4593. ud.set("key", 42);
  4594. EXPECT_TRUE(ud.has("key"));
  4595. auto *p = ud.get<int>("key");
  4596. ASSERT_NE(nullptr, p);
  4597. EXPECT_EQ(42, *p);
  4598. // Type mismatch → nullptr
  4599. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4600. // Overwrite with different type
  4601. ud.set("key", std::string("hello"));
  4602. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4603. auto *s = ud.get<std::string>("key");
  4604. ASSERT_NE(nullptr, s);
  4605. EXPECT_EQ("hello", *s);
  4606. // erase
  4607. ud.erase("key");
  4608. EXPECT_FALSE(ud.has("key"));
  4609. // clear
  4610. ud.set("a", 1);
  4611. ud.set("b", 2);
  4612. ud.clear();
  4613. EXPECT_FALSE(ud.has("a"));
  4614. EXPECT_FALSE(ud.has("b"));
  4615. }
  4616. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4617. struct AuthCtx {
  4618. std::string user_id;
  4619. };
  4620. Server svr;
  4621. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4622. res.user_data.set("auth", AuthCtx{"alice"});
  4623. return Server::HandlerResponse::Unhandled;
  4624. });
  4625. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4626. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4627. ASSERT_NE(nullptr, ctx);
  4628. res.set_content("Hello " + ctx->user_id, "text/plain");
  4629. });
  4630. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4631. auto se = detail::scope_exit([&] {
  4632. svr.stop();
  4633. thread.join();
  4634. ASSERT_FALSE(svr.is_running());
  4635. });
  4636. svr.wait_until_ready();
  4637. Client cli(HOST, PORT);
  4638. auto res = cli.Get("/me");
  4639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4640. EXPECT_EQ(StatusCode::OK_200, res->status);
  4641. EXPECT_EQ("Hello alice", res->body);
  4642. }
  4643. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4644. struct RoleCtx {
  4645. std::string role;
  4646. };
  4647. Server svr;
  4648. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4649. res.user_data.set("role", RoleCtx{"admin"});
  4650. return Server::HandlerResponse::Unhandled;
  4651. });
  4652. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4653. auto *ctx = res.user_data.get<RoleCtx>("role");
  4654. ASSERT_NE(nullptr, ctx);
  4655. res.set_content(ctx->role, "text/plain");
  4656. });
  4657. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4658. auto se = detail::scope_exit([&] {
  4659. svr.stop();
  4660. thread.join();
  4661. ASSERT_FALSE(svr.is_running());
  4662. });
  4663. svr.wait_until_ready();
  4664. Client cli(HOST, PORT);
  4665. auto res = cli.Get("/role");
  4666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4667. EXPECT_EQ(StatusCode::OK_200, res->status);
  4668. EXPECT_EQ("admin", res->body);
  4669. }
  4670. TEST(InvalidFormatTest, StatusCode) {
  4671. Server svr;
  4672. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4673. res.set_content("Hello World!\n", "text/plain");
  4674. res.status = 9999; // Status should be a three-digit code...
  4675. });
  4676. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4677. auto se = detail::scope_exit([&] {
  4678. svr.stop();
  4679. thread.join();
  4680. ASSERT_FALSE(svr.is_running());
  4681. });
  4682. svr.wait_until_ready();
  4683. {
  4684. Client cli(HOST, PORT);
  4685. auto res = cli.Get("/hi");
  4686. ASSERT_FALSE(res);
  4687. }
  4688. }
  4689. TEST(URLFragmentTest, WithFragment) {
  4690. Server svr;
  4691. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4692. EXPECT_TRUE(req.target == "/hi");
  4693. });
  4694. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4695. auto se = detail::scope_exit([&] {
  4696. svr.stop();
  4697. thread.join();
  4698. ASSERT_FALSE(svr.is_running());
  4699. });
  4700. svr.wait_until_ready();
  4701. {
  4702. Client cli(HOST, PORT);
  4703. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4704. EXPECT_TRUE(res);
  4705. EXPECT_EQ(StatusCode::OK_200, res->status);
  4706. res = cli.Get("/hi%23key1=val1=key2=val2");
  4707. EXPECT_TRUE(res);
  4708. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4709. }
  4710. }
  4711. TEST(HeaderWriter, SetHeaderWriter) {
  4712. Server svr;
  4713. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4714. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4715. return detail::write_headers(strm, hdrs);
  4716. });
  4717. svr.Get("/hi", [](const Request &req, Response &res) {
  4718. auto it = req.headers.find("CustomClientHeader");
  4719. EXPECT_TRUE(it != req.headers.end());
  4720. EXPECT_EQ(it->second, "CustomClientValue");
  4721. res.set_content("Hello World!\n", "text/plain");
  4722. });
  4723. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4724. auto se = detail::scope_exit([&] {
  4725. svr.stop();
  4726. thread.join();
  4727. ASSERT_FALSE(svr.is_running());
  4728. });
  4729. svr.wait_until_ready();
  4730. {
  4731. Client cli(HOST, PORT);
  4732. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4733. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4734. return detail::write_headers(strm, hdrs);
  4735. });
  4736. auto res = cli.Get("/hi");
  4737. EXPECT_TRUE(res);
  4738. EXPECT_EQ(StatusCode::OK_200, res->status);
  4739. auto it = res->headers.find("CustomServerHeader");
  4740. EXPECT_TRUE(it != res->headers.end());
  4741. EXPECT_EQ(it->second, "CustomServerValue");
  4742. }
  4743. }
  4744. class ServerTest : public ::testing::Test {
  4745. protected:
  4746. ServerTest()
  4747. : cli_(HOST, PORT)
  4748. #ifdef CPPHTTPLIB_SSL_ENABLED
  4749. ,
  4750. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4751. #endif
  4752. {
  4753. #ifdef CPPHTTPLIB_SSL_ENABLED
  4754. cli_.enable_server_certificate_verification(false);
  4755. #endif
  4756. // Allow LARGE_DATA (100MB) responses
  4757. cli_.set_payload_max_length(200 * 1024 * 1024);
  4758. }
  4759. virtual void SetUp() {
  4760. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4761. svr_.set_payload_max_length(200 * 1024 * 1024);
  4762. svr_.set_mount_point("/", "./www");
  4763. svr_.set_mount_point("/mount", "./www2");
  4764. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4765. svr_.Get("/hi",
  4766. [&](const Request & /*req*/, Response &res) {
  4767. res.set_content("Hello World!", "text/plain");
  4768. })
  4769. .Get("/file_content",
  4770. [&](const Request & /*req*/, Response &res) {
  4771. res.set_file_content("./www/dir/test.html");
  4772. })
  4773. .Get("/file_content_with_content_type",
  4774. [&](const Request & /*req*/, Response &res) {
  4775. res.set_file_content("./www/file", "text/plain");
  4776. })
  4777. .Get("/invalid_file_content",
  4778. [&](const Request & /*req*/, Response &res) {
  4779. res.set_file_content("./www/dir/invalid_file_path");
  4780. })
  4781. .Get("/http_response_splitting",
  4782. [&](const Request & /*req*/, Response &res) {
  4783. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4784. EXPECT_EQ(0U, res.headers.size());
  4785. EXPECT_FALSE(res.has_header("a"));
  4786. res.set_header("a", "1\nSet-Cookie: a=1");
  4787. EXPECT_EQ(0U, res.headers.size());
  4788. EXPECT_FALSE(res.has_header("a"));
  4789. res.set_header("a", "1\rSet-Cookie: a=1");
  4790. EXPECT_EQ(0U, res.headers.size());
  4791. EXPECT_FALSE(res.has_header("a"));
  4792. res.set_header("a\r\nb", "0");
  4793. EXPECT_EQ(0U, res.headers.size());
  4794. EXPECT_FALSE(res.has_header("a"));
  4795. res.set_header("a\rb", "0");
  4796. EXPECT_EQ(0U, res.headers.size());
  4797. EXPECT_FALSE(res.has_header("a"));
  4798. res.set_header("a\nb", "0");
  4799. EXPECT_EQ(0U, res.headers.size());
  4800. EXPECT_FALSE(res.has_header("a"));
  4801. res.set_redirect("1\r\nSet-Cookie: a=1");
  4802. EXPECT_EQ(0U, res.headers.size());
  4803. EXPECT_FALSE(res.has_header("Location"));
  4804. })
  4805. .Get("/slow",
  4806. [&](const Request & /*req*/, Response &res) {
  4807. std::this_thread::sleep_for(std::chrono::seconds(4));
  4808. res.set_content("slow", "text/plain");
  4809. })
  4810. #if 0
  4811. .Post("/slowpost",
  4812. [&](const Request & /*req*/, Response &res) {
  4813. std::this_thread::sleep_for(std::chrono::seconds(2));
  4814. res.set_content("slow", "text/plain");
  4815. })
  4816. #endif
  4817. .Get("/remote_addr",
  4818. [&](const Request &req, Response &res) {
  4819. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4820. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4821. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4822. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4823. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4824. #endif
  4825. res.set_content(req.remote_addr, "text/plain");
  4826. })
  4827. .Get("/local_addr",
  4828. [&](const Request &req, Response &res) {
  4829. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4830. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4831. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4832. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4833. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4834. #endif
  4835. auto local_addr = req.local_addr;
  4836. auto local_port = std::to_string(req.local_port);
  4837. res.set_content(local_addr.append(":").append(local_port),
  4838. "text/plain");
  4839. })
  4840. .Get("/endwith%",
  4841. [&](const Request & /*req*/, Response &res) {
  4842. res.set_content("Hello World!", "text/plain");
  4843. })
  4844. .Get("/a\\+\\+b",
  4845. [&](const Request &req, Response &res) {
  4846. ASSERT_TRUE(req.has_param("a +b"));
  4847. auto val = req.get_param_value("a +b");
  4848. res.set_content(val, "text/plain");
  4849. })
  4850. .Get("/", [&](const Request & /*req*/,
  4851. Response &res) { res.set_redirect("/hi"); })
  4852. .Post("/1",
  4853. [](const Request & /*req*/, Response &res) {
  4854. res.set_redirect("/2", StatusCode::SeeOther_303);
  4855. })
  4856. .Get("/2",
  4857. [](const Request & /*req*/, Response &res) {
  4858. res.set_content("redirected.", "text/plain");
  4859. res.status = StatusCode::OK_200;
  4860. })
  4861. .Post("/person",
  4862. [&](const Request &req, Response &res) {
  4863. if (req.has_param("name") && req.has_param("note")) {
  4864. persons_[req.get_param_value("name")] =
  4865. req.get_param_value("note");
  4866. } else {
  4867. res.status = StatusCode::BadRequest_400;
  4868. }
  4869. })
  4870. .Put("/person",
  4871. [&](const Request &req, Response &res) {
  4872. if (req.has_param("name") && req.has_param("note")) {
  4873. persons_[req.get_param_value("name")] =
  4874. req.get_param_value("note");
  4875. } else {
  4876. res.status = StatusCode::BadRequest_400;
  4877. }
  4878. })
  4879. .Get("/person/(.*)",
  4880. [&](const Request &req, Response &res) {
  4881. string name = req.matches[1];
  4882. if (persons_.find(name) != persons_.end()) {
  4883. auto note = persons_[name];
  4884. res.set_content(note, "text/plain");
  4885. } else {
  4886. res.status = StatusCode::NotFound_404;
  4887. }
  4888. })
  4889. .Delete("/person",
  4890. [&](const Request &req, Response &res) {
  4891. if (req.has_param("name")) {
  4892. string name = req.get_param_value("name");
  4893. if (persons_.find(name) != persons_.end()) {
  4894. persons_.erase(name);
  4895. res.set_content("DELETED", "text/plain");
  4896. } else {
  4897. res.status = StatusCode::NotFound_404;
  4898. }
  4899. } else {
  4900. res.status = StatusCode::BadRequest_400;
  4901. }
  4902. })
  4903. .Post("/x-www-form-urlencoded-json",
  4904. [&](const Request &req, Response &res) {
  4905. auto json = req.get_param_value("json");
  4906. ASSERT_EQ(JSON_DATA, json);
  4907. res.set_content(json, "appliation/json");
  4908. res.status = StatusCode::OK_200;
  4909. })
  4910. .Get("/streamed-chunked",
  4911. [&](const Request & /*req*/, Response &res) {
  4912. res.set_chunked_content_provider(
  4913. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4914. sink.os << "123";
  4915. sink.os << "456";
  4916. sink.os << "789";
  4917. sink.done();
  4918. return true;
  4919. });
  4920. })
  4921. .Get("/streamed-chunked-with-prohibited-trailer",
  4922. [&](const Request & /*req*/, Response &res) {
  4923. auto i = new int(0);
  4924. // Declare both a prohibited trailer (Content-Length) and an
  4925. // allowed one
  4926. res.set_header("Trailer", "Content-Length, X-Allowed");
  4927. res.set_chunked_content_provider(
  4928. "text/plain",
  4929. [i](size_t /*offset*/, DataSink &sink) {
  4930. switch (*i) {
  4931. case 0: sink.os << "123"; break;
  4932. case 1: sink.os << "456"; break;
  4933. case 2: sink.os << "789"; break;
  4934. case 3: {
  4935. sink.done_with_trailer(
  4936. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4937. } break;
  4938. }
  4939. (*i)++;
  4940. return true;
  4941. },
  4942. [i](bool success) {
  4943. EXPECT_TRUE(success);
  4944. delete i;
  4945. });
  4946. })
  4947. .Get("/streamed-chunked2",
  4948. [&](const Request & /*req*/, Response &res) {
  4949. auto i = new int(0);
  4950. res.set_chunked_content_provider(
  4951. "text/plain",
  4952. [i](size_t /*offset*/, DataSink &sink) {
  4953. switch (*i) {
  4954. case 0: sink.os << "123"; break;
  4955. case 1: sink.os << "456"; break;
  4956. case 2: sink.os << "789"; break;
  4957. case 3: sink.done(); break;
  4958. }
  4959. (*i)++;
  4960. return true;
  4961. },
  4962. [i](bool success) {
  4963. EXPECT_TRUE(success);
  4964. delete i;
  4965. });
  4966. })
  4967. .Get("/streamed-chunked-with-trailer",
  4968. [&](const Request & /*req*/, Response &res) {
  4969. auto i = new int(0);
  4970. res.set_header("Trailer", "Dummy1, Dummy2");
  4971. res.set_chunked_content_provider(
  4972. "text/plain",
  4973. [i](size_t /*offset*/, DataSink &sink) {
  4974. switch (*i) {
  4975. case 0: sink.os << "123"; break;
  4976. case 1: sink.os << "456"; break;
  4977. case 2: sink.os << "789"; break;
  4978. case 3: {
  4979. sink.done_with_trailer(
  4980. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4981. } break;
  4982. }
  4983. (*i)++;
  4984. return true;
  4985. },
  4986. [i](bool success) {
  4987. EXPECT_TRUE(success);
  4988. delete i;
  4989. });
  4990. })
  4991. .Get("/streamed",
  4992. [&](const Request & /*req*/, Response &res) {
  4993. res.set_content_provider(
  4994. 6, "text/plain",
  4995. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4996. sink.os << (offset < 3 ? "a" : "b");
  4997. return true;
  4998. });
  4999. })
  5000. .Get("/streamed-without-length",
  5001. [&](const Request & /*req*/, Response &res) {
  5002. auto data = new std::string("abcdefg");
  5003. res.set_content_provider(
  5004. "text/plain",
  5005. [data](size_t offset, DataSink &sink) {
  5006. if (offset < data->size()) {
  5007. sink.os << data->substr(offset);
  5008. }
  5009. sink.done();
  5010. return true;
  5011. },
  5012. [data](bool success) {
  5013. EXPECT_TRUE(success);
  5014. delete data;
  5015. });
  5016. })
  5017. .Get("/streamed-with-range",
  5018. [&](const Request &req, Response &res) {
  5019. auto data = new std::string("abcdefg");
  5020. // An explicit status keeps the server from picking the 206 it
  5021. // would otherwise choose for a ranged request, so the response
  5022. // is not a partial representation.
  5023. auto status = req.get_param_value("status");
  5024. if (status == "200") {
  5025. res.status = StatusCode::OK_200;
  5026. } else if (status == "403") {
  5027. res.status = StatusCode::Forbidden_403;
  5028. }
  5029. res.set_content_provider(
  5030. data->size(), "text/plain",
  5031. [data](size_t offset, size_t length, DataSink &sink) {
  5032. size_t DATA_CHUNK_SIZE = 4;
  5033. const auto &d = *data;
  5034. auto out_len =
  5035. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5036. auto ret =
  5037. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5038. EXPECT_TRUE(ret);
  5039. return true;
  5040. },
  5041. [data, &req](bool success) {
  5042. EXPECT_EQ(success, !req.has_param("error"));
  5043. delete data;
  5044. });
  5045. })
  5046. .Get("/streamed-cancel",
  5047. [&](const Request & /*req*/, Response &res) {
  5048. res.set_content_provider(
  5049. size_t(-1), "text/plain",
  5050. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5051. sink.os << "data_chunk";
  5052. return true;
  5053. });
  5054. })
  5055. .Get("/regex-with-delimiter",
  5056. [&](const Request &req, Response & /*res*/) {
  5057. ASSERT_TRUE(req.has_param("key"));
  5058. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5059. })
  5060. .Get("/with-range",
  5061. [&](const Request & /*req*/, Response &res) {
  5062. res.set_content("abcdefg", "text/plain");
  5063. })
  5064. .Get("/test-start-time",
  5065. [&](const Request &req, Response & /*res*/) {
  5066. EXPECT_NE(req.start_time_,
  5067. std::chrono::steady_clock::time_point::min());
  5068. })
  5069. .Get("/with-range-customized-response",
  5070. [&](const Request & /*req*/, Response &res) {
  5071. res.status = StatusCode::BadRequest_400;
  5072. res.set_content(JSON_DATA, "application/json");
  5073. })
  5074. .Post("/chunked",
  5075. [&](const Request &req, Response & /*res*/) {
  5076. EXPECT_EQ(req.body, "dechunked post body");
  5077. })
  5078. .Post("/large-chunked",
  5079. [&](const Request &req, Response & /*res*/) {
  5080. std::string expected(6 * 30 * 1024u, 'a');
  5081. EXPECT_EQ(req.body, expected);
  5082. })
  5083. .Post("/multipart",
  5084. [&](const Request &req, Response & /*res*/) {
  5085. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5086. req.form.get_field_count("text2") +
  5087. req.form.get_field_count("file3") +
  5088. req.form.get_field_count("file4"));
  5089. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5090. req.form.get_file_count("file2"));
  5091. ASSERT_TRUE(!req.form.has_file("???"));
  5092. ASSERT_TRUE(!req.form.has_field("???"));
  5093. ASSERT_TRUE(req.body.empty());
  5094. {
  5095. const auto &text = req.form.get_field("text1");
  5096. EXPECT_EQ("text default", text);
  5097. }
  5098. {
  5099. const auto &text = req.form.get_field("text2");
  5100. EXPECT_EQ("aωb", text);
  5101. }
  5102. {
  5103. const auto &file = req.form.get_file("file1");
  5104. EXPECT_EQ("hello.txt", file.filename);
  5105. EXPECT_EQ("text/plain", file.content_type);
  5106. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5107. }
  5108. {
  5109. const auto &file = req.form.get_file("file2");
  5110. EXPECT_EQ("world.json", file.filename);
  5111. EXPECT_EQ("application/json", file.content_type);
  5112. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5113. }
  5114. {
  5115. const auto &text = req.form.get_field("file3");
  5116. EXPECT_EQ(0u, text.size());
  5117. }
  5118. {
  5119. const auto &text = req.form.get_field("file4");
  5120. EXPECT_EQ(0u, text.size());
  5121. }
  5122. })
  5123. .Post("/multipart/multi_file_values",
  5124. [&](const Request &req, Response & /*res*/) {
  5125. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5126. req.form.get_field_count("multi_text1"));
  5127. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5128. ASSERT_TRUE(!req.form.has_file("???"));
  5129. ASSERT_TRUE(!req.form.has_field("???"));
  5130. ASSERT_TRUE(req.body.empty());
  5131. {
  5132. const auto &text = req.form.get_field("text");
  5133. EXPECT_EQ("default text", text);
  5134. }
  5135. {
  5136. const auto &text1_values = req.form.get_fields("multi_text1");
  5137. EXPECT_EQ(2u, text1_values.size());
  5138. EXPECT_EQ("aaaaa", text1_values[0]);
  5139. EXPECT_EQ("bbbbb", text1_values[1]);
  5140. }
  5141. {
  5142. const auto &file1_values = req.form.get_files("multi_file1");
  5143. EXPECT_EQ(2u, file1_values.size());
  5144. auto file1 = file1_values[0];
  5145. EXPECT_EQ(file1.filename, "hello.txt");
  5146. EXPECT_EQ(file1.content_type, "text/plain");
  5147. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5148. auto file2 = file1_values[1];
  5149. EXPECT_EQ(file2.filename, "world.json");
  5150. EXPECT_EQ(file2.content_type, "application/json");
  5151. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5152. }
  5153. })
  5154. .Post("/empty",
  5155. [&](const Request &req, Response &res) {
  5156. EXPECT_EQ(req.body, "");
  5157. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5158. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5159. res.set_content("empty", "text/plain");
  5160. })
  5161. .Post("/empty-no-content-type",
  5162. [&](const Request &req, Response &res) {
  5163. EXPECT_EQ(req.body, "");
  5164. EXPECT_FALSE(req.has_header("Content-Type"));
  5165. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5166. res.set_content("empty-no-content-type", "text/plain");
  5167. })
  5168. .Post("/path-only",
  5169. [&](const Request &req, Response &res) {
  5170. EXPECT_EQ(req.body, "");
  5171. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5172. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5173. res.set_content("path-only", "text/plain");
  5174. })
  5175. .Post("/path-headers-only",
  5176. [&](const Request &req, Response &res) {
  5177. EXPECT_EQ(req.body, "");
  5178. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5179. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5180. EXPECT_EQ("world", req.get_header_value("hello"));
  5181. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5182. res.set_content("path-headers-only", "text/plain");
  5183. })
  5184. .Post("/post-large",
  5185. [&](const Request &req, Response &res) {
  5186. EXPECT_EQ(req.body, LARGE_DATA);
  5187. res.set_content(req.body, "text/plain");
  5188. })
  5189. .Post("/post-loopback",
  5190. [&](const Request &, Response &res,
  5191. ContentReader const &content_reader) {
  5192. std::string body;
  5193. content_reader([&](const char *data, size_t data_length) {
  5194. body.append(data, data_length);
  5195. return true;
  5196. });
  5197. res.set_content(body, "text/plain");
  5198. })
  5199. .Put("/put-loopback",
  5200. [&](const Request &, Response &res,
  5201. ContentReader const &content_reader) {
  5202. std::string body;
  5203. content_reader([&](const char *data, size_t data_length) {
  5204. body.append(data, data_length);
  5205. return true;
  5206. });
  5207. res.set_content(body, "text/plain");
  5208. })
  5209. .Patch("/patch-loopback",
  5210. [&](const Request &, Response &res,
  5211. ContentReader const &content_reader) {
  5212. std::string body;
  5213. content_reader([&](const char *data, size_t data_length) {
  5214. body.append(data, data_length);
  5215. return true;
  5216. });
  5217. res.set_content(body, "text/plain");
  5218. })
  5219. .Put("/empty-no-content-type",
  5220. [&](const Request &req, Response &res) {
  5221. EXPECT_EQ(req.body, "");
  5222. EXPECT_FALSE(req.has_header("Content-Type"));
  5223. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5224. res.set_content("empty-no-content-type", "text/plain");
  5225. })
  5226. .Put("/put",
  5227. [&](const Request &req, Response &res) {
  5228. EXPECT_EQ(req.body, "PUT");
  5229. res.set_content(req.body, "text/plain");
  5230. })
  5231. .Put("/put-large",
  5232. [&](const Request &req, Response &res) {
  5233. EXPECT_EQ(req.body, LARGE_DATA);
  5234. res.set_content(req.body, "text/plain");
  5235. })
  5236. .Patch("/patch",
  5237. [&](const Request &req, Response &res) {
  5238. EXPECT_EQ(req.body, "PATCH");
  5239. res.set_content(req.body, "text/plain");
  5240. })
  5241. .Delete("/delete",
  5242. [&](const Request & /*req*/, Response &res) {
  5243. res.set_content("DELETE", "text/plain");
  5244. })
  5245. .Delete("/delete-body",
  5246. [&](const Request &req, Response &res) {
  5247. EXPECT_EQ(req.body, "content");
  5248. res.set_content(req.body, "text/plain");
  5249. })
  5250. .Options(R"(\*)",
  5251. [&](const Request & /*req*/, Response &res) {
  5252. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5253. })
  5254. .CustomRoute("PROPFIND", "/dav/:id",
  5255. [&](const Request &req, Response &res) {
  5256. res.set_header("x-body-size",
  5257. std::to_string(req.body.size()));
  5258. res.set_header("x-matched-route", req.matched_route);
  5259. res.set_header("x-dav-id", req.path_params.at("id"));
  5260. res.status = StatusCode::MultiStatus_207;
  5261. res.set_content(req.body, "application/xml");
  5262. })
  5263. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5264. [&](const Request &req, Response &res) {
  5265. res.set_header("x-dav-match", req.matches[1]);
  5266. res.status = StatusCode::MultiStatus_207;
  5267. })
  5268. .CustomRoute("MKCOL", "/dav-mkcol",
  5269. [&](const Request &req, Response &res) {
  5270. EXPECT_TRUE(req.body.empty());
  5271. res.status = StatusCode::Created_201;
  5272. })
  5273. .CustomRoute(
  5274. "REPORT", "/dav-report",
  5275. [&](const Request & /*req*/, Response &res,
  5276. const ContentReader &content_reader) {
  5277. std::string body;
  5278. content_reader([&](const char *data, size_t data_length) {
  5279. body.append(data, data_length);
  5280. return true;
  5281. });
  5282. res.set_header("x-body-size", std::to_string(body.size()));
  5283. res.status = StatusCode::MultiStatus_207;
  5284. res.set_content(body, "application/xml");
  5285. })
  5286. .Get("/request-target",
  5287. [&](const Request &req, Response & /*res*/) {
  5288. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5289. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5290. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5291. })
  5292. .Get("/long-query-value",
  5293. [&](const Request &req, Response & /*res*/) {
  5294. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5295. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5296. })
  5297. .Get("/too-long-query-value",
  5298. [&](const Request &req, Response & /*res*/) {
  5299. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5300. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5301. })
  5302. .Get("/array-param",
  5303. [&](const Request &req, Response & /*res*/) {
  5304. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5305. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5306. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5307. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5308. })
  5309. .Get("/array-param-values",
  5310. [&](const Request &req, Response & /*res*/) {
  5311. auto values = req.get_param_values("array");
  5312. EXPECT_EQ(3u, values.size());
  5313. EXPECT_EQ("value1", values[0]);
  5314. EXPECT_EQ("value2", values[1]);
  5315. EXPECT_EQ("value3", values[2]);
  5316. auto empty = req.get_param_values("nonexistent");
  5317. EXPECT_TRUE(empty.empty());
  5318. })
  5319. .Post("/validate-no-multiple-headers",
  5320. [&](const Request &req, Response & /*res*/) {
  5321. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5322. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5323. })
  5324. .Post("/content_receiver",
  5325. [&](const Request &req, Response &res,
  5326. const ContentReader &content_reader) {
  5327. if (req.is_multipart_form_data()) {
  5328. std::vector<FormData> items;
  5329. content_reader(
  5330. [&](const FormData &file) {
  5331. items.push_back(file);
  5332. return true;
  5333. },
  5334. [&](const char *data, size_t data_length) {
  5335. items.back().content.append(data, data_length);
  5336. return true;
  5337. });
  5338. EXPECT_EQ(5u, items.size());
  5339. {
  5340. const auto &file = get_file_value(items, "text1");
  5341. EXPECT_TRUE(file.filename.empty());
  5342. EXPECT_EQ("text default", file.content);
  5343. }
  5344. {
  5345. const auto &file = get_file_value(items, "text2");
  5346. EXPECT_TRUE(file.filename.empty());
  5347. EXPECT_EQ("aωb", file.content);
  5348. }
  5349. {
  5350. const auto &file = get_file_value(items, "file1");
  5351. EXPECT_EQ("hello.txt", file.filename);
  5352. EXPECT_EQ("text/plain", file.content_type);
  5353. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5354. }
  5355. {
  5356. const auto &file = get_file_value(items, "file2");
  5357. EXPECT_EQ("world.json", file.filename);
  5358. EXPECT_EQ("application/json", file.content_type);
  5359. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5360. }
  5361. {
  5362. const auto &file = get_file_value(items, "file3");
  5363. EXPECT_TRUE(file.filename.empty());
  5364. EXPECT_EQ("application/octet-stream", file.content_type);
  5365. EXPECT_EQ(0u, file.content.size());
  5366. }
  5367. } else {
  5368. std::string body;
  5369. content_reader([&](const char *data, size_t data_length) {
  5370. EXPECT_EQ(7U, data_length);
  5371. body.append(data, data_length);
  5372. return true;
  5373. });
  5374. EXPECT_EQ(body, "content");
  5375. res.set_content(body, "text/plain");
  5376. }
  5377. })
  5378. .Put("/content_receiver",
  5379. [&](const Request & /*req*/, Response &res,
  5380. const ContentReader &content_reader) {
  5381. std::string body;
  5382. content_reader([&](const char *data, size_t data_length) {
  5383. body.append(data, data_length);
  5384. return true;
  5385. });
  5386. EXPECT_EQ(body, "content");
  5387. res.set_content(body, "text/plain");
  5388. })
  5389. .Patch("/content_receiver",
  5390. [&](const Request & /*req*/, Response &res,
  5391. const ContentReader &content_reader) {
  5392. std::string body;
  5393. content_reader([&](const char *data, size_t data_length) {
  5394. body.append(data, data_length);
  5395. return true;
  5396. });
  5397. EXPECT_EQ(body, "content");
  5398. res.set_content(body, "text/plain");
  5399. })
  5400. .Post("/query-string-and-body",
  5401. [&](const Request &req, Response & /*res*/) {
  5402. ASSERT_TRUE(req.has_param("key"));
  5403. EXPECT_EQ(req.get_param_value("key"), "value");
  5404. EXPECT_EQ(req.body, "content");
  5405. })
  5406. .Get("/last-request",
  5407. [&](const Request &req, Response & /*res*/) {
  5408. EXPECT_EQ("close", req.get_header_value("Connection"));
  5409. })
  5410. .Get(R"(/redirect/(\d+))",
  5411. [&](const Request &req, Response &res) {
  5412. auto num = std::stoi(req.matches[1]) + 1;
  5413. std::string url = "/redirect/" + std::to_string(num);
  5414. res.set_redirect(url);
  5415. })
  5416. .Post("/binary",
  5417. [&](const Request &req, Response &res) {
  5418. EXPECT_EQ(4U, req.body.size());
  5419. EXPECT_EQ("application/octet-stream",
  5420. req.get_header_value("Content-Type"));
  5421. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5422. res.set_content(req.body, "application/octet-stream");
  5423. })
  5424. .Put("/binary",
  5425. [&](const Request &req, Response &res) {
  5426. EXPECT_EQ(4U, req.body.size());
  5427. EXPECT_EQ("application/octet-stream",
  5428. req.get_header_value("Content-Type"));
  5429. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5430. res.set_content(req.body, "application/octet-stream");
  5431. })
  5432. .Patch("/binary",
  5433. [&](const Request &req, Response &res) {
  5434. EXPECT_EQ(4U, req.body.size());
  5435. EXPECT_EQ("application/octet-stream",
  5436. req.get_header_value("Content-Type"));
  5437. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5438. res.set_content(req.body, "application/octet-stream");
  5439. })
  5440. .Delete("/binary",
  5441. [&](const Request &req, Response &res) {
  5442. EXPECT_EQ(4U, req.body.size());
  5443. EXPECT_EQ("application/octet-stream",
  5444. req.get_header_value("Content-Type"));
  5445. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5446. res.set_content(req.body, "application/octet-stream");
  5447. })
  5448. .Get("/issue1772",
  5449. [&](const Request & /*req*/, Response &res) {
  5450. res.status = 401;
  5451. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5452. })
  5453. .Delete("/issue609",
  5454. [](const httplib::Request &, httplib::Response &res,
  5455. const httplib::ContentReader &) {
  5456. res.set_content("ok", "text/plain");
  5457. })
  5458. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5459. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5460. .Get("/compress",
  5461. [&](const Request & /*req*/, Response &res) {
  5462. res.set_content(
  5463. "12345678901234567890123456789012345678901234567890123456789"
  5464. "01234567890123456789012345678901234567890",
  5465. "text/plain");
  5466. })
  5467. .Get("/compress-with-charset",
  5468. [&](const Request & /*req*/, Response &res) {
  5469. res.set_content(
  5470. "12345678901234567890123456789012345678901234567890123456789"
  5471. "01234567890123456789012345678901234567890",
  5472. "application/json; charset=utf-8");
  5473. })
  5474. .Get("/nocompress",
  5475. [&](const Request & /*req*/, Response &res) {
  5476. res.set_content(
  5477. "12345678901234567890123456789012345678901234567890123456789"
  5478. "01234567890123456789012345678901234567890",
  5479. "application/octet-stream");
  5480. })
  5481. .Post("/compress-multipart",
  5482. [&](const Request &req, Response & /*res*/) {
  5483. EXPECT_EQ(2u, req.form.fields.size());
  5484. ASSERT_TRUE(!req.form.has_field("???"));
  5485. {
  5486. const auto &text = req.form.get_field("key1");
  5487. EXPECT_EQ("test", text);
  5488. }
  5489. {
  5490. const auto &text = req.form.get_field("key2");
  5491. EXPECT_EQ("--abcdefg123", text);
  5492. }
  5493. })
  5494. #endif
  5495. ;
  5496. persons_["john"] = "programmer";
  5497. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5498. svr_.wait_until_ready();
  5499. }
  5500. virtual void TearDown() {
  5501. svr_.stop();
  5502. if (!request_threads_.empty()) {
  5503. std::this_thread::sleep_for(std::chrono::seconds(1));
  5504. for (auto &t : request_threads_) {
  5505. t.join();
  5506. }
  5507. }
  5508. t_.join();
  5509. }
  5510. map<string, string> persons_;
  5511. #ifdef CPPHTTPLIB_SSL_ENABLED
  5512. SSLClient cli_;
  5513. SSLServer svr_;
  5514. #else
  5515. Client cli_;
  5516. Server svr_;
  5517. #endif
  5518. thread t_;
  5519. std::vector<thread> request_threads_;
  5520. };
  5521. TEST_F(ServerTest, GetMethod200) {
  5522. auto res = cli_.Get("/hi");
  5523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5524. EXPECT_EQ("HTTP/1.1", res->version);
  5525. EXPECT_EQ(StatusCode::OK_200, res->status);
  5526. EXPECT_EQ("OK", res->reason);
  5527. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5528. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5529. EXPECT_EQ("Hello World!", res->body);
  5530. }
  5531. TEST_F(ServerTest, GetEmptyFile) {
  5532. auto res = cli_.Get("/empty_file");
  5533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5534. EXPECT_EQ(StatusCode::OK_200, res->status);
  5535. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5536. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5537. EXPECT_EQ("", res->body);
  5538. }
  5539. TEST_F(ServerTest, GetFileContent) {
  5540. auto res = cli_.Get("/file_content");
  5541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5542. EXPECT_EQ(StatusCode::OK_200, res->status);
  5543. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5544. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5545. EXPECT_EQ("test.html", res->body);
  5546. }
  5547. TEST_F(ServerTest, GetFileContentWithRange) {
  5548. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5550. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5551. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5552. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5553. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5554. EXPECT_EQ("est", res->body);
  5555. }
  5556. TEST_F(ServerTest, GetFileContentWithContentType) {
  5557. auto res = cli_.Get("/file_content_with_content_type");
  5558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5559. EXPECT_EQ(StatusCode::OK_200, res->status);
  5560. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5561. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5562. EXPECT_EQ("file\n", res->body);
  5563. }
  5564. TEST_F(ServerTest, GetInvalidFileContent) {
  5565. auto res = cli_.Get("/invalid_file_content");
  5566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5567. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5568. }
  5569. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5570. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5572. EXPECT_EQ("HTTP/1.1", res->version);
  5573. EXPECT_EQ(StatusCode::OK_200, res->status);
  5574. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5575. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5576. EXPECT_EQ("Hello World!", res->body);
  5577. }
  5578. TEST_F(ServerTest, GetMethod302) {
  5579. auto res = cli_.Get("/");
  5580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5581. EXPECT_EQ(StatusCode::Found_302, res->status);
  5582. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5583. }
  5584. TEST_F(ServerTest, GetMethod302Redirect) {
  5585. cli_.set_follow_location(true);
  5586. auto res = cli_.Get("/");
  5587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5588. EXPECT_EQ(StatusCode::OK_200, res->status);
  5589. EXPECT_EQ("Hello World!", res->body);
  5590. EXPECT_EQ("/hi", res->location);
  5591. }
  5592. TEST_F(ServerTest, GetMethod404) {
  5593. auto res = cli_.Get("/invalid");
  5594. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5595. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5596. }
  5597. TEST_F(ServerTest, HeadMethod200) {
  5598. auto res = cli_.Head("/hi");
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. EXPECT_EQ(StatusCode::OK_200, res->status);
  5601. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5602. EXPECT_TRUE(res->body.empty());
  5603. }
  5604. TEST_F(ServerTest, HeadMethod200Static) {
  5605. auto res = cli_.Head("/mount/dir/index.html");
  5606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5607. EXPECT_EQ(StatusCode::OK_200, res->status);
  5608. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5609. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5610. EXPECT_TRUE(res->body.empty());
  5611. }
  5612. TEST_F(ServerTest, HeadMethod404) {
  5613. auto res = cli_.Head("/invalid");
  5614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5615. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5616. EXPECT_TRUE(res->body.empty());
  5617. }
  5618. TEST_F(ServerTest, GetMethodPersonJohn) {
  5619. auto res = cli_.Get("/person/john");
  5620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5621. EXPECT_EQ(StatusCode::OK_200, res->status);
  5622. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5623. EXPECT_EQ("programmer", res->body);
  5624. }
  5625. TEST_F(ServerTest, PostMethod1) {
  5626. auto res = cli_.Get("/person/john1");
  5627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5628. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5629. res = cli_.Post("/person", "name=john1&note=coder",
  5630. "application/x-www-form-urlencoded");
  5631. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5632. ASSERT_EQ(StatusCode::OK_200, res->status);
  5633. res = cli_.Get("/person/john1");
  5634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5635. ASSERT_EQ(StatusCode::OK_200, res->status);
  5636. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5637. ASSERT_EQ("coder", res->body);
  5638. }
  5639. TEST_F(ServerTest, PostMethod2) {
  5640. auto res = cli_.Get("/person/john2");
  5641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5642. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5643. Params params;
  5644. params.emplace("name", "john2");
  5645. params.emplace("note", "coder");
  5646. res = cli_.Post("/person", params);
  5647. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5648. ASSERT_EQ(StatusCode::OK_200, res->status);
  5649. res = cli_.Get("/person/john2");
  5650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5651. ASSERT_EQ(StatusCode::OK_200, res->status);
  5652. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5653. ASSERT_EQ("coder", res->body);
  5654. }
  5655. TEST_F(ServerTest, PutMethod3) {
  5656. auto res = cli_.Get("/person/john3");
  5657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5658. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5659. Params params;
  5660. params.emplace("name", "john3");
  5661. params.emplace("note", "coder");
  5662. res = cli_.Put("/person", params);
  5663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5664. ASSERT_EQ(StatusCode::OK_200, res->status);
  5665. res = cli_.Get("/person/john3");
  5666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5667. ASSERT_EQ(StatusCode::OK_200, res->status);
  5668. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5669. ASSERT_EQ("coder", res->body);
  5670. }
  5671. TEST_F(ServerTest, DeleteMethod1) {
  5672. auto res = cli_.Get("/person/john4");
  5673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5674. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5675. Params params;
  5676. params.emplace("name", "john4");
  5677. params.emplace("note", "coder");
  5678. res = cli_.Post("/person", params);
  5679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5680. ASSERT_EQ(StatusCode::OK_200, res->status);
  5681. res = cli_.Get("/person/john4");
  5682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5683. ASSERT_EQ(StatusCode::OK_200, res->status);
  5684. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5685. ASSERT_EQ("coder", res->body);
  5686. Params delete_params;
  5687. delete_params.emplace("name", "john4");
  5688. res = cli_.Delete("/person", delete_params);
  5689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5690. ASSERT_EQ(StatusCode::OK_200, res->status);
  5691. ASSERT_EQ("DELETED", res->body);
  5692. res = cli_.Get("/person/john4");
  5693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5694. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5695. }
  5696. TEST_F(ServerTest, DeleteMethod2) {
  5697. auto res = cli_.Get("/person/john5");
  5698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5699. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5700. Params params;
  5701. params.emplace("name", "john5");
  5702. params.emplace("note", "developer");
  5703. res = cli_.Post("/person", params);
  5704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5705. ASSERT_EQ(StatusCode::OK_200, res->status);
  5706. res = cli_.Get("/person/john5");
  5707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5708. ASSERT_EQ(StatusCode::OK_200, res->status);
  5709. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5710. ASSERT_EQ("developer", res->body);
  5711. Params delete_params;
  5712. delete_params.emplace("name", "john5");
  5713. Headers headers;
  5714. headers.emplace("Custom-Header", "test-value");
  5715. res = cli_.Delete("/person", headers, delete_params);
  5716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5717. ASSERT_EQ(StatusCode::OK_200, res->status);
  5718. ASSERT_EQ("DELETED", res->body);
  5719. res = cli_.Get("/person/john5");
  5720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5721. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5722. }
  5723. TEST_F(ServerTest, DeleteMethod3) {
  5724. auto res = cli_.Get("/person/john6");
  5725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5726. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5727. Params params;
  5728. params.emplace("name", "john6");
  5729. params.emplace("note", "tester");
  5730. res = cli_.Post("/person", params);
  5731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5732. ASSERT_EQ(StatusCode::OK_200, res->status);
  5733. res = cli_.Get("/person/john6");
  5734. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5735. ASSERT_EQ(StatusCode::OK_200, res->status);
  5736. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5737. ASSERT_EQ("tester", res->body);
  5738. Params delete_params;
  5739. delete_params.emplace("name", "john6");
  5740. Headers headers;
  5741. headers.emplace("Custom-Header", "test-value");
  5742. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5744. ASSERT_EQ(StatusCode::OK_200, res->status);
  5745. ASSERT_EQ("DELETED", res->body);
  5746. res = cli_.Get("/person/john6");
  5747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5748. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5749. }
  5750. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5751. Params params;
  5752. params.emplace("json", JSON_DATA);
  5753. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5755. ASSERT_EQ(StatusCode::OK_200, res->status);
  5756. ASSERT_EQ(JSON_DATA, res->body);
  5757. }
  5758. TEST_F(ServerTest, PostEmptyContent) {
  5759. auto res = cli_.Post("/empty", "", "text/plain");
  5760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5761. ASSERT_EQ(StatusCode::OK_200, res->status);
  5762. ASSERT_EQ("empty", res->body);
  5763. }
  5764. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5765. auto res = cli_.Post("/empty-no-content-type");
  5766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5767. ASSERT_EQ(StatusCode::OK_200, res->status);
  5768. ASSERT_EQ("empty-no-content-type", res->body);
  5769. }
  5770. TEST_F(ServerTest, PostPathOnly) {
  5771. auto res = cli_.Post("/path-only");
  5772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5773. ASSERT_EQ(StatusCode::OK_200, res->status);
  5774. ASSERT_EQ("path-only", res->body);
  5775. }
  5776. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5777. auto res = cli_.Post("/path-headers-only",
  5778. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5779. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5780. ASSERT_EQ(StatusCode::OK_200, res->status);
  5781. ASSERT_EQ("path-headers-only", res->body);
  5782. }
  5783. TEST_F(ServerTest, PostLarge) {
  5784. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5786. ASSERT_EQ(StatusCode::OK_200, res->status);
  5787. EXPECT_EQ(LARGE_DATA, res->body);
  5788. }
  5789. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5790. auto res = cli_.Put("/empty-no-content-type");
  5791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5792. ASSERT_EQ(StatusCode::OK_200, res->status);
  5793. ASSERT_EQ("empty-no-content-type", res->body);
  5794. }
  5795. TEST_F(ServerTest, GetMethodDir) {
  5796. auto res = cli_.Get("/dir/");
  5797. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5798. EXPECT_EQ(StatusCode::OK_200, res->status);
  5799. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5800. auto body = R"(<html>
  5801. <head>
  5802. </head>
  5803. <body>
  5804. <a href="/dir/test.html">Test</a>
  5805. <a href="/hi">hi</a>
  5806. </body>
  5807. </html>
  5808. )";
  5809. EXPECT_EQ(body, res->body);
  5810. }
  5811. TEST_F(ServerTest, GetMethodDirTest) {
  5812. auto res = cli_.Get("/dir/test.html");
  5813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5814. EXPECT_EQ(StatusCode::OK_200, res->status);
  5815. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5816. EXPECT_EQ("test.html", res->body);
  5817. }
  5818. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5819. auto res = cli_.Get("/dir/../dir/test.html");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::OK_200, res->status);
  5822. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5823. EXPECT_EQ("test.html", res->body);
  5824. }
  5825. TEST_F(ServerTest, GetMethodInvalidPath) {
  5826. auto res = cli_.Get("/dir/../test.html");
  5827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5828. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5829. }
  5830. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5831. auto res = cli_.Get("/../www/dir/test.html");
  5832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5833. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5834. }
  5835. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5836. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5838. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5839. }
  5840. TEST_F(ServerTest, GetMethodDirMountTest) {
  5841. auto res = cli_.Get("/mount/dir/test.html");
  5842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5843. EXPECT_EQ(StatusCode::OK_200, res->status);
  5844. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5845. EXPECT_EQ("test.html", res->body);
  5846. }
  5847. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5848. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5850. EXPECT_EQ(StatusCode::OK_200, res->status);
  5851. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5852. EXPECT_EQ("test.html", res->body);
  5853. }
  5854. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5855. auto res = cli_.Get("/mount/dir/../test.html");
  5856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5857. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5858. }
  5859. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5860. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5862. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5863. }
  5864. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5865. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5867. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5868. }
  5869. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5870. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5872. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5873. }
  5874. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5875. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5877. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5878. }
  5879. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  5880. auto res = cli_.Get("/mount/dir");
  5881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5882. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5883. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5884. }
  5885. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  5886. auto res = cli_.Get("//dir");
  5887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5888. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  5889. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  5890. }
  5891. TEST_F(ServerTest, PostMethod303) {
  5892. auto res = cli_.Post("/1", "body", "text/plain");
  5893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5894. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5895. EXPECT_EQ("/2", res->get_header_value("Location"));
  5896. }
  5897. TEST_F(ServerTest, PostMethod303Redirect) {
  5898. cli_.set_follow_location(true);
  5899. auto res = cli_.Post("/1", "body", "text/plain");
  5900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5901. EXPECT_EQ(StatusCode::OK_200, res->status);
  5902. EXPECT_EQ("redirected.", res->body);
  5903. EXPECT_EQ("/2", res->location);
  5904. }
  5905. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5906. auto res = cli_.Get("/dir/test.abcde");
  5907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5908. EXPECT_EQ(StatusCode::OK_200, res->status);
  5909. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5910. EXPECT_EQ("abcde", res->body);
  5911. }
  5912. TEST_F(ServerTest, StaticFileRange) {
  5913. auto res =
  5914. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5916. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5917. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5918. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5919. EXPECT_EQ(true, res->has_header("Content-Range"));
  5920. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5921. EXPECT_EQ(std::string("cd"), res->body);
  5922. }
  5923. TEST_F(ServerTest, StaticFileRanges) {
  5924. auto res = cli_.Get("/dir/test.abcde",
  5925. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5927. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5928. EXPECT_TRUE(
  5929. res->get_header_value("Content-Type")
  5930. .find(
  5931. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5932. 0);
  5933. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5934. }
  5935. TEST_F(ServerTest, StaticFileRangeHead) {
  5936. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5938. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5939. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5940. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5941. EXPECT_EQ(true, res->has_header("Content-Range"));
  5942. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5943. }
  5944. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5945. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5947. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5948. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5949. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5950. EXPECT_EQ(true, res->has_header("Content-Range"));
  5951. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5952. res->get_header_value("Content-Range"));
  5953. EXPECT_EQ("LAST\n", res->body);
  5954. }
  5955. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5956. auto res =
  5957. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5959. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5960. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5961. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5962. EXPECT_EQ(true, res->has_header("Content-Range"));
  5963. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5964. }
  5965. TEST_F(ServerTest, StaticFileBigFile) {
  5966. auto res = cli_.Get("/dir/1MB.txt");
  5967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5968. EXPECT_EQ(StatusCode::OK_200, res->status);
  5969. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5970. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5971. }
  5972. TEST_F(ServerTest, InvalidBaseDirMount) {
  5973. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5974. }
  5975. TEST_F(ServerTest, Binary) {
  5976. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5977. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5978. "application/octet-stream");
  5979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5980. ASSERT_EQ(StatusCode::OK_200, res->status);
  5981. ASSERT_EQ(4U, res->body.size());
  5982. res = cli_.Put("/binary", binary.data(), binary.size(),
  5983. "application/octet-stream");
  5984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5985. ASSERT_EQ(StatusCode::OK_200, res->status);
  5986. ASSERT_EQ(4U, res->body.size());
  5987. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5988. "application/octet-stream");
  5989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5990. ASSERT_EQ(StatusCode::OK_200, res->status);
  5991. ASSERT_EQ(4U, res->body.size());
  5992. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5993. "application/octet-stream");
  5994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5995. ASSERT_EQ(StatusCode::OK_200, res->status);
  5996. ASSERT_EQ(4U, res->body.size());
  5997. }
  5998. TEST_F(ServerTest, BinaryString) {
  5999. auto binary = std::string("\x00\x01\x02\x03", 4);
  6000. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. ASSERT_EQ(StatusCode::OK_200, res->status);
  6003. ASSERT_EQ(4U, res->body.size());
  6004. res = cli_.Put("/binary", binary, "application/octet-stream");
  6005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6006. ASSERT_EQ(StatusCode::OK_200, res->status);
  6007. ASSERT_EQ(4U, res->body.size());
  6008. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6010. ASSERT_EQ(StatusCode::OK_200, res->status);
  6011. ASSERT_EQ(4U, res->body.size());
  6012. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6014. ASSERT_EQ(StatusCode::OK_200, res->status);
  6015. ASSERT_EQ(4U, res->body.size());
  6016. }
  6017. TEST_F(ServerTest, EmptyRequest) {
  6018. auto res = cli_.Get("");
  6019. ASSERT_TRUE(!res);
  6020. EXPECT_EQ(Error::Connection, res.error());
  6021. }
  6022. TEST_F(ServerTest, LongRequest) {
  6023. std::string request;
  6024. for (size_t i = 0; i < 545; i++) {
  6025. request += "/TooLongRequest";
  6026. }
  6027. request += "OK";
  6028. auto res = cli_.Get(request.c_str());
  6029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6030. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6031. }
  6032. TEST_F(ServerTest, TooLongRequest) {
  6033. std::string request;
  6034. for (size_t i = 0; i < 546; i++) {
  6035. request += "/TooLongRequest";
  6036. }
  6037. request += "_NG";
  6038. auto start = std::chrono::high_resolution_clock::now();
  6039. cli_.set_keep_alive(true);
  6040. auto res = cli_.Get(request.c_str());
  6041. auto end = std::chrono::high_resolution_clock::now();
  6042. auto elapsed =
  6043. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6044. .count();
  6045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6046. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6047. EXPECT_LE(elapsed, 1000);
  6048. EXPECT_EQ("close", res->get_header_value("Connection"));
  6049. EXPECT_FALSE(cli_.is_socket_open());
  6050. }
  6051. TEST_F(ServerTest, AlmostTooLongRequest) {
  6052. // test for #2046 - URI length check shouldn't include other content on req
  6053. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6054. // leading /, space, HTTP/1.1)
  6055. std::string request =
  6056. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6057. auto res = cli_.Get(request.c_str());
  6058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6059. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6060. }
  6061. TEST_F(ServerTest, LongHeader) {
  6062. Request req;
  6063. req.method = "GET";
  6064. req.path = "/hi";
  6065. std::string host_and_port;
  6066. host_and_port += HOST;
  6067. host_and_port += ":";
  6068. host_and_port += std::to_string(PORT);
  6069. req.headers.emplace("Host", host_and_port.c_str());
  6070. req.headers.emplace("Accept", "*/*");
  6071. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6072. req.headers.emplace(
  6073. "Header-Name",
  6074. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6075. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6076. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6077. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6078. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6079. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6080. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6081. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6082. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6083. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6084. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6085. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6086. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6087. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6088. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6089. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6090. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6091. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6092. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6093. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6094. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6095. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6096. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6097. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6098. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6099. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6100. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6101. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6102. "@@@@@@@@@@@@@@@@");
  6103. auto res = std::make_shared<Response>();
  6104. auto error = Error::Success;
  6105. auto ret = cli_.send(req, *res, error);
  6106. ASSERT_TRUE(ret);
  6107. EXPECT_EQ(StatusCode::OK_200, res->status);
  6108. }
  6109. TEST_F(ServerTest, LongQueryValue) {
  6110. auto start = std::chrono::high_resolution_clock::now();
  6111. cli_.set_keep_alive(true);
  6112. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6113. auto end = std::chrono::high_resolution_clock::now();
  6114. auto elapsed =
  6115. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6116. .count();
  6117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6118. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6119. EXPECT_LE(elapsed, 1000);
  6120. EXPECT_EQ("close", res->get_header_value("Connection"));
  6121. EXPECT_FALSE(cli_.is_socket_open());
  6122. }
  6123. TEST_F(ServerTest, TooLongQueryValue) {
  6124. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6125. ASSERT_FALSE(res);
  6126. EXPECT_EQ(Error::Read, res.error());
  6127. }
  6128. TEST_F(ServerTest, TooLongHeader) {
  6129. Request req;
  6130. req.method = "GET";
  6131. req.path = "/hi";
  6132. std::string host_and_port;
  6133. host_and_port += HOST;
  6134. host_and_port += ":";
  6135. host_and_port += std::to_string(PORT);
  6136. req.headers.emplace("Host", host_and_port.c_str());
  6137. req.headers.emplace("Accept", "*/*");
  6138. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6139. req.headers.emplace(
  6140. "Header-Name",
  6141. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6142. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6143. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6144. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6145. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6146. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6147. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6148. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6149. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6150. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6151. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6152. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6153. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6154. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6155. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6156. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6157. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6158. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6159. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6160. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6161. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6162. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6163. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6164. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6165. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6166. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6167. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6168. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6169. "@@@@@@@@@@@@@@@@@");
  6170. auto res = std::make_shared<Response>();
  6171. auto error = Error::Success;
  6172. auto ret = cli_.send(req, *res, error);
  6173. ASSERT_TRUE(ret);
  6174. EXPECT_EQ(StatusCode::OK_200, res->status);
  6175. }
  6176. TEST_F(ServerTest, HeaderCountAtLimit) {
  6177. // Test with headers just under the 100 limit
  6178. httplib::Headers headers;
  6179. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6180. // This should keep us just under the 100 header limit
  6181. for (int i = 0; i < 95; i++) {
  6182. std::string name = "X-Test-Header-" + std::to_string(i);
  6183. std::string value = "value" + std::to_string(i);
  6184. headers.emplace(name, value);
  6185. }
  6186. // This should work fine as we're under the limit
  6187. auto res = cli_.Get("/hi", headers);
  6188. EXPECT_TRUE(res);
  6189. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6190. }
  6191. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6192. // Test with many headers to exceed the 100 limit
  6193. httplib::Headers headers;
  6194. // Add 150 headers to definitely exceed the 100 limit
  6195. for (int i = 0; i < 150; i++) {
  6196. std::string name = "X-Test-Header-" + std::to_string(i);
  6197. std::string value = "value" + std::to_string(i);
  6198. headers.emplace(name, value);
  6199. }
  6200. // This should fail due to exceeding header count limit
  6201. cli_.set_keep_alive(true);
  6202. auto res = cli_.Get("/hi", headers);
  6203. // The server should respond with 400 Bad Request
  6204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6205. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6206. EXPECT_EQ("close", res->get_header_value("Connection"));
  6207. EXPECT_FALSE(cli_.is_socket_open());
  6208. }
  6209. TEST_F(ServerTest, PercentEncoding) {
  6210. auto res = cli_.Get("/e%6edwith%");
  6211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6212. EXPECT_EQ(StatusCode::OK_200, res->status);
  6213. }
  6214. TEST_F(ServerTest, PercentEncodingUnicode) {
  6215. auto res = cli_.Get("/e%u006edwith%");
  6216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6217. EXPECT_EQ(StatusCode::OK_200, res->status);
  6218. }
  6219. TEST_F(ServerTest, InvalidPercentEncoding) {
  6220. auto res = cli_.Get("/%endwith%");
  6221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6222. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6223. }
  6224. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6225. auto res = cli_.Get("/%uendwith%");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6228. }
  6229. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6230. auto res = cli_.Get("/hello?aaa=bbb%");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6233. }
  6234. TEST_F(ServerTest, PlusSignEncoding) {
  6235. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6237. EXPECT_EQ(StatusCode::OK_200, res->status);
  6238. EXPECT_EQ("a +b", res->body);
  6239. }
  6240. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6241. // This test simulates a potential DoS attack using many headers
  6242. // to verify our security fix prevents memory exhaustion
  6243. httplib::Headers attack_headers;
  6244. // Attempt to add many headers like an attacker would (200 headers to far
  6245. // exceed limit)
  6246. for (int i = 0; i < 200; i++) {
  6247. std::string name = "X-Attack-Header-" + std::to_string(i);
  6248. std::string value = "attack_payload_" + std::to_string(i);
  6249. attack_headers.emplace(name, value);
  6250. }
  6251. // Try to POST with excessive headers
  6252. cli_.set_keep_alive(true);
  6253. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6254. // Should either fail or return 400 Bad Request due to security limit
  6255. if (res) {
  6256. // If we get a response, it should be 400 Bad Request
  6257. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6258. EXPECT_EQ("close", res->get_header_value("Connection"));
  6259. }
  6260. EXPECT_FALSE(cli_.is_socket_open());
  6261. }
  6262. TEST_F(ServerTest, MultipartFormData) {
  6263. UploadFormDataItems items = {
  6264. {"text1", "text default", "", ""},
  6265. {"text2", "aωb", "", ""},
  6266. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6267. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6268. {"file3", "", "", "application/octet-stream"},
  6269. {"file4", "", "", " application/json tmp-string "}};
  6270. auto res = cli_.Post("/multipart", items);
  6271. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6272. EXPECT_EQ(StatusCode::OK_200, res->status);
  6273. }
  6274. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6275. UploadFormDataItems items = {
  6276. {"text", "default text", "", ""},
  6277. {"multi_text1", "aaaaa", "", ""},
  6278. {"multi_text1", "bbbbb", "", ""},
  6279. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6280. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6281. "application/json"},
  6282. };
  6283. auto res = cli_.Post("/multipart/multi_file_values", items);
  6284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6285. EXPECT_EQ(StatusCode::OK_200, res->status);
  6286. }
  6287. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6288. auto res = cli_.Get("/hi");
  6289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6290. EXPECT_EQ(StatusCode::OK_200, res->status);
  6291. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6292. EXPECT_EQ("Hello World!", res->body);
  6293. }
  6294. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6295. Request req;
  6296. req.method = "POST";
  6297. req.path = "/chunked";
  6298. std::string host_and_port;
  6299. host_and_port += HOST;
  6300. host_and_port += ":";
  6301. host_and_port += std::to_string(PORT);
  6302. req.headers.emplace("Host", host_and_port.c_str());
  6303. req.headers.emplace("Accept", "*/*");
  6304. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6305. req.headers.emplace("Content-Type", "text/plain");
  6306. req.headers.emplace("Content-Length", "0");
  6307. req.headers.emplace(
  6308. "Transfer-Encoding",
  6309. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6310. // Client does not chunk, so make a chunked body manually.
  6311. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6312. auto res = std::make_shared<Response>();
  6313. auto error = Error::Success;
  6314. auto ret = cli_.send(req, *res, error);
  6315. ASSERT_TRUE(ret);
  6316. EXPECT_EQ(StatusCode::OK_200, res->status);
  6317. }
  6318. template <typename ClientT>
  6319. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6320. int expected_status) {
  6321. Request req;
  6322. req.method = "POST";
  6323. req.path = "/chunked";
  6324. std::string host_and_port;
  6325. host_and_port += HOST;
  6326. host_and_port += ":";
  6327. host_and_port += std::to_string(PORT);
  6328. req.headers.emplace("Host", host_and_port.c_str());
  6329. req.headers.emplace("Content-Length", "0");
  6330. req.headers.emplace("Transfer-Encoding", "chunked");
  6331. req.body = body;
  6332. auto res = std::make_shared<Response>();
  6333. auto error = Error::Success;
  6334. ASSERT_TRUE(cli.send(req, *res, error));
  6335. EXPECT_EQ(expected_status, res->status);
  6336. }
  6337. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6338. // rather than treat them as valid lengths.
  6339. template <typename ClientT>
  6340. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6341. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6342. }
  6343. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6344. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6345. }
  6346. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6347. expect_chunked_body_rejected(
  6348. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6349. }
  6350. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6351. // chunk-size line carries no CR, LF or other control character ahead of its
  6352. // terminator. Such a line must be refused rather than read as extension text.
  6353. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6354. expect_chunked_body_rejected(
  6355. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6356. }
  6357. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6358. expect_chunked_body_rejected(
  6359. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6360. }
  6361. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6362. expect_chunked_body_rejected(
  6363. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6364. }
  6365. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6366. // The literal stays split: a hex escape consumes every hex digit that
  6367. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6368. expect_chunked_body_rejected(
  6369. cli_, "4;a\x01"
  6370. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6371. }
  6372. TEST_F(ServerTest, AcceptsChunkExtension) {
  6373. expect_chunked_body_status(cli_,
  6374. "4;name=value\r\ndech\r\n"
  6375. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6376. "0;last\r\n\r\n",
  6377. StatusCode::OK_200);
  6378. }
  6379. TEST_F(ServerTest, GetStreamed2) {
  6380. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6382. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6383. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6384. EXPECT_EQ(true, res->has_header("Content-Range"));
  6385. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6386. EXPECT_EQ(std::string("ab"), res->body);
  6387. }
  6388. TEST_F(ServerTest, GetStreamed) {
  6389. auto res = cli_.Get("/streamed");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::OK_200, res->status);
  6392. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6393. EXPECT_EQ(std::string("aaabbb"), res->body);
  6394. }
  6395. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6396. auto res = cli_.Get("/streamed-without-length",
  6397. Headers{make_range_header({{0, -1}})});
  6398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6399. EXPECT_EQ(StatusCode::OK_200, res->status);
  6400. EXPECT_EQ(false, res->has_header("Content-Length"));
  6401. EXPECT_EQ(false, res->has_header("Content-Range"));
  6402. EXPECT_EQ(std::string("abcdefg"), res->body);
  6403. }
  6404. TEST_F(ServerTest, GetStreamedWithRange1) {
  6405. auto res =
  6406. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6408. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6409. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6410. EXPECT_EQ(true, res->has_header("Content-Range"));
  6411. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6412. EXPECT_EQ(std::string("def"), res->body);
  6413. }
  6414. TEST_F(ServerTest, GetStreamedWithRange2) {
  6415. auto res =
  6416. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6418. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6419. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6420. EXPECT_EQ(true, res->has_header("Content-Range"));
  6421. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6422. EXPECT_EQ(std::string("bcdefg"), res->body);
  6423. }
  6424. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6425. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6427. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6428. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6429. EXPECT_EQ(true, res->has_header("Content-Range"));
  6430. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6431. EXPECT_EQ(std::string("efg"), res->body);
  6432. }
  6433. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6434. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6435. // the entire representation.
  6436. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6437. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6439. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6440. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6441. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6442. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6443. }
  6444. }
  6445. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6446. auto res =
  6447. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6449. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6450. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6451. EXPECT_EQ(false, res->has_header("Content-Range"));
  6452. EXPECT_EQ(0U, res->body.size());
  6453. }
  6454. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6455. // Only a 206 is served as a partial representation. Under any other status
  6456. // `apply_ranges()` reported the full content length, so the body must match
  6457. // that header, and the content provider must never be asked for an offset
  6458. // outside the representation.
  6459. auto check = [&](int status, const char *range) {
  6460. auto path =
  6461. std::string("/streamed-with-range?status=") + std::to_string(status);
  6462. auto ctx = path + " Range: " + range;
  6463. auto res = cli_.Get(path, Headers{{"Range", range}});
  6464. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6465. EXPECT_EQ(status, res->status) << ctx;
  6466. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6467. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6468. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6469. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6470. };
  6471. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6472. check(403, "bytes=3-5");
  6473. // The offset is far past the representation.
  6474. check(403, "bytes=100000-100200");
  6475. // `first_pos` is still -1 here, and the bounds asserts in
  6476. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6477. check(403, "bytes=-3");
  6478. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6479. // multipart branch would have written one that is empty.
  6480. check(403, "bytes=1-2, 4-5");
  6481. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6482. // covers the whole representation.
  6483. check(200, "bytes=3-5");
  6484. check(200, "bytes=1-2, 4-5");
  6485. }
  6486. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6487. auto res =
  6488. cli_.Get("/streamed-with-range",
  6489. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6490. "92233720368547758079223372036854775807"}});
  6491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6492. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6493. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6494. EXPECT_EQ(false, res->has_header("Content-Range"));
  6495. EXPECT_EQ(0U, res->body.size());
  6496. }
  6497. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6498. auto res = cli_.Get(
  6499. "/with-range",
  6500. Headers{{"Range",
  6501. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6502. {"Accept-Encoding", ""}});
  6503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6504. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6505. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6506. EXPECT_EQ(true, res->has_header("Content-Range"));
  6507. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6508. EXPECT_EQ(std::string("abcdefg"), res->body);
  6509. }
  6510. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6511. auto res = cli_.Get("/with-range", Headers{
  6512. {"Range", "bytes=0-"},
  6513. {"Accept-Encoding", ""},
  6514. });
  6515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6516. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6517. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6518. EXPECT_EQ(true, res->has_header("Content-Range"));
  6519. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6520. EXPECT_EQ(std::string("abcdefg"), res->body);
  6521. }
  6522. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6523. auto res = cli_.Get("/streamed-with-range",
  6524. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6526. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6527. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6528. EXPECT_EQ(false, res->has_header("Content-Range"));
  6529. EXPECT_EQ(267U, res->body.size());
  6530. // Check that both range contents are present
  6531. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6532. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6533. // Check that Content-Range headers are present for both ranges
  6534. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6535. std::string::npos);
  6536. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6537. std::string::npos);
  6538. }
  6539. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6540. Ranges ranges;
  6541. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6542. ranges.emplace_back(0, -1);
  6543. }
  6544. auto res = cli_.Get("/streamed-with-range?error",
  6545. Headers{{make_range_header(ranges)}});
  6546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6547. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6548. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6549. EXPECT_EQ(false, res->has_header("Content-Range"));
  6550. EXPECT_EQ(0U, res->body.size());
  6551. }
  6552. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6553. auto res = cli_.Get("/streamed-with-range",
  6554. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6555. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6556. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6557. EXPECT_EQ(5U, res->body.size());
  6558. // Check that overlapping ranges are coalesced into a single range
  6559. EXPECT_EQ("bcdef", res->body);
  6560. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6561. // Should be single range, not multipart
  6562. EXPECT_TRUE(res->has_header("Content-Range"));
  6563. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6564. }
  6565. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6566. auto res = cli_.Get("/streamed-with-range",
  6567. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6569. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6570. EXPECT_EQ(268U, res->body.size());
  6571. // Check that both range contents are present
  6572. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6573. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6574. // Check that Content-Range headers are present for both ranges
  6575. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6576. std::string::npos);
  6577. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6578. std::string::npos);
  6579. }
  6580. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6581. auto res = cli_.Get("/streamed-with-range",
  6582. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6584. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6585. EXPECT_EQ(269U, res->body.size());
  6586. // Check that both duplicate range contents are present
  6587. size_t first_abc = res->body.find("abc\r\n");
  6588. EXPECT_TRUE(first_abc != std::string::npos);
  6589. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6590. EXPECT_TRUE(second_abc != std::string::npos);
  6591. // Check that Content-Range headers are present for both ranges
  6592. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6593. EXPECT_TRUE(first_range != std::string::npos);
  6594. size_t second_range =
  6595. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6596. EXPECT_TRUE(second_range != std::string::npos);
  6597. }
  6598. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6599. auto res =
  6600. cli_.Get("/streamed-with-range?error",
  6601. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6603. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6604. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6605. EXPECT_EQ(false, res->has_header("Content-Range"));
  6606. EXPECT_EQ(0U, res->body.size());
  6607. }
  6608. TEST_F(ServerTest, GetStreamedEndless) {
  6609. uint64_t offset = 0;
  6610. auto res = cli_.Get("/streamed-cancel",
  6611. [&](const char * /*data*/, uint64_t data_length) {
  6612. if (offset < 100) {
  6613. offset += data_length;
  6614. return true;
  6615. }
  6616. return false;
  6617. });
  6618. ASSERT_TRUE(!res);
  6619. EXPECT_EQ(Error::Canceled, res.error());
  6620. }
  6621. TEST_F(ServerTest, ClientStop) {
  6622. std::atomic_size_t count{4};
  6623. std::vector<std::thread> threads;
  6624. for (auto i = count.load(); i != 0; --i) {
  6625. threads.emplace_back([&]() {
  6626. auto res = cli_.Get("/streamed-cancel",
  6627. [&](const char *, uint64_t) { return true; });
  6628. --count;
  6629. ASSERT_TRUE(!res);
  6630. EXPECT_TRUE(res.error() == Error::Canceled ||
  6631. res.error() == Error::Read || res.error() == Error::Write);
  6632. });
  6633. }
  6634. std::this_thread::sleep_for(std::chrono::seconds(2));
  6635. while (count != 0) {
  6636. cli_.stop();
  6637. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6638. }
  6639. for (auto &t : threads) {
  6640. t.join();
  6641. }
  6642. }
  6643. TEST_F(ServerTest, GetWithRange1) {
  6644. auto res = cli_.Get("/with-range", Headers{
  6645. make_range_header({{3, 5}}),
  6646. {"Accept-Encoding", ""},
  6647. });
  6648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6649. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6650. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6651. EXPECT_EQ(true, res->has_header("Content-Range"));
  6652. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6653. EXPECT_EQ(std::string("def"), res->body);
  6654. }
  6655. TEST_F(ServerTest, GetWithRange2) {
  6656. auto res = cli_.Get("/with-range", Headers{
  6657. make_range_header({{1, -1}}),
  6658. {"Accept-Encoding", ""},
  6659. });
  6660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6661. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6662. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6663. EXPECT_EQ(true, res->has_header("Content-Range"));
  6664. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6665. EXPECT_EQ(std::string("bcdefg"), res->body);
  6666. }
  6667. TEST_F(ServerTest, GetWithRange3) {
  6668. auto res = cli_.Get("/with-range", Headers{
  6669. make_range_header({{0, 0}}),
  6670. {"Accept-Encoding", ""},
  6671. });
  6672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6673. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6674. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6675. EXPECT_EQ(true, res->has_header("Content-Range"));
  6676. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6677. EXPECT_EQ(std::string("a"), res->body);
  6678. }
  6679. TEST_F(ServerTest, GetWithRange4) {
  6680. auto res = cli_.Get("/with-range", Headers{
  6681. make_range_header({{-1, 2}}),
  6682. {"Accept-Encoding", ""},
  6683. });
  6684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6685. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6686. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6687. EXPECT_EQ(true, res->has_header("Content-Range"));
  6688. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6689. EXPECT_EQ(std::string("fg"), res->body);
  6690. }
  6691. TEST_F(ServerTest, GetWithRange5) {
  6692. auto res = cli_.Get("/with-range", Headers{
  6693. make_range_header({{0, 5}}),
  6694. {"Accept-Encoding", ""},
  6695. });
  6696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6697. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6698. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6699. EXPECT_EQ(true, res->has_header("Content-Range"));
  6700. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6701. EXPECT_EQ(std::string("abcdef"), res->body);
  6702. }
  6703. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6704. auto res =
  6705. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6707. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6708. }
  6709. TEST_F(ServerTest, GetWithRangeMultipart) {
  6710. auto res =
  6711. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6713. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6714. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6715. EXPECT_EQ(false, res->has_header("Content-Range"));
  6716. EXPECT_EQ(267U, res->body.size());
  6717. }
  6718. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6719. auto res = cli_.Get("/with-range",
  6720. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6721. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6722. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6723. }
  6724. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6725. auto res = cli_.Get("/with-range-customized-response",
  6726. Headers{{make_range_header({{1, 2}})}});
  6727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6728. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6729. EXPECT_EQ(true, res->has_header("Content-Length"));
  6730. EXPECT_EQ(false, res->has_header("Content-Range"));
  6731. EXPECT_EQ(JSON_DATA, res->body);
  6732. }
  6733. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6734. auto res = cli_.Get("/with-range-customized-response",
  6735. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6737. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6738. EXPECT_EQ(true, res->has_header("Content-Length"));
  6739. EXPECT_EQ(false, res->has_header("Content-Range"));
  6740. EXPECT_EQ(JSON_DATA, res->body);
  6741. }
  6742. TEST_F(ServerTest, Issue1772) {
  6743. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6745. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6746. }
  6747. TEST_F(ServerTest, Issue609) {
  6748. auto res = cli_.Delete("/issue609");
  6749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6750. EXPECT_EQ(StatusCode::OK_200, res->status);
  6751. EXPECT_EQ(std::string("ok"), res->body);
  6752. }
  6753. TEST_F(ServerTest, GetStreamedChunked) {
  6754. auto res = cli_.Get("/streamed-chunked");
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. EXPECT_EQ(StatusCode::OK_200, res->status);
  6757. EXPECT_EQ(std::string("123456789"), res->body);
  6758. }
  6759. TEST_F(ServerTest, GetStreamedChunked2) {
  6760. auto res = cli_.Get("/streamed-chunked2");
  6761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6762. EXPECT_EQ(StatusCode::OK_200, res->status);
  6763. EXPECT_EQ(std::string("123456789"), res->body);
  6764. }
  6765. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6766. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6768. EXPECT_EQ(StatusCode::OK_200, res->status);
  6769. EXPECT_EQ(std::string("123456789"), res->body);
  6770. EXPECT_TRUE(res->has_header("Trailer"));
  6771. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6772. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6773. // Trailers are now stored separately from headers (security fix)
  6774. EXPECT_EQ(2U, res->trailers.size());
  6775. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6776. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6777. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6778. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6779. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6780. // Verify trailers are NOT in headers (security verification)
  6781. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6782. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6783. }
  6784. TEST_F(ServerTest, LargeChunkedPost) {
  6785. Request req;
  6786. req.method = "POST";
  6787. req.path = "/large-chunked";
  6788. std::string host_and_port;
  6789. host_and_port += HOST;
  6790. host_and_port += ":";
  6791. host_and_port += std::to_string(PORT);
  6792. req.headers.emplace("Host", host_and_port.c_str());
  6793. req.headers.emplace("Accept", "*/*");
  6794. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6795. req.headers.emplace("Content-Type", "text/plain");
  6796. req.headers.emplace("Content-Length", "0");
  6797. req.headers.emplace("Transfer-Encoding", "chunked");
  6798. std::string long_string(30 * 1024u, 'a');
  6799. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6800. // Attempt to make a large enough post to exceed OS buffers, to test that
  6801. // the server handles short reads if the full chunk data isn't available.
  6802. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6803. auto res = std::make_shared<Response>();
  6804. auto error = Error::Success;
  6805. auto ret = cli_.send(req, *res, error);
  6806. ASSERT_TRUE(ret);
  6807. EXPECT_EQ(StatusCode::OK_200, res->status);
  6808. }
  6809. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6810. auto res = cli_.Get("/remote_addr");
  6811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6812. EXPECT_EQ(StatusCode::OK_200, res->status);
  6813. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6814. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6815. }
  6816. TEST_F(ServerTest, GetMethodLocalAddr) {
  6817. auto res = cli_.Get("/local_addr");
  6818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6819. EXPECT_EQ(StatusCode::OK_200, res->status);
  6820. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6821. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6822. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6823. }
  6824. TEST_F(ServerTest, HTTPResponseSplitting) {
  6825. auto res = cli_.Get("/http_response_splitting");
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. }
  6829. TEST_F(ServerTest, SlowRequest) {
  6830. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6831. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6832. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6833. }
  6834. #if 0
  6835. TEST_F(ServerTest, SlowPost) {
  6836. char buffer[64 * 1024];
  6837. memset(buffer, 0x42, sizeof(buffer));
  6838. auto res = cli_.Post(
  6839. "/slowpost", 64 * 1024 * 1024,
  6840. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6841. auto ret = sink.write(buffer, sizeof(buffer));
  6842. EXPECT_TRUE(ret);
  6843. return true;
  6844. },
  6845. "text/plain");
  6846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6847. EXPECT_EQ(StatusCode::OK_200, res->status);
  6848. }
  6849. TEST_F(ServerTest, SlowPostFail) {
  6850. char buffer[64 * 1024];
  6851. memset(buffer, 0x42, sizeof(buffer));
  6852. cli_.set_write_timeout(std::chrono::seconds(0));
  6853. auto res = cli_.Post(
  6854. "/slowpost", 64 * 1024 * 1024,
  6855. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6856. sink.write(buffer, sizeof(buffer));
  6857. return true;
  6858. },
  6859. "text/plain");
  6860. ASSERT_TRUE(!res);
  6861. EXPECT_EQ(Error::Write, res.error());
  6862. }
  6863. #endif
  6864. TEST_F(ServerTest, Put) {
  6865. auto res = cli_.Put("/put", "PUT", "text/plain");
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("PUT", res->body);
  6869. }
  6870. TEST_F(ServerTest, PutWithContentProvider) {
  6871. auto res = cli_.Put(
  6872. "/put", 3,
  6873. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6874. sink.os << "PUT";
  6875. return true;
  6876. },
  6877. "text/plain");
  6878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6879. EXPECT_EQ(StatusCode::OK_200, res->status);
  6880. EXPECT_EQ("PUT", res->body);
  6881. }
  6882. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6883. auto res = cli_.Post(
  6884. "/post", 42,
  6885. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6886. return false;
  6887. },
  6888. "text/plain");
  6889. ASSERT_TRUE(!res);
  6890. EXPECT_EQ(Error::Canceled, res.error());
  6891. }
  6892. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6893. auto res = cli_.Put(
  6894. "/put",
  6895. [](size_t /*offset*/, DataSink &sink) {
  6896. sink.os << "PUT";
  6897. sink.done();
  6898. return true;
  6899. },
  6900. "text/plain");
  6901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6902. EXPECT_EQ(StatusCode::OK_200, res->status);
  6903. EXPECT_EQ("PUT", res->body);
  6904. }
  6905. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6906. auto res = cli_.Post(
  6907. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6908. "text/plain");
  6909. ASSERT_TRUE(!res);
  6910. EXPECT_EQ(Error::Canceled, res.error());
  6911. }
  6912. TEST_F(ServerTest, PostLoopBack) {
  6913. std::string body;
  6914. auto res = cli_.Post(
  6915. "/post-loopback", 9,
  6916. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6917. EXPECT_EQ(9u, length);
  6918. sink.write("123", 3);
  6919. sink.write("456", 3);
  6920. sink.write("789", 3);
  6921. return true;
  6922. },
  6923. "text/plain",
  6924. [&body](const char *data, size_t data_length) {
  6925. body.append(data, data_length);
  6926. return true;
  6927. });
  6928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6929. EXPECT_EQ(StatusCode::OK_200, res->status);
  6930. EXPECT_EQ("123456789", body);
  6931. }
  6932. TEST_F(ServerTest, PutLoopBack) {
  6933. std::string body;
  6934. auto res = cli_.Put(
  6935. "/put-loopback", 9,
  6936. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6937. EXPECT_EQ(9u, length);
  6938. sink.write("123", 3);
  6939. sink.write("456", 3);
  6940. sink.write("789", 3);
  6941. return true;
  6942. },
  6943. "text/plain",
  6944. [&body](const char *data, size_t data_length) {
  6945. body.append(data, data_length);
  6946. return true;
  6947. });
  6948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6949. EXPECT_EQ(StatusCode::OK_200, res->status);
  6950. EXPECT_EQ("123456789", body);
  6951. }
  6952. TEST_F(ServerTest, PatchLoopBack) {
  6953. std::string body;
  6954. auto res = cli_.Patch(
  6955. "/patch-loopback", 9,
  6956. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6957. EXPECT_EQ(9u, length);
  6958. sink.write("123", 3);
  6959. sink.write("456", 3);
  6960. sink.write("789", 3);
  6961. return true;
  6962. },
  6963. "text/plain",
  6964. [&body](const char *data, size_t data_length) {
  6965. body.append(data, data_length);
  6966. return true;
  6967. });
  6968. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6969. EXPECT_EQ(StatusCode::OK_200, res->status);
  6970. EXPECT_EQ("123456789", body);
  6971. }
  6972. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6973. std::string body;
  6974. auto res = cli_.Post(
  6975. "/post-loopback",
  6976. [](size_t /*offset*/, DataSink &sink) {
  6977. sink.write("123", 3);
  6978. sink.write("456", 3);
  6979. sink.write("789", 3);
  6980. sink.done();
  6981. return true;
  6982. },
  6983. "text/plain",
  6984. [&body](const char *data, size_t data_length) {
  6985. body.append(data, data_length);
  6986. return true;
  6987. });
  6988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6989. EXPECT_EQ(StatusCode::OK_200, res->status);
  6990. EXPECT_EQ("123456789", body);
  6991. }
  6992. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6993. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6994. cli_.set_compress(true);
  6995. auto res = cli_.Put(
  6996. "/put", 3,
  6997. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6998. sink.os << "PUT";
  6999. return true;
  7000. },
  7001. "text/plain");
  7002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7003. EXPECT_EQ(StatusCode::OK_200, res->status);
  7004. EXPECT_EQ("PUT", res->body);
  7005. }
  7006. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7007. cli_.set_compress(true);
  7008. auto res = cli_.Post(
  7009. "/post", 42,
  7010. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7011. return false;
  7012. },
  7013. "text/plain");
  7014. ASSERT_TRUE(!res);
  7015. EXPECT_EQ(Error::Canceled, res.error());
  7016. }
  7017. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7018. cli_.set_compress(true);
  7019. auto res = cli_.Put(
  7020. "/put",
  7021. [](size_t /*offset*/, DataSink &sink) {
  7022. sink.os << "PUT";
  7023. sink.done();
  7024. return true;
  7025. },
  7026. "text/plain");
  7027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7028. EXPECT_EQ(StatusCode::OK_200, res->status);
  7029. EXPECT_EQ("PUT", res->body);
  7030. }
  7031. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7032. cli_.set_compress(true);
  7033. auto res = cli_.Post(
  7034. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7035. "text/plain");
  7036. ASSERT_TRUE(!res);
  7037. EXPECT_EQ(Error::Canceled, res.error());
  7038. }
  7039. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7040. cli_.set_compress(true);
  7041. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7043. EXPECT_EQ(StatusCode::OK_200, res->status);
  7044. EXPECT_EQ(LARGE_DATA, res->body);
  7045. }
  7046. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7047. #ifdef CPPHTTPLIB_SSL_ENABLED
  7048. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7049. Client cli(s.c_str());
  7050. cli.enable_server_certificate_verification(false);
  7051. #else
  7052. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7053. Client cli(s.c_str());
  7054. #endif
  7055. cli.set_compress(true);
  7056. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_EQ(StatusCode::OK_200, res->status);
  7059. EXPECT_EQ(LARGE_DATA, res->body);
  7060. // The compressed size should be less than a 10th of the original. May vary
  7061. // depending on the zlib library.
  7062. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7063. static_cast<uint64_t>(10 * 1024 * 1024));
  7064. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7065. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7066. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7067. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7068. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7069. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7070. #endif
  7071. }
  7072. TEST_F(ServerTest, PutContentWithDeflate) {
  7073. cli_.set_compress(false);
  7074. Headers headers;
  7075. headers.emplace("Content-Encoding", "deflate");
  7076. // PUT in deflate format:
  7077. auto res = cli_.Put("/put", headers,
  7078. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::OK_200, res->status);
  7081. EXPECT_EQ("PUT", res->body);
  7082. }
  7083. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7084. Headers headers;
  7085. headers.emplace("Accept-Encoding", "gzip, deflate");
  7086. auto res = cli_.Get("/streamed-chunked", headers);
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(StatusCode::OK_200, res->status);
  7089. EXPECT_EQ(std::string("123456789"), res->body);
  7090. }
  7091. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7092. Headers headers;
  7093. headers.emplace("Accept-Encoding", "gzip, deflate");
  7094. auto res = cli_.Get("/streamed-chunked2", headers);
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. EXPECT_EQ(StatusCode::OK_200, res->status);
  7097. EXPECT_EQ(std::string("123456789"), res->body);
  7098. }
  7099. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7100. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7102. EXPECT_EQ(StatusCode::OK_200, res->status);
  7103. }
  7104. TEST(GzipDecompressor, ChunkedDecompression) {
  7105. std::string data;
  7106. for (size_t i = 0; i < 32 * 1024; ++i) {
  7107. data.push_back(static_cast<char>('a' + i % 26));
  7108. }
  7109. std::string compressed_data;
  7110. {
  7111. httplib::detail::gzip_compressor compressor;
  7112. bool result = compressor.compress(
  7113. data.data(), data.size(),
  7114. /*last=*/true,
  7115. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7116. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7117. compressed_data_size);
  7118. return true;
  7119. });
  7120. ASSERT_TRUE(result);
  7121. }
  7122. std::string decompressed_data;
  7123. {
  7124. httplib::detail::gzip_decompressor decompressor;
  7125. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7126. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7127. size_t chunk_size = 130;
  7128. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7129. chunk_begin += chunk_size) {
  7130. size_t current_chunk_size =
  7131. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7132. bool result = decompressor.decompress(
  7133. compressed_data.data() + chunk_begin, current_chunk_size,
  7134. [&](const char *decompressed_data_chunk,
  7135. size_t decompressed_data_chunk_size) {
  7136. decompressed_data.insert(decompressed_data.size(),
  7137. decompressed_data_chunk,
  7138. decompressed_data_chunk_size);
  7139. return true;
  7140. });
  7141. ASSERT_TRUE(result);
  7142. }
  7143. }
  7144. ASSERT_EQ(data, decompressed_data);
  7145. }
  7146. TEST(GzipDecompressor, DeflateDecompression) {
  7147. std::string original_text = "Raw deflate without gzip";
  7148. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7149. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7150. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7151. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7152. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7153. std::string decompressed_data;
  7154. {
  7155. httplib::detail::gzip_decompressor decompressor;
  7156. bool result = decompressor.decompress(
  7157. compressed_data.data(), compressed_data.size(),
  7158. [&](const char *decompressed_data_chunk,
  7159. size_t decompressed_data_chunk_size) {
  7160. decompressed_data.insert(decompressed_data.size(),
  7161. decompressed_data_chunk,
  7162. decompressed_data_chunk_size);
  7163. return true;
  7164. });
  7165. ASSERT_TRUE(result);
  7166. }
  7167. ASSERT_EQ(original_text, decompressed_data);
  7168. }
  7169. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7170. std::string original_text = "Raw deflate without gzip";
  7171. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7172. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7173. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7174. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7175. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7176. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7177. std::string decompressed_data;
  7178. {
  7179. httplib::detail::gzip_decompressor decompressor;
  7180. bool result = decompressor.decompress(
  7181. compressed_data.data(), compressed_data.size(),
  7182. [&](const char *decompressed_data_chunk,
  7183. size_t decompressed_data_chunk_size) {
  7184. decompressed_data.insert(decompressed_data.size(),
  7185. decompressed_data_chunk,
  7186. decompressed_data_chunk_size);
  7187. return true;
  7188. });
  7189. ASSERT_TRUE(result);
  7190. }
  7191. ASSERT_EQ(original_text, decompressed_data);
  7192. }
  7193. #endif
  7194. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7195. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7196. Headers headers;
  7197. headers.emplace("Accept-Encoding", "br");
  7198. auto res = cli_.Get("/streamed-chunked", headers);
  7199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7200. EXPECT_EQ(StatusCode::OK_200, res->status);
  7201. EXPECT_EQ(std::string("123456789"), res->body);
  7202. }
  7203. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7204. Headers headers;
  7205. headers.emplace("Accept-Encoding", "br");
  7206. auto res = cli_.Get("/streamed-chunked2", headers);
  7207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7208. EXPECT_EQ(StatusCode::OK_200, res->status);
  7209. EXPECT_EQ(std::string("123456789"), res->body);
  7210. }
  7211. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7212. cli_.set_compress(true);
  7213. auto res = cli_.Put(
  7214. "/put", 3,
  7215. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7216. sink.os << "PUT";
  7217. return true;
  7218. },
  7219. "text/plain");
  7220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7221. EXPECT_EQ(StatusCode::OK_200, res->status);
  7222. EXPECT_EQ("PUT", res->body);
  7223. }
  7224. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7225. cli_.set_compress(true);
  7226. auto res = cli_.Put(
  7227. "/put",
  7228. [](size_t /*offset*/, DataSink &sink) {
  7229. sink.os << "PUT";
  7230. sink.done();
  7231. return true;
  7232. },
  7233. "text/plain");
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. EXPECT_EQ(StatusCode::OK_200, res->status);
  7236. EXPECT_EQ("PUT", res->body);
  7237. }
  7238. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7239. cli_.set_compress(true);
  7240. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7242. EXPECT_EQ(StatusCode::OK_200, res->status);
  7243. EXPECT_EQ(LARGE_DATA, res->body);
  7244. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7245. }
  7246. #endif
  7247. TEST_F(ServerTest, Patch) {
  7248. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7250. EXPECT_EQ(StatusCode::OK_200, res->status);
  7251. EXPECT_EQ("PATCH", res->body);
  7252. }
  7253. TEST_F(ServerTest, Delete) {
  7254. auto res = cli_.Delete("/delete");
  7255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7256. EXPECT_EQ(StatusCode::OK_200, res->status);
  7257. EXPECT_EQ("DELETE", res->body);
  7258. }
  7259. TEST_F(ServerTest, DeleteContentReceiver) {
  7260. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7262. EXPECT_EQ(StatusCode::OK_200, res->status);
  7263. EXPECT_EQ("content", res->body);
  7264. }
  7265. TEST_F(ServerTest, Options) {
  7266. auto res = cli_.Options("*");
  7267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7268. EXPECT_EQ(StatusCode::OK_200, res->status);
  7269. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7270. EXPECT_TRUE(res->body.empty());
  7271. }
  7272. TEST_F(ServerTest, URL) {
  7273. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7275. EXPECT_EQ(StatusCode::OK_200, res->status);
  7276. }
  7277. TEST_F(ServerTest, ArrayParam) {
  7278. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::OK_200, res->status);
  7281. }
  7282. TEST_F(ServerTest, ArrayParamValues) {
  7283. auto res =
  7284. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7286. EXPECT_EQ(StatusCode::OK_200, res->status);
  7287. }
  7288. TEST_F(ServerTest, NoMultipleHeaders) {
  7289. Headers headers = {{"Content-Length", "5"}};
  7290. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7291. "text/plain");
  7292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7293. EXPECT_EQ(StatusCode::OK_200, res->status);
  7294. }
  7295. TEST_F(ServerTest, PostContentReceiver) {
  7296. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7298. ASSERT_EQ(StatusCode::OK_200, res->status);
  7299. ASSERT_EQ("content", res->body);
  7300. }
  7301. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7302. UploadFormDataItems items = {
  7303. {"text1", "text default", "", ""},
  7304. {"text2", "aωb", "", ""},
  7305. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7306. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7307. {"file3", "", "", "application/octet-stream"},
  7308. };
  7309. auto res = cli_.Post("/content_receiver", items);
  7310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7311. EXPECT_EQ(StatusCode::OK_200, res->status);
  7312. }
  7313. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7314. UploadFormDataItems items = {
  7315. {"text1", "text default", "", ""},
  7316. {"text2", "aωb", "", ""},
  7317. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7318. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7319. {"file3", "", "", "application/octet-stream"},
  7320. };
  7321. auto boundary = std::string("+++++");
  7322. std::string body;
  7323. for (const auto &item : items) {
  7324. body += "--" + boundary + "\r\n";
  7325. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7326. if (!item.filename.empty()) {
  7327. body += "; filename=\"" + item.filename + "\"";
  7328. }
  7329. body += "\r\n";
  7330. if (!item.content_type.empty()) {
  7331. body += "Content-Type: " + item.content_type + "\r\n";
  7332. }
  7333. body += "\r\n";
  7334. body += item.content + "\r\n";
  7335. }
  7336. body += "--" + boundary + "--\r\n";
  7337. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7338. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7339. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7340. EXPECT_EQ(StatusCode::OK_200, res->status);
  7341. }
  7342. TEST(MultipartFormDataTest, FieldEscaping) {
  7343. Server svr;
  7344. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7345. const ContentReader &content_reader) {
  7346. ASSERT_TRUE(req.is_multipart_form_data());
  7347. std::vector<FormData> received;
  7348. content_reader(
  7349. [&](const FormData &file) {
  7350. received.push_back(file);
  7351. return true;
  7352. },
  7353. [&](const char *data, size_t data_length) {
  7354. received.back().content.append(data, data_length);
  7355. return true;
  7356. });
  7357. // '"', CR and LF in names and filenames are escaped following the
  7358. // WHATWG HTML standard, so each part still parses as a single part
  7359. // with no injected headers. Content types get CR/LF escaped too,
  7360. // while '"' (legal there, e.g. quoted charset) is preserved.
  7361. ASSERT_EQ(4U, received.size());
  7362. EXPECT_EQ("na%22me", received[0].name);
  7363. EXPECT_EQ("quoted name", received[0].content);
  7364. EXPECT_EQ("file", received[1].name);
  7365. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7366. received[1].filename);
  7367. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7368. EXPECT_EQ("injected", received[1].content);
  7369. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7370. EXPECT_EQ("my%22file.txt", received[2].filename);
  7371. EXPECT_EQ("cr lf name", received[2].content);
  7372. EXPECT_EQ("typed", received[3].name);
  7373. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7374. received[3].content_type);
  7375. EXPECT_EQ("typed content", received[3].content);
  7376. });
  7377. auto port = svr.bind_to_any_port("localhost");
  7378. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7379. auto se = detail::scope_exit([&] {
  7380. svr.stop();
  7381. t.join();
  7382. ASSERT_FALSE(svr.is_running());
  7383. });
  7384. svr.wait_until_ready();
  7385. Client cli("localhost", port);
  7386. UploadFormDataItems items = {
  7387. {"na\"me", "quoted name", "", ""},
  7388. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7389. "application/octet-stream"},
  7390. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7391. {"typed", "typed content", "",
  7392. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7393. };
  7394. auto res = cli.Post("/post", items);
  7395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7396. EXPECT_EQ(StatusCode::OK_200, res->status);
  7397. }
  7398. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7399. const UploadFormDataItems items = {
  7400. {"name1", "Content 1", "", ""},
  7401. {"name2", "Content 2", "file2.txt", "text/plain"},
  7402. };
  7403. Server svr;
  7404. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7405. const ContentReader &content_reader) {
  7406. ASSERT_TRUE(req.is_multipart_form_data());
  7407. std::vector<FormData> received;
  7408. content_reader(
  7409. [&](const FormData &file) {
  7410. received.push_back(file);
  7411. return true;
  7412. },
  7413. [&](const char *data, size_t data_length) {
  7414. received.back().content.append(data, data_length);
  7415. return true;
  7416. });
  7417. ASSERT_EQ(2U, received.size());
  7418. EXPECT_EQ("name1", received[0].name);
  7419. EXPECT_EQ("Content 1", received[0].content);
  7420. EXPECT_EQ("name2", received[1].name);
  7421. EXPECT_EQ("Content 2", received[1].content);
  7422. EXPECT_EQ("file2.txt", received[1].filename);
  7423. EXPECT_EQ("text/plain", received[1].content_type);
  7424. });
  7425. auto port = svr.bind_to_any_port("localhost");
  7426. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7427. auto se = detail::scope_exit([&] {
  7428. svr.stop();
  7429. t.join();
  7430. ASSERT_FALSE(svr.is_running());
  7431. });
  7432. svr.wait_until_ready();
  7433. Client cli("localhost", port);
  7434. // Whole-body serialization with a generated boundary
  7435. {
  7436. MultipartFormDataWriter writer;
  7437. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7438. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7439. writer.content_type());
  7440. auto body = writer.serialize(items);
  7441. EXPECT_EQ(body.size(), writer.content_length(items));
  7442. auto res = cli.Post("/post", body, writer.content_type());
  7443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7444. EXPECT_EQ(StatusCode::OK_200, res->status);
  7445. }
  7446. // Per-part framing with a custom boundary via a content provider
  7447. {
  7448. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7449. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7450. MultipartFormDataWriter writer("custom-boundary_123");
  7451. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7452. std::string body;
  7453. for (const auto &item : items) {
  7454. body += writer.item_begin(item);
  7455. body += item.content;
  7456. body += MultipartFormDataWriter::item_end();
  7457. }
  7458. body += writer.finish();
  7459. EXPECT_EQ(body.size(), writer.content_length(items));
  7460. auto res = cli.Post(
  7461. "/post", body.size(),
  7462. [&](size_t offset, size_t length, DataSink &sink) {
  7463. sink.write(body.data() + offset, length);
  7464. return true;
  7465. },
  7466. writer.content_type());
  7467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7468. EXPECT_EQ(StatusCode::OK_200, res->status);
  7469. }
  7470. }
  7471. TEST_F(ServerTest, PostContentReceiverGzip) {
  7472. cli_.set_compress(true);
  7473. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7475. ASSERT_EQ(StatusCode::OK_200, res->status);
  7476. ASSERT_EQ("content", res->body);
  7477. }
  7478. TEST_F(ServerTest, PutContentReceiver) {
  7479. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7481. ASSERT_EQ(StatusCode::OK_200, res->status);
  7482. ASSERT_EQ("content", res->body);
  7483. }
  7484. TEST_F(ServerTest, PatchContentReceiver) {
  7485. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7487. ASSERT_EQ(StatusCode::OK_200, res->status);
  7488. ASSERT_EQ("content", res->body);
  7489. }
  7490. template <typename ClientType>
  7491. void TestWithHeadersAndContentReceiver(
  7492. ClientType &cli,
  7493. std::function<Result(ClientType &, const std::string &, const Headers &,
  7494. const std::string &, const std::string &,
  7495. ContentReceiver, DownloadProgress)>
  7496. request_func) {
  7497. Headers headers;
  7498. headers.emplace("X-Custom-Header", "test-value");
  7499. std::string received_body;
  7500. auto res = request_func(
  7501. cli, "/content_receiver", headers, "content", "application/json",
  7502. [&](const char *data, size_t data_length) {
  7503. received_body.append(data, data_length);
  7504. return true;
  7505. },
  7506. nullptr);
  7507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7508. EXPECT_EQ(StatusCode::OK_200, res->status);
  7509. EXPECT_EQ("content", received_body);
  7510. }
  7511. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7512. #ifdef CPPHTTPLIB_SSL_ENABLED
  7513. using ClientT = SSLClient;
  7514. #else
  7515. using ClientT = Client;
  7516. #endif
  7517. TestWithHeadersAndContentReceiver<ClientT>(
  7518. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7519. const std::string &body, const std::string &content_type,
  7520. ContentReceiver receiver, DownloadProgress progress) {
  7521. return cli.Post(path, headers, body, content_type, receiver, progress);
  7522. });
  7523. }
  7524. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7525. #ifdef CPPHTTPLIB_SSL_ENABLED
  7526. using ClientT = SSLClient;
  7527. #else
  7528. using ClientT = Client;
  7529. #endif
  7530. TestWithHeadersAndContentReceiver<ClientT>(
  7531. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7532. const std::string &body, const std::string &content_type,
  7533. ContentReceiver receiver, DownloadProgress progress) {
  7534. return cli.Put(path, headers, body, content_type, receiver, progress);
  7535. });
  7536. }
  7537. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7538. #ifdef CPPHTTPLIB_SSL_ENABLED
  7539. using ClientT = SSLClient;
  7540. #else
  7541. using ClientT = Client;
  7542. #endif
  7543. TestWithHeadersAndContentReceiver<ClientT>(
  7544. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7545. const std::string &body, const std::string &content_type,
  7546. ContentReceiver receiver, DownloadProgress progress) {
  7547. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7548. });
  7549. }
  7550. template <typename ClientType>
  7551. void TestWithHeadersAndContentReceiverWithProgress(
  7552. ClientType &cli,
  7553. std::function<Result(ClientType &, const std::string &, const Headers &,
  7554. const std::string &, const std::string &,
  7555. ContentReceiver, DownloadProgress)>
  7556. request_func) {
  7557. Headers headers;
  7558. headers.emplace("X-Test-Header", "progress-test");
  7559. std::string received_body;
  7560. auto progress_called = false;
  7561. auto res = request_func(
  7562. cli, "/content_receiver", headers, "content", "text/plain",
  7563. [&](const char *data, size_t data_length) {
  7564. received_body.append(data, data_length);
  7565. return true;
  7566. },
  7567. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7568. progress_called = true;
  7569. return true;
  7570. });
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. EXPECT_EQ("content", received_body);
  7574. EXPECT_TRUE(progress_called);
  7575. }
  7576. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7577. #ifdef CPPHTTPLIB_SSL_ENABLED
  7578. using ClientT = SSLClient;
  7579. #else
  7580. using ClientT = Client;
  7581. #endif
  7582. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7583. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7584. const std::string &body, const std::string &content_type,
  7585. ContentReceiver receiver, DownloadProgress progress) {
  7586. return cli.Post(path, headers, body, content_type, receiver, progress);
  7587. });
  7588. }
  7589. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7590. #ifdef CPPHTTPLIB_SSL_ENABLED
  7591. using ClientT = SSLClient;
  7592. #else
  7593. using ClientT = Client;
  7594. #endif
  7595. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7596. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7597. const std::string &body, const std::string &content_type,
  7598. ContentReceiver receiver, DownloadProgress progress) {
  7599. return cli.Put(path, headers, body, content_type, receiver, progress);
  7600. });
  7601. }
  7602. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7603. #ifdef CPPHTTPLIB_SSL_ENABLED
  7604. using ClientT = SSLClient;
  7605. #else
  7606. using ClientT = Client;
  7607. #endif
  7608. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7609. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7610. const std::string &body, const std::string &content_type,
  7611. ContentReceiver receiver, DownloadProgress progress) {
  7612. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7613. });
  7614. }
  7615. template <typename ClientType>
  7616. void TestWithHeadersAndContentReceiverError(
  7617. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7618. const Headers &, const std::string &,
  7619. const std::string &, ContentReceiver)>
  7620. request_func) {
  7621. Headers headers;
  7622. headers.emplace("X-Error-Test", "true");
  7623. std::string received_body;
  7624. auto receiver_failed = false;
  7625. auto res =
  7626. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7627. [&](const char *data, size_t data_length) {
  7628. received_body.append(data, data_length);
  7629. receiver_failed = true;
  7630. return false;
  7631. });
  7632. ASSERT_FALSE(res);
  7633. EXPECT_TRUE(receiver_failed);
  7634. }
  7635. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7636. #ifdef CPPHTTPLIB_SSL_ENABLED
  7637. using ClientT = SSLClient;
  7638. #else
  7639. using ClientT = Client;
  7640. #endif
  7641. TestWithHeadersAndContentReceiverError<ClientT>(
  7642. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7643. const std::string &body, const std::string &content_type,
  7644. ContentReceiver receiver) {
  7645. return cli.Post(path, headers, body, content_type, receiver);
  7646. });
  7647. }
  7648. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7649. #ifdef CPPHTTPLIB_SSL_ENABLED
  7650. using ClientT = SSLClient;
  7651. #else
  7652. using ClientT = Client;
  7653. #endif
  7654. TestWithHeadersAndContentReceiverError<ClientT>(
  7655. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7656. const std::string &body, const std::string &content_type,
  7657. ContentReceiver receiver) {
  7658. return cli.Put(path, headers, body, content_type, receiver);
  7659. });
  7660. }
  7661. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7662. #ifdef CPPHTTPLIB_SSL_ENABLED
  7663. using ClientT = SSLClient;
  7664. #else
  7665. using ClientT = Client;
  7666. #endif
  7667. TestWithHeadersAndContentReceiverError<ClientT>(
  7668. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7669. const std::string &body, const std::string &content_type,
  7670. ContentReceiver receiver) {
  7671. return cli.Patch(path, headers, body, content_type, receiver);
  7672. });
  7673. }
  7674. TEST_F(ServerTest, PostQueryStringAndBody) {
  7675. auto res =
  7676. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7678. ASSERT_EQ(StatusCode::OK_200, res->status);
  7679. }
  7680. TEST_F(ServerTest, HTTP2Magic) {
  7681. Request req;
  7682. req.method = "PRI";
  7683. req.path = "*";
  7684. req.body = "SM";
  7685. auto res = std::make_shared<Response>();
  7686. auto error = Error::Success;
  7687. auto ret = cli_.send(req, *res, error);
  7688. ASSERT_TRUE(ret);
  7689. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7690. }
  7691. TEST_F(ServerTest, KeepAlive) {
  7692. auto res = cli_.Get("/hi");
  7693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7694. EXPECT_EQ(StatusCode::OK_200, res->status);
  7695. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7696. EXPECT_EQ("Hello World!", res->body);
  7697. res = cli_.Get("/hi");
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::OK_200, res->status);
  7700. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7701. EXPECT_EQ("Hello World!", res->body);
  7702. res = cli_.Get("/hi");
  7703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7704. EXPECT_EQ(StatusCode::OK_200, res->status);
  7705. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7706. EXPECT_EQ("Hello World!", res->body);
  7707. res = cli_.Get("/not-exist");
  7708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7709. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7710. res = cli_.Post("/empty", "", "text/plain");
  7711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7712. EXPECT_EQ(StatusCode::OK_200, res->status);
  7713. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7714. EXPECT_EQ("empty", res->body);
  7715. EXPECT_EQ("close", res->get_header_value("Connection"));
  7716. res = cli_.Post(
  7717. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7718. "text/plain");
  7719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7720. EXPECT_EQ(StatusCode::OK_200, res->status);
  7721. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7722. EXPECT_EQ("empty", res->body);
  7723. cli_.set_keep_alive(false);
  7724. res = cli_.Get("/last-request");
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::OK_200, res->status);
  7727. EXPECT_EQ("close", res->get_header_value("Connection"));
  7728. }
  7729. TEST_F(ServerTest, TooManyRedirect) {
  7730. cli_.set_follow_location(true);
  7731. auto res = cli_.Get("/redirect/0");
  7732. ASSERT_TRUE(!res);
  7733. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7734. }
  7735. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7736. Request req;
  7737. req.method = "FOOBAR";
  7738. req.path = "/hi";
  7739. cli_.set_keep_alive(true);
  7740. auto res = cli_.send(req);
  7741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7742. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7743. EXPECT_EQ("close", res->get_header_value("Connection"));
  7744. EXPECT_FALSE(cli_.is_socket_open());
  7745. }
  7746. TEST_F(ServerTest, CustomRouteReadsBody) {
  7747. const std::string xml =
  7748. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7749. Request req;
  7750. req.method = "PROPFIND";
  7751. req.path = "/dav/dir";
  7752. req.set_header("Depth", "1");
  7753. req.body = xml;
  7754. auto res = cli_.send(req);
  7755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7756. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7757. EXPECT_EQ(xml, res->body);
  7758. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7759. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7760. }
  7761. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7762. Request req;
  7763. req.method = "PROPFIND";
  7764. req.path = "/dav/42";
  7765. auto res = cli_.send(req);
  7766. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7767. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7768. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7769. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7770. }
  7771. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7772. Request req;
  7773. req.method = "PROPFIND";
  7774. req.path = "/dav-re/123";
  7775. auto res = cli_.send(req);
  7776. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7777. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7778. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7779. }
  7780. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7781. Request req;
  7782. req.method = "MKCOL";
  7783. req.path = "/dav-mkcol";
  7784. auto res = cli_.send(req);
  7785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7786. EXPECT_EQ(StatusCode::Created_201, res->status);
  7787. }
  7788. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7789. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7790. Request req;
  7791. req.method = "REPORT";
  7792. req.path = "/dav-report";
  7793. req.body = xml;
  7794. auto res = cli_.send(req);
  7795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7796. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7797. EXPECT_EQ(xml, res->body);
  7798. }
  7799. // A content reader route must fire even when the request carries no body,
  7800. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7801. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7802. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7803. Request req;
  7804. req.method = "REPORT";
  7805. req.path = "/dav-report";
  7806. auto res = cli_.send(req);
  7807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7808. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7809. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7810. }
  7811. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7812. Request req;
  7813. req.method = "PROPFIND";
  7814. req.path = "/not-dav";
  7815. auto res = cli_.send(req);
  7816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7817. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7818. }
  7819. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7820. Request req;
  7821. req.method = "UNLOCK";
  7822. req.path = "/dav/dir";
  7823. cli_.set_keep_alive(true);
  7824. auto res = cli_.send(req);
  7825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7826. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7827. EXPECT_EQ("close", res->get_header_value("Connection"));
  7828. EXPECT_FALSE(cli_.is_socket_open());
  7829. }
  7830. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7831. // The mount point serves this path, but only for GET and HEAD.
  7832. auto get_res = cli_.Get("/dir/index.html");
  7833. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7834. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7835. Request req;
  7836. req.method = "PROPFIND";
  7837. req.path = "/dir/index.html";
  7838. auto res = cli_.send(req);
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7841. }
  7842. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7843. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7844. cli_.set_keep_alive(true);
  7845. for (auto i = 0; i < 2; i++) {
  7846. Request req;
  7847. req.method = "PROPFIND";
  7848. req.path = "/dav/dir";
  7849. req.body = xml;
  7850. auto res = cli_.send(req);
  7851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7852. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7853. EXPECT_EQ(xml, res->body);
  7854. EXPECT_TRUE(cli_.is_socket_open());
  7855. }
  7856. // A built-in method must still be served on the same connection.
  7857. cli_.set_keep_alive(false);
  7858. auto res = cli_.Get("/hi");
  7859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7860. EXPECT_EQ(StatusCode::OK_200, res->status);
  7861. EXPECT_EQ("close", res->get_header_value("Connection"));
  7862. }
  7863. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7864. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7865. Request req;
  7866. req.method = "PROPFIND";
  7867. req.path = "/dav/dir";
  7868. req.set_header("Expect", "100-continue");
  7869. req.body = xml;
  7870. auto res = cli_.send(req);
  7871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7872. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7873. EXPECT_EQ(xml, res->body);
  7874. }
  7875. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7876. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7877. TEST_F(ServerTest, Gzip) {
  7878. Headers headers;
  7879. headers.emplace("Accept-Encoding", "gzip, deflate");
  7880. auto res = cli_.Get("/compress", headers);
  7881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7882. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7884. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7885. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7886. "7890123456789012345678901234567890",
  7887. res->body);
  7888. EXPECT_EQ(StatusCode::OK_200, res->status);
  7889. }
  7890. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7891. Headers headers;
  7892. headers.emplace("Accept-Encoding", "gzip, deflate");
  7893. auto res = cli_.Get("/compress-with-charset", headers);
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7896. EXPECT_EQ("application/json; charset=utf-8",
  7897. res->get_header_value("Content-Type"));
  7898. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7899. "7890123456789012345678901234567890",
  7900. res->body);
  7901. EXPECT_EQ(StatusCode::OK_200, res->status);
  7902. }
  7903. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7904. Headers headers;
  7905. headers.emplace("Accept-Encoding", "");
  7906. auto res = cli_.Get("/compress", headers);
  7907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7908. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7909. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7910. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7911. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7912. "7890123456789012345678901234567890",
  7913. res->body);
  7914. EXPECT_EQ(StatusCode::OK_200, res->status);
  7915. }
  7916. TEST_F(ServerTest, GzipWithContentReceiver) {
  7917. Headers headers;
  7918. headers.emplace("Accept-Encoding", "gzip, deflate");
  7919. std::string body;
  7920. auto res = cli_.Get("/compress", headers,
  7921. [&](const char *data, uint64_t data_length) {
  7922. EXPECT_EQ(100U, data_length);
  7923. body.append(data, data_length);
  7924. return true;
  7925. });
  7926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7927. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7928. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7929. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7930. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7931. "7890123456789012345678901234567890",
  7932. body);
  7933. EXPECT_EQ(StatusCode::OK_200, res->status);
  7934. }
  7935. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7936. Headers headers;
  7937. headers.emplace("Accept-Encoding", "gzip, deflate");
  7938. cli_.set_decompress(false);
  7939. auto res = cli_.Get("/compress", headers);
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7942. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7943. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7944. EXPECT_EQ(33U, res->body.size());
  7945. EXPECT_EQ(StatusCode::OK_200, res->status);
  7946. }
  7947. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7948. Headers headers;
  7949. headers.emplace("Accept-Encoding", "");
  7950. std::string body;
  7951. auto res = cli_.Get("/compress", headers,
  7952. [&](const char *data, uint64_t data_length) {
  7953. EXPECT_EQ(100U, data_length);
  7954. body.append(data, data_length);
  7955. return true;
  7956. });
  7957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7958. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7959. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7960. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7961. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7962. "7890123456789012345678901234567890",
  7963. body);
  7964. EXPECT_EQ(StatusCode::OK_200, res->status);
  7965. }
  7966. TEST_F(ServerTest, NoGzip) {
  7967. Headers headers;
  7968. headers.emplace("Accept-Encoding", "gzip, deflate");
  7969. auto res = cli_.Get("/nocompress", headers);
  7970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7971. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7972. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7973. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7974. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7975. "7890123456789012345678901234567890",
  7976. res->body);
  7977. EXPECT_EQ(StatusCode::OK_200, res->status);
  7978. }
  7979. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7980. Headers headers;
  7981. headers.emplace("Accept-Encoding", "gzip, deflate");
  7982. std::string body;
  7983. auto res = cli_.Get("/nocompress", headers,
  7984. [&](const char *data, uint64_t data_length) {
  7985. EXPECT_EQ(100U, data_length);
  7986. body.append(data, data_length);
  7987. return true;
  7988. });
  7989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7990. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7991. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7992. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7993. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7994. "7890123456789012345678901234567890",
  7995. body);
  7996. EXPECT_EQ(StatusCode::OK_200, res->status);
  7997. }
  7998. TEST_F(ServerTest, MultipartFormDataGzip) {
  7999. UploadFormDataItems items = {
  8000. {"key1", "test", "", ""},
  8001. {"key2", "--abcdefg123", "", ""},
  8002. };
  8003. cli_.set_compress(true);
  8004. auto res = cli_.Post("/compress-multipart", items);
  8005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8006. EXPECT_EQ(StatusCode::OK_200, res->status);
  8007. }
  8008. #endif
  8009. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8010. // Static file compression is opt-in, so these run their own server rather than
  8011. // flipping it on for the shared ServerTest fixture, which would silently
  8012. // rewrite what every other static file test is asserting.
  8013. class StaticFileCompressionTest : public ::testing::Test {
  8014. protected:
  8015. void TearDown() override {
  8016. if (t_.joinable()) {
  8017. svr_.stop();
  8018. t_.join();
  8019. }
  8020. }
  8021. int start(const std::function<void(Server &)> &configure = nullptr) {
  8022. // Serves the same tree as a directory of build-time compressed assets
  8023. // would be served: the mount point names the coding the files are already
  8024. // stored in. Registered before "/" so it is the one that matches.
  8025. svr_.set_mount_point("/pre-encoded", "./www",
  8026. {{"Content-Encoding", "gzip"}});
  8027. svr_.set_mount_point("/", "./www");
  8028. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8029. res.set_file_content("./www/dir/index.html", "text/html");
  8030. });
  8031. svr_.Get("/pre-encoded-file-content",
  8032. [](const Request & /*req*/, Response &res) {
  8033. res.set_header("Content-Encoding", "gzip");
  8034. res.set_file_content("./www/dir/index.html", "text/html");
  8035. });
  8036. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8037. res.set_content_provider(
  8038. 6, "text/plain",
  8039. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8040. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8041. return true;
  8042. });
  8043. });
  8044. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8045. res.set_content_provider(
  8046. 1000, "text/plain",
  8047. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8048. if (offset < 100) {
  8049. std::string data(100, 'A');
  8050. sink.write(data.data(), data.size());
  8051. return true;
  8052. }
  8053. std::this_thread::sleep_for(std::chrono::seconds(2));
  8054. std::string data(900, 'B');
  8055. sink.write(data.data(), data.size());
  8056. return true;
  8057. });
  8058. });
  8059. if (configure) { configure(svr_); }
  8060. auto port = svr_.bind_to_any_port(HOST);
  8061. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8062. svr_.wait_until_ready();
  8063. return port;
  8064. }
  8065. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8066. // Every file under ./www except 1MB.txt is smaller than the default
  8067. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8068. // it out of the way.
  8069. static void enable_without_floor(Server &svr) {
  8070. svr.set_static_file_compression(true);
  8071. svr.set_static_file_compression_min_length(0);
  8072. }
  8073. Server svr_;
  8074. std::thread t_;
  8075. };
  8076. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8077. auto port = start();
  8078. Client cli(HOST, port);
  8079. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8081. EXPECT_EQ(StatusCode::OK_200, res->status);
  8082. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8083. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8084. EXPECT_EQ(1048576U, res->body.size());
  8085. }
  8086. TEST_F(StaticFileCompressionTest, MountPoint) {
  8087. auto port = start(enable);
  8088. Client cli(HOST, port);
  8089. cli.set_decompress(false);
  8090. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8092. EXPECT_EQ(StatusCode::OK_200, res->status);
  8093. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8094. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8095. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8096. // The response stays self-delimiting: a length, not a chunked body.
  8097. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8098. EXPECT_EQ(std::to_string(res->body.size()),
  8099. res->get_header_value("Content-Length"));
  8100. EXPECT_LT(res->body.size(), 1048576U);
  8101. EXPECT_FALSE(res->body.empty());
  8102. }
  8103. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8104. auto port = start(enable);
  8105. Client cli(HOST, port);
  8106. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8108. EXPECT_EQ(StatusCode::OK_200, res->status);
  8109. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8110. EXPECT_EQ(1048576U, res->body.size());
  8111. }
  8112. TEST_F(StaticFileCompressionTest, FileContent) {
  8113. auto port = start(enable_without_floor);
  8114. Client cli(HOST, port);
  8115. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8117. EXPECT_EQ(StatusCode::OK_200, res->status);
  8118. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8119. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8120. EXPECT_EQ(104U, res->body.size());
  8121. }
  8122. // A handler that serves an already-encoded file names the coding itself. The
  8123. // file-backed path decided its coding from Accept-Encoding and the content
  8124. // type alone, so it compressed the stored bytes a second time and appended a
  8125. // second Content-Encoding field line.
  8126. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8127. auto port = start(enable_without_floor);
  8128. Client cli(HOST, port);
  8129. cli.set_decompress(false);
  8130. auto res = cli.Get("/pre-encoded-file-content",
  8131. Headers{{"Accept-Encoding", "gzip"}});
  8132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8133. EXPECT_EQ(StatusCode::OK_200, res->status);
  8134. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8135. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8136. // Vary belongs to a coding the server chose, and it chose none here.
  8137. EXPECT_FALSE(res->has_header("Vary"));
  8138. // The file travels exactly as it is stored on disk.
  8139. EXPECT_EQ(104U, res->body.size());
  8140. }
  8141. // The 1MB file clears the default floor, so this one runs the configuration a
  8142. // deployment would actually have.
  8143. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8144. auto port = start(enable);
  8145. Client cli(HOST, port);
  8146. cli.set_decompress(false);
  8147. auto res =
  8148. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8150. EXPECT_EQ(StatusCode::OK_200, res->status);
  8151. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8152. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8153. EXPECT_FALSE(res->has_header("Vary"));
  8154. EXPECT_EQ(1048576U, res->body.size());
  8155. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8156. }
  8157. TEST_F(StaticFileCompressionTest, Head) {
  8158. auto port = start(enable);
  8159. Client cli(HOST, port);
  8160. cli.set_decompress(false);
  8161. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8162. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8163. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8165. EXPECT_EQ(StatusCode::OK_200, res->status);
  8166. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8167. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8168. // HEAD still reports the size a GET would return.
  8169. EXPECT_EQ(get->get_header_value("Content-Length"),
  8170. res->get_header_value("Content-Length"));
  8171. EXPECT_TRUE(res->body.empty());
  8172. }
  8173. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8174. auto port = start(enable);
  8175. Client cli(HOST, port);
  8176. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8177. {"Accept-Encoding", "gzip"}});
  8178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8179. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8180. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8181. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8182. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8183. EXPECT_EQ("cd", res->body);
  8184. }
  8185. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8186. auto port = start(enable);
  8187. Client cli(HOST, port);
  8188. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8190. EXPECT_EQ(StatusCode::OK_200, res->status);
  8191. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8192. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8193. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8194. }
  8195. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8196. auto port = start(enable);
  8197. Client cli(HOST, port);
  8198. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8200. EXPECT_EQ(StatusCode::OK_200, res->status);
  8201. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8202. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8203. EXPECT_TRUE(res->body.empty());
  8204. }
  8205. TEST_F(StaticFileCompressionTest, MinLength) {
  8206. auto port = start(enable);
  8207. Client cli(HOST, port);
  8208. // 104 bytes, well under the default floor. Compressing it would add the
  8209. // gzip header and trailer to a body that already fits in one packet.
  8210. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8211. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8212. EXPECT_EQ(StatusCode::OK_200, res->status);
  8213. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8214. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8215. }
  8216. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8217. auto port = start([](Server &svr) {
  8218. svr.set_static_file_compression(true);
  8219. svr.set_static_file_compression_min_length(1);
  8220. });
  8221. Client cli(HOST, port);
  8222. cli.set_decompress(false);
  8223. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8226. // A 9-byte file comes back larger than it went in, because gzip's header and
  8227. // trailer outweigh anything deflate can save. That is the end of the range
  8228. // the floor exists to keep out.
  8229. EXPECT_GT(res->body.size(), 9U);
  8230. }
  8231. TEST_F(StaticFileCompressionTest, MaxLength) {
  8232. auto port = start([](Server &svr) {
  8233. svr.set_static_file_compression(true);
  8234. svr.set_static_file_compression_min_length(0);
  8235. svr.set_static_file_compression_max_length(1024);
  8236. });
  8237. Client cli(HOST, port);
  8238. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8239. // defines `small` as a macro on Windows.
  8240. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8241. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8242. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8243. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8244. // Under it: compressed.
  8245. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8246. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8247. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8248. }
  8249. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8250. auto port = start(enable_without_floor);
  8251. Client cli(HOST, port);
  8252. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8253. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8254. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8255. auto identity_etag = identity->get_header_value("ETag");
  8256. ASSERT_FALSE(identity_etag.empty());
  8257. auto gzipped =
  8258. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8259. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8260. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8261. auto gzip_etag = gzipped->get_header_value("ETag");
  8262. ASSERT_FALSE(gzip_etag.empty());
  8263. // Two representations, two validators.
  8264. EXPECT_NE(identity_etag, gzip_etag);
  8265. // Each one revalidates against the request that would produce it...
  8266. auto fresh =
  8267. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8268. {"If-None-Match", gzip_etag}});
  8269. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8270. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8271. auto fresh_identity =
  8272. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8273. {"If-None-Match", identity_etag}});
  8274. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8275. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8276. // ...and not against the other representation.
  8277. auto crossed =
  8278. cli.Get("/dir/index.html",
  8279. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8280. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8281. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8282. }
  8283. // The opt-in covers responses the server reads off disk itself. A caller's own
  8284. // known-length provider keeps its Content-Length and, more importantly, keeps
  8285. // delivering incrementally: routing it through a compressor would hold every
  8286. // write back until zlib's window filled.
  8287. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8288. auto port = start(enable);
  8289. Client cli(HOST, port);
  8290. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8292. EXPECT_EQ(StatusCode::OK_200, res->status);
  8293. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8294. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8295. EXPECT_EQ("aaabbb", res->body);
  8296. }
  8297. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8298. auto port = start(enable);
  8299. Client cli(HOST, port);
  8300. cli.set_read_timeout(1, 0);
  8301. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8302. Headers{{"Accept-Encoding", "gzip"}});
  8303. ASSERT_TRUE(handle.is_valid());
  8304. // The provider writes 100 bytes and then stalls for longer than the read
  8305. // timeout. Those first bytes have to arrive anyway: run the response through
  8306. // a compressor and zlib holds them until its window fills, so the read would
  8307. // come back empty instead.
  8308. char buf[256];
  8309. auto n = handle.read(buf, sizeof(buf));
  8310. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8311. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8312. }
  8313. #endif
  8314. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8315. TEST_F(ServerTest, Brotli) {
  8316. Headers headers;
  8317. headers.emplace("Accept-Encoding", "br");
  8318. auto res = cli_.Get("/compress", headers);
  8319. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8320. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8321. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8322. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8323. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8324. "7890123456789012345678901234567890",
  8325. res->body);
  8326. EXPECT_EQ(StatusCode::OK_200, res->status);
  8327. }
  8328. #endif
  8329. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8330. TEST_F(ServerTest, Zstd) {
  8331. Headers headers;
  8332. headers.emplace("Accept-Encoding", "zstd");
  8333. auto res = cli_.Get("/compress", headers);
  8334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8335. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8336. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8337. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8338. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8339. "7890123456789012345678901234567890",
  8340. res->body);
  8341. EXPECT_EQ(StatusCode::OK_200, res->status);
  8342. }
  8343. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8344. Headers headers;
  8345. headers.emplace("Accept-Encoding", "");
  8346. auto res = cli_.Get("/compress", headers);
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8349. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8350. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8351. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8352. "7890123456789012345678901234567890",
  8353. res->body);
  8354. EXPECT_EQ(StatusCode::OK_200, res->status);
  8355. }
  8356. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8357. Headers headers;
  8358. headers.emplace("Accept-Encoding", "zstd");
  8359. std::string body;
  8360. auto res = cli_.Get("/compress", headers,
  8361. [&](const char *data, uint64_t data_length) {
  8362. EXPECT_EQ(100U, data_length);
  8363. body.append(data, data_length);
  8364. return true;
  8365. });
  8366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8367. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8368. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8369. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8370. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8371. "7890123456789012345678901234567890",
  8372. body);
  8373. EXPECT_EQ(StatusCode::OK_200, res->status);
  8374. }
  8375. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8376. Headers headers;
  8377. headers.emplace("Accept-Encoding", "zstd");
  8378. cli_.set_decompress(false);
  8379. auto res = cli_.Get("/compress", headers);
  8380. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8381. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8382. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8383. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8385. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8386. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8387. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8388. EXPECT_EQ(StatusCode::OK_200, res->status);
  8389. ASSERT_EQ(26U, res->body.size());
  8390. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8391. 0);
  8392. }
  8393. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8394. Headers headers;
  8395. headers.emplace("Accept-Encoding", "");
  8396. std::string body;
  8397. auto res = cli_.Get("/compress", headers,
  8398. [&](const char *data, uint64_t data_length) {
  8399. EXPECT_EQ(100U, data_length);
  8400. body.append(data, data_length);
  8401. return true;
  8402. });
  8403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8404. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8405. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8406. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8407. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8408. "7890123456789012345678901234567890",
  8409. body);
  8410. EXPECT_EQ(StatusCode::OK_200, res->status);
  8411. }
  8412. TEST_F(ServerTest, NoZstd) {
  8413. Headers headers;
  8414. headers.emplace("Accept-Encoding", "zstd");
  8415. auto res = cli_.Get("/nocompress", headers);
  8416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8417. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8418. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8419. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8420. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8421. "7890123456789012345678901234567890",
  8422. res->body);
  8423. EXPECT_EQ(StatusCode::OK_200, res->status);
  8424. }
  8425. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8426. Headers headers;
  8427. headers.emplace("Accept-Encoding", "zstd");
  8428. std::string body;
  8429. auto res = cli_.Get("/nocompress", headers,
  8430. [&](const char *data, uint64_t data_length) {
  8431. EXPECT_EQ(100U, data_length);
  8432. body.append(data, data_length);
  8433. return true;
  8434. });
  8435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8436. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8437. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8438. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8439. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8440. "7890123456789012345678901234567890",
  8441. body);
  8442. EXPECT_EQ(StatusCode::OK_200, res->status);
  8443. }
  8444. // TODO: How to enable zstd ??
  8445. TEST_F(ServerTest, MultipartFormDataZstd) {
  8446. UploadFormDataItems items = {
  8447. {"key1", "test", "", ""},
  8448. {"key2", "--abcdefg123", "", ""},
  8449. };
  8450. Headers headers;
  8451. headers.emplace("Accept-Encoding", "zstd");
  8452. cli_.set_compress(true);
  8453. auto res = cli_.Post("/compress-multipart", headers, items);
  8454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8455. EXPECT_EQ(StatusCode::OK_200, res->status);
  8456. }
  8457. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8458. Headers headers;
  8459. headers.emplace("Accept-Encoding", "zstd");
  8460. cli_.set_compress(true);
  8461. auto res = cli_.Put(
  8462. "/put", headers, 3,
  8463. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8464. sink.os << "PUT";
  8465. return true;
  8466. },
  8467. "text/plain");
  8468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8469. EXPECT_EQ(StatusCode::OK_200, res->status);
  8470. EXPECT_EQ("PUT", res->body);
  8471. }
  8472. // Pre-compression logging tests
  8473. TEST_F(ServerTest, PreCompressionLogging) {
  8474. // Test data for compression (matches the actual /compress endpoint content)
  8475. const std::string test_content =
  8476. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8477. "3456789012345678901234567890";
  8478. // Variables to capture logging data
  8479. std::string pre_compression_body;
  8480. std::string pre_compression_content_type;
  8481. std::string pre_compression_content_encoding;
  8482. std::string post_compression_body;
  8483. std::string post_compression_content_type;
  8484. std::string post_compression_content_encoding;
  8485. // Set up pre-compression logger
  8486. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8487. const Response &res) {
  8488. pre_compression_body = res.body;
  8489. pre_compression_content_type = res.get_header_value("Content-Type");
  8490. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8491. });
  8492. // Set up post-compression logger
  8493. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8494. post_compression_body = res.body;
  8495. post_compression_content_type = res.get_header_value("Content-Type");
  8496. post_compression_content_encoding =
  8497. res.get_header_value("Content-Encoding");
  8498. });
  8499. // Test with gzip compression
  8500. Headers headers;
  8501. headers.emplace("Accept-Encoding", "gzip");
  8502. auto res = cli_.Get("/compress", headers);
  8503. // Verify response was compressed
  8504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8505. EXPECT_EQ(StatusCode::OK_200, res->status);
  8506. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8507. // Verify pre-compression logger captured uncompressed content
  8508. EXPECT_EQ(test_content, pre_compression_body);
  8509. EXPECT_EQ("text/plain", pre_compression_content_type);
  8510. EXPECT_TRUE(pre_compression_content_encoding
  8511. .empty()); // No encoding header before compression
  8512. // Verify post-compression logger captured compressed content
  8513. EXPECT_NE(test_content,
  8514. post_compression_body); // Should be different after compression
  8515. EXPECT_EQ("text/plain", post_compression_content_type);
  8516. EXPECT_EQ("gzip", post_compression_content_encoding);
  8517. // Verify compressed content is smaller
  8518. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8519. }
  8520. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8521. const std::string test_content =
  8522. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8523. "3456789012345678901234567890";
  8524. std::string pre_compression_body;
  8525. std::string post_compression_body;
  8526. svr_.set_pre_compression_logger(
  8527. [&](const Request & /*req*/, const Response &res) {
  8528. pre_compression_body = res.body;
  8529. });
  8530. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8531. post_compression_body = res.body;
  8532. });
  8533. Headers headers;
  8534. headers.emplace("Accept-Encoding", "br");
  8535. auto res = cli_.Get("/compress", headers);
  8536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8537. EXPECT_EQ(StatusCode::OK_200, res->status);
  8538. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8539. // Verify pre-compression content is uncompressed
  8540. EXPECT_EQ(test_content, pre_compression_body);
  8541. // Verify post-compression content is compressed
  8542. EXPECT_NE(test_content, post_compression_body);
  8543. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8544. }
  8545. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8546. const std::string test_content =
  8547. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8548. "3456789012345678901234567890";
  8549. std::string pre_compression_body;
  8550. std::string post_compression_body;
  8551. svr_.set_pre_compression_logger(
  8552. [&](const Request & /*req*/, const Response &res) {
  8553. pre_compression_body = res.body;
  8554. });
  8555. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8556. post_compression_body = res.body;
  8557. });
  8558. // Request without compression (use /nocompress endpoint)
  8559. Headers headers;
  8560. auto res = cli_.Get("/nocompress", headers);
  8561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8562. EXPECT_EQ(StatusCode::OK_200, res->status);
  8563. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8564. // Pre-compression logger should not be called when no compression is applied
  8565. EXPECT_TRUE(
  8566. pre_compression_body.empty()); // Pre-compression logger not called
  8567. EXPECT_EQ(
  8568. test_content,
  8569. post_compression_body); // Post-compression logger captures final content
  8570. }
  8571. TEST_F(ServerTest, LoggerSeesContentLength) {
  8572. size_t logged_content_length = 0;
  8573. std::string logged_content_length_header;
  8574. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8575. logged_content_length = res.content_length_;
  8576. logged_content_length_header = res.get_header_value("Content-Length");
  8577. });
  8578. auto res = cli_.Get("/nocompress");
  8579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8580. EXPECT_EQ(StatusCode::OK_200, res->status);
  8581. EXPECT_EQ(res->body.size(), logged_content_length);
  8582. EXPECT_EQ(std::to_string(logged_content_length),
  8583. logged_content_length_header);
  8584. }
  8585. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8586. const std::string test_content =
  8587. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8588. "3456789012345678901234567890";
  8589. std::string pre_compression_body;
  8590. bool pre_logger_called = false;
  8591. // Set only pre-compression logger
  8592. svr_.set_pre_compression_logger(
  8593. [&](const Request & /*req*/, const Response &res) {
  8594. pre_compression_body = res.body;
  8595. pre_logger_called = true;
  8596. });
  8597. Headers headers;
  8598. headers.emplace("Accept-Encoding", "gzip");
  8599. auto res = cli_.Get("/compress", headers);
  8600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8601. EXPECT_EQ(StatusCode::OK_200, res->status);
  8602. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8603. // Verify pre-compression logger was called
  8604. EXPECT_TRUE(pre_logger_called);
  8605. EXPECT_EQ(test_content, pre_compression_body);
  8606. }
  8607. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8608. {
  8609. // Test with Expect: 100-continue header - success case
  8610. // Server returns 100 Continue, client sends body, server returns 200 OK
  8611. Request req;
  8612. req.method = "POST";
  8613. req.path = "/post-large";
  8614. req.set_header("Expect", "100-continue");
  8615. req.body = LARGE_DATA;
  8616. Response res;
  8617. auto error = Error::Success;
  8618. cli_.set_keep_alive(true);
  8619. auto ret = cli_.send(req, res, error);
  8620. EXPECT_TRUE(ret);
  8621. EXPECT_EQ(StatusCode::OK_200, res.status);
  8622. EXPECT_EQ(LARGE_DATA, res.body);
  8623. }
  8624. {
  8625. // Test with Expect: 100-continue header - error case
  8626. // Client should not send the body when server returns an error
  8627. Request req;
  8628. req.method = "POST";
  8629. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8630. req.set_header("Expect", "100-continue");
  8631. req.body = LARGE_DATA;
  8632. Response res;
  8633. auto error = Error::Success;
  8634. auto start = std::chrono::high_resolution_clock::now();
  8635. cli_.set_keep_alive(true);
  8636. auto ret = cli_.send(req, res, error);
  8637. auto end = std::chrono::high_resolution_clock::now();
  8638. auto elapsed =
  8639. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8640. .count();
  8641. // With Expect: 100-continue, request completes successfully but with error
  8642. EXPECT_TRUE(ret);
  8643. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8644. EXPECT_EQ("close", res.get_header_value("Connection"));
  8645. EXPECT_FALSE(cli_.is_socket_open());
  8646. EXPECT_LE(elapsed, 2000);
  8647. }
  8648. {
  8649. // Send an extra GET request to ensure error recovery without hanging
  8650. Request req;
  8651. req.method = "GET";
  8652. req.path = "/hi";
  8653. auto start = std::chrono::high_resolution_clock::now();
  8654. auto res = cli_.send(req);
  8655. auto end = std::chrono::high_resolution_clock::now();
  8656. auto elapsed =
  8657. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8658. .count();
  8659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8660. EXPECT_EQ(StatusCode::OK_200, res->status);
  8661. EXPECT_EQ("Hello World!", res->body);
  8662. EXPECT_LE(elapsed, 500);
  8663. }
  8664. }
  8665. TEST(ZstdDecompressor, ChunkedDecompression) {
  8666. std::string data;
  8667. for (size_t i = 0; i < 32 * 1024; ++i) {
  8668. data.push_back(static_cast<char>('a' + i % 26));
  8669. }
  8670. std::string compressed_data;
  8671. {
  8672. httplib::detail::zstd_compressor compressor;
  8673. bool result = compressor.compress(
  8674. data.data(), data.size(),
  8675. /*last=*/true,
  8676. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8677. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8678. compressed_data_size);
  8679. return true;
  8680. });
  8681. ASSERT_TRUE(result);
  8682. }
  8683. std::string decompressed_data;
  8684. {
  8685. httplib::detail::zstd_decompressor decompressor;
  8686. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8687. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8688. size_t chunk_size = 130;
  8689. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8690. chunk_begin += chunk_size) {
  8691. size_t current_chunk_size =
  8692. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8693. bool result = decompressor.decompress(
  8694. compressed_data.data() + chunk_begin, current_chunk_size,
  8695. [&](const char *decompressed_data_chunk,
  8696. size_t decompressed_data_chunk_size) {
  8697. decompressed_data.insert(decompressed_data.size(),
  8698. decompressed_data_chunk,
  8699. decompressed_data_chunk_size);
  8700. return true;
  8701. });
  8702. ASSERT_TRUE(result);
  8703. }
  8704. }
  8705. ASSERT_EQ(data, decompressed_data);
  8706. }
  8707. TEST(ZstdDecompressor, Decompress) {
  8708. std::string original_text = "Compressed with ZSTD";
  8709. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8710. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8711. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8712. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8713. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8714. std::string decompressed_data;
  8715. {
  8716. httplib::detail::zstd_decompressor decompressor;
  8717. bool result = decompressor.decompress(
  8718. compressed_data.data(), compressed_data.size(),
  8719. [&](const char *decompressed_data_chunk,
  8720. size_t decompressed_data_chunk_size) {
  8721. decompressed_data.insert(decompressed_data.size(),
  8722. decompressed_data_chunk,
  8723. decompressed_data_chunk_size);
  8724. return true;
  8725. });
  8726. ASSERT_TRUE(result);
  8727. }
  8728. ASSERT_EQ(original_text, decompressed_data);
  8729. }
  8730. #endif
  8731. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8732. // separate chunks so that the server sees each part in its own read(). Used to
  8733. // place a read boundary at a specific offset of a request body.
  8734. static bool send_request_in_parts(time_t read_timeout_sec,
  8735. const std::vector<std::string> &parts,
  8736. std::string *resp = nullptr,
  8737. int port = PORT) {
  8738. auto error = Error::Success;
  8739. auto client_sock = detail::create_client_socket(
  8740. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8741. /*connection_timeout_sec=*/5, 0,
  8742. /*read_timeout_sec=*/5, 0,
  8743. /*write_timeout_sec=*/5, 0, std::string(), error);
  8744. if (client_sock == INVALID_SOCKET) { return false; }
  8745. auto ret = detail::process_client_socket(
  8746. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8747. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8748. for (size_t i = 0; i < parts.size(); i++) {
  8749. const auto &part = parts[i];
  8750. if (part.size() !=
  8751. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8752. return false;
  8753. }
  8754. if (i + 1 < parts.size()) {
  8755. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8756. }
  8757. }
  8758. char buf[512];
  8759. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8760. while (line_reader.getline()) {
  8761. if (resp) { *resp += line_reader.ptr(); }
  8762. }
  8763. return true;
  8764. });
  8765. detail::close_socket(client_sock);
  8766. return ret;
  8767. }
  8768. // Sends a raw request to a server listening at HOST:PORT.
  8769. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8770. std::string *resp = nullptr, int port = PORT) {
  8771. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8772. }
  8773. #ifdef CPPHTTPLIB_SSL_ENABLED
  8774. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  8775. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  8776. ASSERT_TRUE(svr.is_valid());
  8777. svr.set_read_timeout(1, 0);
  8778. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  8779. auto se = detail::scope_exit([&] {
  8780. svr.stop();
  8781. t.join();
  8782. ASSERT_FALSE(svr.is_running());
  8783. });
  8784. svr.wait_until_ready();
  8785. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  8786. // keeps each wait well within the read timeout. The server gives up a
  8787. // second in, so the bytes sent after that fail.
  8788. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  8789. parts.resize(26, std::string(1, '\0'));
  8790. EXPECT_FALSE(send_request_in_parts(5, parts));
  8791. }
  8792. #endif
  8793. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8794. Server svr;
  8795. std::string header_value;
  8796. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8797. header_value = req.get_header_value("foo");
  8798. res.set_content("ok", "text/plain");
  8799. });
  8800. thread t = thread([&] { svr.listen(HOST, PORT); });
  8801. auto se = detail::scope_exit([&] {
  8802. svr.stop();
  8803. t.join();
  8804. ASSERT_FALSE(svr.is_running());
  8805. });
  8806. svr.wait_until_ready();
  8807. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8808. // like characters are not treated the same - use vertical tab and escape.
  8809. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8810. "foo: \t \v bar \x1B\t \r\n"
  8811. "Connection: close\r\n"
  8812. "\r\n";
  8813. std::string res;
  8814. ASSERT_TRUE(send_request(5, req, &res));
  8815. EXPECT_EQ(header_value, "");
  8816. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8817. }
  8818. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8819. Server svr;
  8820. std::string received;
  8821. svr.Get("/order", [&](const Request &req, Response &res) {
  8822. received = entries_to_string(req.headers);
  8823. res.set_content("ok", "text/plain");
  8824. });
  8825. auto port = svr.bind_to_any_port(HOST);
  8826. thread t = thread([&] { svr.listen_after_bind(); });
  8827. auto se = detail::scope_exit([&] {
  8828. svr.stop();
  8829. t.join();
  8830. ASSERT_FALSE(svr.is_running());
  8831. });
  8832. svr.wait_until_ready();
  8833. const std::string req = "GET /order HTTP/1.1\r\n"
  8834. "Host: localhost\r\n"
  8835. "X-First: 1\r\n"
  8836. "X-Dup: a\r\n"
  8837. "X-Second: 2\r\n"
  8838. "X-Dup: b\r\n"
  8839. "Connection: close\r\n"
  8840. "\r\n";
  8841. std::string res;
  8842. ASSERT_TRUE(send_request(5, req, &res, port));
  8843. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8844. EXPECT_EQ(
  8845. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  8846. received);
  8847. }
  8848. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8849. Server svr;
  8850. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8851. res.set_header("Set-Cookie", "first=1");
  8852. res.set_header("X-Between", "y");
  8853. res.set_header("Set-Cookie", "second=2");
  8854. res.set_content("ok", "text/plain");
  8855. });
  8856. auto port = svr.bind_to_any_port(HOST);
  8857. thread t = thread([&] { svr.listen_after_bind(); });
  8858. auto se = detail::scope_exit([&] {
  8859. svr.stop();
  8860. t.join();
  8861. ASSERT_FALSE(svr.is_running());
  8862. });
  8863. svr.wait_until_ready();
  8864. Client cli(HOST, port);
  8865. auto res = cli.Get("/cookies");
  8866. ASSERT_TRUE(res);
  8867. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8868. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8869. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8870. }
  8871. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8872. Server svr;
  8873. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8874. auto i = new int(0);
  8875. res.set_header("Trailer", "X-Safe, X-Reflected");
  8876. res.set_chunked_content_provider(
  8877. "text/plain",
  8878. [i](size_t /*offset*/, DataSink &sink) {
  8879. if (*i == 0) {
  8880. sink.os << "body";
  8881. } else {
  8882. Headers trailer;
  8883. // A valid trailer that must survive.
  8884. trailer.emplace("X-Safe", "safe");
  8885. // Attacker-controlled value carrying CR/LF (response splitting).
  8886. trailer.emplace("X-Reflected",
  8887. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8888. // Attacker-controlled name carrying CR/LF.
  8889. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8890. sink.done_with_trailer(trailer);
  8891. }
  8892. (*i)++;
  8893. return true;
  8894. },
  8895. [i](bool /*success*/) { delete i; });
  8896. });
  8897. thread t = thread([&] { svr.listen(HOST, PORT); });
  8898. auto se = detail::scope_exit([&] {
  8899. svr.stop();
  8900. t.join();
  8901. ASSERT_FALSE(svr.is_running());
  8902. });
  8903. svr.wait_until_ready();
  8904. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8905. "Host: " + HOST +
  8906. "\r\n"
  8907. "Connection: close\r\n"
  8908. "\r\n";
  8909. std::string res;
  8910. ASSERT_TRUE(send_request(5, req, &res));
  8911. // The injected fields must not appear anywhere in the raw response.
  8912. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8913. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8914. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8915. // Invalid trailers are dropped entirely, matching set_header().
  8916. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8917. // The valid trailer still passes through.
  8918. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8919. }
  8920. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8921. Server svr;
  8922. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8923. // res.headers is a public field an application can populate directly,
  8924. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8925. // A valid header that must survive.
  8926. res.headers.emplace("X-Safe", "safe");
  8927. // Attacker-controlled value carrying CR/LF (response splitting).
  8928. res.headers.emplace("X-Reflected",
  8929. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8930. // Attacker-controlled name carrying CR/LF.
  8931. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8932. res.set_content("body", "text/plain");
  8933. });
  8934. thread t = thread([&] { svr.listen(HOST, PORT); });
  8935. auto se = detail::scope_exit([&] {
  8936. svr.stop();
  8937. t.join();
  8938. ASSERT_FALSE(svr.is_running());
  8939. });
  8940. svr.wait_until_ready();
  8941. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8942. "Host: " + HOST +
  8943. "\r\n"
  8944. "Connection: close\r\n"
  8945. "\r\n";
  8946. std::string res;
  8947. ASSERT_TRUE(send_request(5, req, &res));
  8948. // The injected fields must not appear anywhere in the raw response.
  8949. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8950. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8951. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8952. // Invalid headers are dropped entirely, matching set_header().
  8953. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8954. // The valid header still passes through.
  8955. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8956. }
  8957. // Forward declaration: in split builds split.py strips `inline` and moves the
  8958. // definition into httplib.cc, so detail::write_request_line is not visible from
  8959. // the public httplib.h. Re-declaring it here lets the tests link against the
  8960. // symbol in both header-only and split builds.
  8961. namespace httplib {
  8962. namespace detail {
  8963. ssize_t write_request_line(Stream &strm, const std::string &method,
  8964. const std::string &path);
  8965. } // namespace detail
  8966. } // namespace httplib
  8967. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  8968. // A well-formed target is written verbatim.
  8969. {
  8970. detail::BufferStream strm;
  8971. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8972. EXPECT_GT(n, 0);
  8973. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8974. }
  8975. // A target carrying CR/LF, SP or other control octets must be rejected
  8976. // before anything reaches the wire, otherwise it splits the request line and
  8977. // injects a header or a whole request.
  8978. const std::string evil_targets[] = {
  8979. "/a\r\nInjected: pwned",
  8980. "/a\rInjected",
  8981. "/a\nInjected",
  8982. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8983. "/a b",
  8984. "/a\tb",
  8985. "/a\x7f",
  8986. };
  8987. for (const auto &evil : evil_targets) {
  8988. detail::BufferStream strm;
  8989. auto n = detail::write_request_line(strm, "GET", evil);
  8990. EXPECT_LT(n, 0);
  8991. EXPECT_TRUE(strm.get_buffer().empty());
  8992. }
  8993. }
  8994. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8995. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  8996. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  8997. // target reaches write_request. The client must fail cleanly with
  8998. // Error::Write instead of putting a request-line-less, header-injecting
  8999. // request on the wire.
  9000. Server svr;
  9001. svr.Get("/a", [](const Request &, Response &res) {
  9002. res.set_content("ok", "text/plain");
  9003. });
  9004. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9005. auto se = detail::scope_exit([&] {
  9006. svr.stop();
  9007. thread.join();
  9008. ASSERT_FALSE(svr.is_running());
  9009. });
  9010. svr.wait_until_ready();
  9011. {
  9012. Client cli(HOST, PORT);
  9013. cli.set_path_encode(false);
  9014. // The request is rejected before anything is written, so the connection
  9015. // stays silent and the subsequent response read would otherwise block for
  9016. // the full default read timeout. Shorten it -- the assertion is on the
  9017. // error, not the timeout.
  9018. cli.set_read_timeout(1, 0);
  9019. auto res = cli.Get("/a\r\nInjected: pwned");
  9020. EXPECT_FALSE(res);
  9021. EXPECT_EQ(Error::Write, res.error());
  9022. }
  9023. }
  9024. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9025. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9026. // including extension methods.
  9027. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9028. for (const auto &method : good_methods) {
  9029. detail::BufferStream strm;
  9030. auto n = detail::write_request_line(strm, method, "/");
  9031. EXPECT_GT(n, 0);
  9032. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9033. }
  9034. // A method carrying CR/LF would split the request line and smuggle a whole
  9035. // request ahead of the real one. A space or an empty method corrupts the
  9036. // request line. All must be rejected before anything reaches the wire.
  9037. const std::string evil_methods[] = {
  9038. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9039. "GET\r\nInjected: pwned",
  9040. "GET\r",
  9041. "GET\n",
  9042. "GE T",
  9043. "",
  9044. };
  9045. for (const auto &evil : evil_methods) {
  9046. detail::BufferStream strm;
  9047. auto n = detail::write_request_line(strm, evil, "/");
  9048. EXPECT_LT(n, 0);
  9049. EXPECT_TRUE(strm.get_buffer().empty());
  9050. }
  9051. }
  9052. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9053. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9054. // through Client::send must fail with Error::Write and no request, neither
  9055. // the smuggled one nor the real one, may reach the server.
  9056. Server svr;
  9057. std::atomic<int> request_count(0);
  9058. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9059. request_count++;
  9060. res.status = StatusCode::OK_200;
  9061. return Server::HandlerResponse::Handled;
  9062. });
  9063. auto port = svr.bind_to_any_port(HOST);
  9064. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9065. auto se = detail::scope_exit([&] {
  9066. svr.stop();
  9067. thread.join();
  9068. ASSERT_FALSE(svr.is_running());
  9069. });
  9070. svr.wait_until_ready();
  9071. {
  9072. Client cli(HOST, port);
  9073. const std::string evil_methods[] = {
  9074. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9075. "GE T",
  9076. "",
  9077. };
  9078. for (const auto &evil : evil_methods) {
  9079. Request req;
  9080. req.method = evil;
  9081. req.path = "/";
  9082. auto res = cli.send(req);
  9083. EXPECT_FALSE(res);
  9084. EXPECT_EQ(Error::Write, res.error());
  9085. }
  9086. auto handle =
  9087. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9088. EXPECT_FALSE(handle.is_valid());
  9089. EXPECT_EQ(Error::Write, handle.error);
  9090. // A valid request on the same client still goes through.
  9091. auto res = cli.Get("/");
  9092. ASSERT_TRUE(res);
  9093. EXPECT_EQ(StatusCode::OK_200, res->status);
  9094. }
  9095. EXPECT_EQ(1, request_count.load());
  9096. }
  9097. // Sends a raw request and verifies that there isn't a crash or exception.
  9098. static void test_raw_request(const std::string &req,
  9099. std::string *out = nullptr) {
  9100. Server svr;
  9101. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9102. res.set_content("ok", "text/plain");
  9103. });
  9104. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9105. res.set_content("ok", "text/plain");
  9106. });
  9107. svr.Get("/header_field_value_check",
  9108. [&](const Request & /*req*/, Response &res) {
  9109. res.set_content("ok", "text/plain");
  9110. });
  9111. svr.CustomRoute("PROPFIND", "/dav",
  9112. [&](const Request & /*req*/, Response &res) {
  9113. res.status = StatusCode::MultiStatus_207;
  9114. });
  9115. // Server read timeout must be longer than the client read timeout for the
  9116. // bug to reproduce, probably to force the server to process a request
  9117. // without a trailing blank line.
  9118. const time_t client_read_timeout_sec = 1;
  9119. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9120. bool listen_thread_ok = false;
  9121. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9122. auto se = detail::scope_exit([&] {
  9123. svr.stop();
  9124. t.join();
  9125. ASSERT_FALSE(svr.is_running());
  9126. EXPECT_TRUE(listen_thread_ok);
  9127. });
  9128. svr.wait_until_ready();
  9129. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9130. }
  9131. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9132. // A certain header line causes an exception if the header property is parsed
  9133. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9134. test_raw_request(
  9135. "GET /hi HTTP/1.1\r\n"
  9136. " : "
  9137. " "
  9138. " ");
  9139. }
  9140. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9141. // A certain header line causes an exception if the header property *name* is
  9142. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9143. // greedy matcher and requires backtracking when there are a lot of ":"
  9144. // characters.
  9145. // This occurs with libc++ but not libstdc++.
  9146. test_raw_request(
  9147. "GET /hi HTTP/1.1\r\n"
  9148. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9149. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9150. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9151. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9152. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9153. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9154. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9155. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9156. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9157. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9158. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9159. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9160. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9161. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9162. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9163. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9164. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9165. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9166. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9167. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9168. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9169. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9170. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9171. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9172. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9173. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9174. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9175. "&&&%%%");
  9176. }
  9177. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9178. // Make sure this doesn't crash the server.
  9179. // In a previous version of the header line regex, the "\r" rendered the line
  9180. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9181. // a new position where the leading white space ended and the field value
  9182. // began.
  9183. // The crash occurs with libc++ but not libstdc++.
  9184. test_raw_request("GET /hi HTTP/1.1\r\n"
  9185. "a:" +
  9186. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9187. "\r\n"
  9188. "\r\n");
  9189. }
  9190. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9191. const char *rejected[] = {
  9192. // RFC 9112 §3: one SP between the parts, and nothing else
  9193. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9194. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9195. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9196. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9197. // A request-target has no fragment
  9198. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9199. // An HTTP/1.1 request needs a Host
  9200. "GET /hi HTTP/1.1\r\n\r\n",
  9201. };
  9202. for (auto request : rejected) {
  9203. std::string out;
  9204. test_raw_request(request, &out);
  9205. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9206. }
  9207. std::string out;
  9208. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9209. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9210. }
  9211. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9212. // RFC 9112 §6.1
  9213. const char *requests[] = {
  9214. "PUT /put_hi HTTP/1.1\r\n"
  9215. "Host: localhost\r\n"
  9216. "Content-Length: 0\r\n"
  9217. "Transfer-Encoding: chunked\r\n"
  9218. "\r\n"
  9219. "0\r\n\r\n",
  9220. "PUT /put_hi HTTP/1.0\r\n"
  9221. "Connection: keep-alive\r\n"
  9222. "Transfer-Encoding: chunked\r\n"
  9223. "\r\n"
  9224. "0\r\n\r\n",
  9225. };
  9226. for (auto request : requests) {
  9227. std::string out;
  9228. test_raw_request(request, &out);
  9229. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9230. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9231. }
  9232. }
  9233. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9234. std::string out;
  9235. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9236. "Content-Type: text/plain\r\n"
  9237. "Transfer-Encoding: chunked\r\n"
  9238. "\r\n"
  9239. "nothex\r\n",
  9240. &out);
  9241. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9242. }
  9243. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9244. std::string out;
  9245. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9246. "Content-Type: text/plain\r\n"
  9247. "Transfer-Encoding: chunked\r\n"
  9248. "\r\n"
  9249. "3\r\n"
  9250. "xyz\r\n"
  9251. "NaN\r\n",
  9252. &out);
  9253. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9254. }
  9255. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9256. std::string out;
  9257. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9258. "Content-Type: text/plain\r\n"
  9259. "Transfer-Encoding: chunked\r\n"
  9260. "\r\n"
  9261. // Length is too large for 64 bits.
  9262. "1ffffffffffffffff\r\n"
  9263. "xyz\r\n",
  9264. &out);
  9265. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9266. }
  9267. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9268. test_raw_request("GET /hi HTTP/1.1\r\n"
  9269. "Content-Type: text/plain\r\n\r");
  9270. }
  9271. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9272. std::string out;
  9273. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9274. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9275. }
  9276. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9277. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9278. std::string out;
  9279. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9280. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9281. }
  9282. }
  9283. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9284. std::string out;
  9285. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9286. "Host: localhost\r\n"
  9287. "Connection: close\r\n\r\n",
  9288. &out);
  9289. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9290. }
  9291. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9292. Server svr;
  9293. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9294. EXPECT_TRUE(!req.remote_addr.empty());
  9295. });
  9296. thread t = thread([&] { svr.listen(HOST, PORT); });
  9297. auto se = detail::scope_exit([&] {
  9298. svr.stop();
  9299. t.join();
  9300. ASSERT_FALSE(svr.is_running());
  9301. });
  9302. svr.wait_until_ready();
  9303. // Send an invalid request line to trigger Bad Request
  9304. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9305. std::string out;
  9306. ASSERT_TRUE(send_request(5, bad_req, &out));
  9307. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9308. }
  9309. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9310. // answered right away rather than blocking on a read that waits for EOF.
  9311. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9312. std::string out;
  9313. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9314. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9315. }
  9316. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9317. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9318. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9319. for (const auto *method : methods) {
  9320. Server svr;
  9321. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9322. EXPECT_FALSE(svr.is_valid()) << method;
  9323. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  9324. }
  9325. }
  9326. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  9327. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  9328. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  9329. for (const auto *method : methods) {
  9330. Server svr;
  9331. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9332. EXPECT_FALSE(svr.is_valid()) << method;
  9333. }
  9334. }
  9335. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  9336. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  9337. "COPY", "MOVE", "LOCK",
  9338. "UNLOCK", "REPORT", "SUBSCRIBE"};
  9339. Server svr;
  9340. for (const auto *method : methods) {
  9341. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  9342. }
  9343. EXPECT_TRUE(svr.is_valid());
  9344. }
  9345. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  9346. Server svr;
  9347. svr.CustomRoute("POST", "/x",
  9348. [](const Request &, Response &, const ContentReader &) {});
  9349. EXPECT_FALSE(svr.is_valid());
  9350. }
  9351. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  9352. Server svr;
  9353. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  9354. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  9355. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  9356. EXPECT_FALSE(svr.is_valid());
  9357. }
  9358. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  9359. Server svr;
  9360. auto captured = Error::Success;
  9361. svr.set_error_logger(
  9362. [&](const Error &err, const Request * /*req*/) { captured = err; });
  9363. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  9364. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  9365. }
  9366. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  9367. std::string out;
  9368. std::string request(
  9369. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  9370. test_raw_request(request, &out);
  9371. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9372. }
  9373. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  9374. std::string out;
  9375. std::string request(
  9376. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  9377. test_raw_request(request, &out);
  9378. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9379. }
  9380. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  9381. std::string out;
  9382. std::string request(
  9383. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  9384. test_raw_request(request, &out);
  9385. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9386. }
  9387. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  9388. std::string out;
  9389. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  9390. "Host: localhost\r\n"
  9391. "Test: \r\n\r\n",
  9392. &out);
  9393. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9394. }
  9395. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  9396. Server svr;
  9397. std::string x_custom;
  9398. std::string cookie;
  9399. std::string xff;
  9400. std::string x_unicode;
  9401. std::string x_iis;
  9402. svr.Get("/check", [&](const Request &req, Response &res) {
  9403. x_custom = req.get_header_value("X-Custom");
  9404. cookie = req.get_header_value("Cookie");
  9405. xff = req.get_header_value("X-Forwarded-For");
  9406. x_unicode = req.get_header_value("X-Unicode");
  9407. x_iis = req.get_header_value("X-IIS");
  9408. res.set_content("ok", "text/plain");
  9409. });
  9410. thread t = thread([&] { svr.listen(HOST, PORT); });
  9411. auto se = detail::scope_exit([&] {
  9412. svr.stop();
  9413. t.join();
  9414. ASSERT_FALSE(svr.is_running());
  9415. });
  9416. svr.wait_until_ready();
  9417. const std::string req = "GET /check HTTP/1.1\r\n"
  9418. "Host: localhost\r\n"
  9419. "X-Custom: a%0D%0AInjected: b\r\n"
  9420. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  9421. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  9422. "X-Unicode: %E3%81%82\r\n"
  9423. "X-IIS: %u00E9\r\n"
  9424. "Connection: close\r\n"
  9425. "\r\n";
  9426. std::string res;
  9427. ASSERT_TRUE(send_request(5, req, &res));
  9428. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9429. // Every value must be returned verbatim (wire form), with no decoding.
  9430. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  9431. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  9432. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  9433. EXPECT_EQ("%E3%81%82", x_unicode);
  9434. EXPECT_EQ("%u00E9", x_iis);
  9435. }
  9436. // Applications that previously relied on automatic percent-decoding can
  9437. // reproduce the old behavior by explicitly calling decode_path_component()
  9438. // or, for RFC 3986 conformance, decode_uri_component().
  9439. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  9440. Server svr;
  9441. std::string decoded;
  9442. svr.Get("/check", [&](const Request &req, Response &res) {
  9443. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  9444. res.set_content("ok", "text/plain");
  9445. });
  9446. thread t = thread([&] { svr.listen(HOST, PORT); });
  9447. auto se = detail::scope_exit([&] {
  9448. svr.stop();
  9449. t.join();
  9450. ASSERT_FALSE(svr.is_running());
  9451. });
  9452. svr.wait_until_ready();
  9453. const std::string req = "GET /check HTTP/1.1\r\n"
  9454. "Host: localhost\r\n"
  9455. "X-Custom: hello%20world\r\n"
  9456. "Connection: close\r\n"
  9457. "\r\n";
  9458. std::string res;
  9459. ASSERT_TRUE(send_request(5, req, &res));
  9460. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9461. EXPECT_EQ("hello world", decoded);
  9462. }
  9463. // Regression test for #2033. Browsers send Referer values that include
  9464. // percent-encoded characters such as %0A inside the URL. Decoding the
  9465. // header value would either trip the post-decode CR/LF/NUL guard (the
  9466. // original bug, returning 400) or, after that guard was relaxed, silently
  9467. // store a literal LF — both unacceptable. The wire form must round-trip.
  9468. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  9469. Server svr;
  9470. std::string referer;
  9471. svr.Get("/check", [&](const Request &req, Response &res) {
  9472. referer = req.get_header_value("Referer");
  9473. res.set_content("ok", "text/plain");
  9474. });
  9475. thread t = thread([&] { svr.listen(HOST, PORT); });
  9476. auto se = detail::scope_exit([&] {
  9477. svr.stop();
  9478. t.join();
  9479. ASSERT_FALSE(svr.is_running());
  9480. });
  9481. svr.wait_until_ready();
  9482. const std::string req = "GET /check HTTP/1.1\r\n"
  9483. "Host: localhost\r\n"
  9484. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  9485. "Connection: close\r\n"
  9486. "\r\n";
  9487. std::string res;
  9488. ASSERT_TRUE(send_request(5, req, &res));
  9489. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9490. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9491. }
  9492. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9493. Server svr;
  9494. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9495. res.set_header("Cache-Control", "no-cache");
  9496. res.set_chunked_content_provider(
  9497. "text/event-stream", [](size_t offset, DataSink &sink) {
  9498. std::string s = "data:";
  9499. s += std::to_string(offset);
  9500. s += "\n\n";
  9501. auto ret = sink.write(s.data(), s.size());
  9502. EXPECT_TRUE(ret);
  9503. std::this_thread::sleep_for(std::chrono::seconds(1));
  9504. return true;
  9505. });
  9506. });
  9507. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9508. svr.wait_until_ready();
  9509. Client client(HOST, PORT);
  9510. const Headers headers = {{"Accept", "text/event-stream"}};
  9511. auto get_thread = std::thread([&client, &headers]() {
  9512. auto res = client.Get(
  9513. "/events", headers,
  9514. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9515. });
  9516. auto se = detail::scope_exit([&] {
  9517. svr.stop();
  9518. get_thread.join();
  9519. listen_thread.join();
  9520. ASSERT_FALSE(svr.is_running());
  9521. });
  9522. // Give GET time to get a few messages.
  9523. std::this_thread::sleep_for(std::chrono::seconds(2));
  9524. }
  9525. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9526. httplib::Server svr;
  9527. svr.Post("/hi",
  9528. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9529. res.status = StatusCode::OK_200;
  9530. });
  9531. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9532. svr.wait_until_ready();
  9533. Client cli(HOST, PORT);
  9534. auto res = cli.Post("/hi", "data", "text/plain");
  9535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9536. EXPECT_EQ(StatusCode::OK_200, res->status);
  9537. svr.stop();
  9538. thread.join();
  9539. ASSERT_FALSE(svr.is_running());
  9540. res = cli.Post("/hi", "data", "text/plain");
  9541. ASSERT_FALSE(res);
  9542. }
  9543. TEST(ServerStopTest, ListenFailure) {
  9544. Server svr;
  9545. auto t = thread([&]() {
  9546. auto ret = svr.listen("????", PORT);
  9547. EXPECT_FALSE(ret);
  9548. });
  9549. svr.wait_until_ready();
  9550. svr.stop();
  9551. t.join();
  9552. }
  9553. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9554. TEST(ServerStopTest, Decommision) {
  9555. Server svr;
  9556. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9557. for (int i = 0; i < 4; i++) {
  9558. auto is_even = !(i % 2);
  9559. std::thread t{[&] {
  9560. try {
  9561. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9562. if (is_even) {
  9563. throw std::runtime_error("Some thing that happens to go wrong.");
  9564. }
  9565. svr.listen(HOST, PORT);
  9566. } catch (...) { svr.decommission(); }
  9567. }};
  9568. svr.wait_until_ready();
  9569. // Server is up
  9570. {
  9571. Client cli(HOST, PORT);
  9572. auto res = cli.Get("/hi");
  9573. if (is_even) {
  9574. EXPECT_FALSE(res);
  9575. } else {
  9576. EXPECT_TRUE(res);
  9577. EXPECT_EQ("hi...", res->body);
  9578. }
  9579. }
  9580. svr.stop();
  9581. t.join();
  9582. // Server is down...
  9583. {
  9584. Client cli(HOST, PORT);
  9585. auto res = cli.Get("/hi");
  9586. EXPECT_FALSE(res);
  9587. }
  9588. }
  9589. }
  9590. #endif
  9591. // Helper function for string body upload progress tests
  9592. template <typename SetupHandler, typename ClientCall>
  9593. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9594. ClientCall &&client_call,
  9595. const string &body) {
  9596. Server svr;
  9597. setup_handler(svr);
  9598. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9599. auto se = detail::scope_exit([&] {
  9600. svr.stop();
  9601. t.join();
  9602. });
  9603. svr.wait_until_ready();
  9604. Client cli(HOST, PORT);
  9605. vector<uint64_t> progress_values;
  9606. bool progress_called = false;
  9607. auto res =
  9608. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9609. progress_values.push_back(current);
  9610. progress_called = true;
  9611. return true;
  9612. });
  9613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9614. EXPECT_EQ(200, res->status);
  9615. EXPECT_TRUE(progress_called);
  9616. }
  9617. TEST(UploadProgressTest, PostStringBodyBasic) {
  9618. TestStringBodyUploadProgress(
  9619. [](Server &svr) {
  9620. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9621. res.set_content("received", "text/plain");
  9622. });
  9623. },
  9624. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9625. return cli.Post("/test", body, "text/plain", progress_callback);
  9626. },
  9627. "test data for upload progress");
  9628. }
  9629. TEST(UploadProgressTest, PutStringBodyBasic) {
  9630. TestStringBodyUploadProgress(
  9631. [](Server &svr) {
  9632. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9633. res.set_content("put received", "text/plain");
  9634. });
  9635. },
  9636. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9637. return cli.Put("/test", body, "text/plain", progress_callback);
  9638. },
  9639. "put test data for upload progress");
  9640. }
  9641. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9642. TestStringBodyUploadProgress(
  9643. [](Server &svr) {
  9644. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9645. res.set_content("patch received", "text/plain");
  9646. });
  9647. },
  9648. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9649. return cli.Patch("/test", body, "text/plain", progress_callback);
  9650. },
  9651. "patch test data for upload progress");
  9652. }
  9653. // Helper function for content provider upload progress tests
  9654. template <typename SetupHandler, typename ClientCall>
  9655. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9656. ClientCall &&client_call) {
  9657. Server svr;
  9658. setup_handler(svr);
  9659. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9660. auto se = detail::scope_exit([&] {
  9661. svr.stop();
  9662. t.join();
  9663. });
  9664. svr.wait_until_ready();
  9665. Client cli(HOST, PORT);
  9666. vector<uint64_t> progress_values;
  9667. auto res =
  9668. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9669. progress_values.push_back(current);
  9670. return true;
  9671. });
  9672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9673. EXPECT_EQ(200, res->status);
  9674. EXPECT_FALSE(progress_values.empty());
  9675. }
  9676. TEST(UploadProgressTest, PostContentProviderProgress) {
  9677. TestContentProviderUploadProgress(
  9678. [](Server &svr) {
  9679. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9680. res.set_content("provider received", "text/plain");
  9681. });
  9682. },
  9683. [](Client &cli, UploadProgress progress_callback) {
  9684. return cli.Post(
  9685. "/test", 10,
  9686. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9687. sink.os << "test data";
  9688. return true;
  9689. },
  9690. "text/plain", progress_callback);
  9691. });
  9692. }
  9693. // Helper function for multipart upload progress tests
  9694. template <typename SetupHandler, typename ClientCall>
  9695. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9696. ClientCall &&client_call,
  9697. const string &endpoint) {
  9698. Server svr;
  9699. setup_handler(svr);
  9700. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9701. auto se = detail::scope_exit([&] {
  9702. svr.stop();
  9703. t.join();
  9704. });
  9705. svr.wait_until_ready();
  9706. Client cli(HOST, PORT);
  9707. vector<uint64_t> progress_values;
  9708. UploadFormDataItems items = {
  9709. {"field1", "value1", "", ""},
  9710. {"field2", "longer value for progress tracking test", "", ""},
  9711. {"file1", "file content data for upload progress", "test.txt",
  9712. "text/plain"}};
  9713. auto res = client_call(cli, endpoint, items,
  9714. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9715. progress_values.push_back(current);
  9716. return true;
  9717. });
  9718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9719. EXPECT_EQ(200, res->status);
  9720. EXPECT_FALSE(progress_values.empty());
  9721. }
  9722. TEST(UploadProgressTest, PostMultipartProgress) {
  9723. TestMultipartUploadProgress(
  9724. [](Server &svr) {
  9725. svr.Post("/multipart", [](const Request &req, Response &res) {
  9726. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9727. res.set_content("multipart received", "text/plain");
  9728. });
  9729. },
  9730. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9731. UploadProgress progress_callback) {
  9732. return cli.Post(endpoint, items, progress_callback);
  9733. },
  9734. "/multipart");
  9735. }
  9736. // Helper function for basic download progress tests
  9737. template <typename SetupHandler, typename ClientCall>
  9738. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9739. ClientCall &&client_call, const string &endpoint,
  9740. size_t expected_content_size) {
  9741. Server svr;
  9742. setup_handler(svr);
  9743. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9744. auto se = detail::scope_exit([&] {
  9745. svr.stop();
  9746. t.join();
  9747. });
  9748. svr.wait_until_ready();
  9749. Client cli(HOST, PORT);
  9750. vector<uint64_t> progress_values;
  9751. auto res = client_call(cli, endpoint,
  9752. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9753. progress_values.push_back(current);
  9754. return true;
  9755. });
  9756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9757. EXPECT_EQ(200, res->status);
  9758. EXPECT_FALSE(progress_values.empty());
  9759. EXPECT_EQ(expected_content_size, res->body.size());
  9760. }
  9761. TEST(DownloadProgressTest, GetBasic) {
  9762. TestBasicDownloadProgress(
  9763. [](Server &svr) {
  9764. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9765. string content(1000, 'D');
  9766. res.set_content(content, "text/plain");
  9767. });
  9768. },
  9769. [](Client &cli, const string &endpoint,
  9770. DownloadProgress progress_callback) {
  9771. return cli.Get(endpoint, progress_callback);
  9772. },
  9773. "/download", 1000u);
  9774. }
  9775. // Helper function for content receiver download progress tests
  9776. template <typename SetupHandler, typename ClientCall>
  9777. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9778. ClientCall &&client_call,
  9779. const string &endpoint,
  9780. size_t expected_content_size) {
  9781. Server svr;
  9782. setup_handler(svr);
  9783. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9784. auto se = detail::scope_exit([&] {
  9785. svr.stop();
  9786. t.join();
  9787. });
  9788. svr.wait_until_ready();
  9789. Client cli(HOST, PORT);
  9790. vector<uint64_t> progress_values;
  9791. string received_body;
  9792. auto res = client_call(
  9793. cli, endpoint,
  9794. [&](const char *data, size_t data_length) -> bool {
  9795. received_body.append(data, data_length);
  9796. return true;
  9797. },
  9798. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9799. progress_values.push_back(current);
  9800. return true;
  9801. });
  9802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9803. EXPECT_EQ(200, res->status);
  9804. EXPECT_FALSE(progress_values.empty());
  9805. EXPECT_EQ(expected_content_size, received_body.size());
  9806. EXPECT_TRUE(res->body.empty());
  9807. }
  9808. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9809. TestContentReceiverDownloadProgress(
  9810. [](Server &svr) {
  9811. svr.Get("/download-receiver",
  9812. [](const Request & /*req*/, Response &res) {
  9813. string content(2000, 'R');
  9814. res.set_content(content, "text/plain");
  9815. });
  9816. },
  9817. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9818. DownloadProgress progress_callback) {
  9819. return cli.Get(endpoint, content_receiver, progress_callback);
  9820. },
  9821. "/download-receiver", 2000u);
  9822. }
  9823. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9824. // A provider reaching a pass with nothing to hand over - an empty buffer
  9825. // popped off a queue, say - must not be taken to mean the body is finished.
  9826. // It used to end the loop with the terminating chunk unwritten while the
  9827. // server still considered the response complete, so the peer waited for an
  9828. // end that never arrived.
  9829. Server svr;
  9830. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9831. auto step = std::make_shared<int>(0);
  9832. res.set_chunked_content_provider("text/plain",
  9833. [step](size_t /*offset*/, DataSink &sink) {
  9834. switch ((*step)++) {
  9835. case 0: sink.write("", 0); break;
  9836. case 1: sink.write("hello", 5); break;
  9837. default: sink.done(); break;
  9838. }
  9839. return true;
  9840. });
  9841. });
  9842. auto port = svr.bind_to_any_port(HOST);
  9843. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9844. auto listen_se = detail::scope_exit([&] {
  9845. svr.stop();
  9846. listen_thread.join();
  9847. ASSERT_FALSE(svr.is_running());
  9848. });
  9849. svr.wait_until_ready();
  9850. Client cli(HOST, port);
  9851. // Without the fix the body is never terminated, so bound the wait rather
  9852. // than letting the test hang on the default read timeout.
  9853. cli.set_read_timeout(5, 0);
  9854. auto res = cli.Get("/stream");
  9855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9856. EXPECT_EQ(StatusCode::OK_200, res->status);
  9857. EXPECT_EQ("hello", res->body);
  9858. }
  9859. TEST(StreamingTest, NoContentLengthStreaming) {
  9860. Server svr;
  9861. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9862. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9863. if (offset < 6) {
  9864. sink.os << (offset < 3 ? "a" : "b");
  9865. } else {
  9866. sink.done();
  9867. }
  9868. return true;
  9869. });
  9870. });
  9871. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9872. auto listen_se = detail::scope_exit([&] {
  9873. svr.stop();
  9874. listen_thread.join();
  9875. ASSERT_FALSE(svr.is_running());
  9876. });
  9877. svr.wait_until_ready();
  9878. Client client(HOST, PORT);
  9879. auto get_thread = std::thread([&client]() {
  9880. std::string s;
  9881. auto res =
  9882. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9883. s += std::string(data, len);
  9884. return true;
  9885. });
  9886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9887. EXPECT_EQ(StatusCode::OK_200, res->status);
  9888. EXPECT_EQ("aaabbb", s);
  9889. });
  9890. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9891. // Give GET time to get a few messages.
  9892. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9893. }
  9894. TEST(MountTest, Unmount) {
  9895. Server svr;
  9896. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9897. auto se = detail::scope_exit([&] {
  9898. svr.stop();
  9899. listen_thread.join();
  9900. ASSERT_FALSE(svr.is_running());
  9901. });
  9902. svr.wait_until_ready();
  9903. Client cli("localhost", PORT);
  9904. svr.set_mount_point("/mount2", "./www2");
  9905. auto res = cli.Get("/");
  9906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9907. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9908. res = cli.Get("/mount2/dir/test.html");
  9909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9910. EXPECT_EQ(StatusCode::OK_200, res->status);
  9911. svr.set_mount_point("/", "./www");
  9912. res = cli.Get("/dir/");
  9913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9914. EXPECT_EQ(StatusCode::OK_200, res->status);
  9915. svr.remove_mount_point("/");
  9916. res = cli.Get("/dir/");
  9917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9918. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9919. svr.remove_mount_point("/mount2");
  9920. res = cli.Get("/mount2/dir/test.html");
  9921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9922. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9923. }
  9924. TEST(MountTest, PathSegmentBoundary) {
  9925. Server svr;
  9926. svr.set_mount_point("/mount2", "./www2");
  9927. svr.set_mount_point("/", "./www");
  9928. auto port = svr.bind_to_any_port(HOST);
  9929. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9930. auto se = detail::scope_exit([&] {
  9931. svr.stop();
  9932. listen_thread.join();
  9933. ASSERT_FALSE(svr.is_running());
  9934. });
  9935. svr.wait_until_ready();
  9936. Client cli(HOST, port);
  9937. auto res = cli.Get("/mount2/dir/test.html");
  9938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9939. EXPECT_EQ(StatusCode::OK_200, res->status);
  9940. // "/mount2" must not match part-way through a path segment.
  9941. res = cli.Get("/mount2dir/test.html");
  9942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9943. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9944. // A mount point ending in '/' keeps matching every path below it.
  9945. res = cli.Get("/dir/test.html");
  9946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9947. EXPECT_EQ(StatusCode::OK_200, res->status);
  9948. }
  9949. TEST(MountTest, Redicect) {
  9950. Server svr;
  9951. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9952. auto se = detail::scope_exit([&] {
  9953. svr.stop();
  9954. listen_thread.join();
  9955. ASSERT_FALSE(svr.is_running());
  9956. });
  9957. svr.set_mount_point("/", "./www");
  9958. svr.wait_until_ready();
  9959. Client cli("localhost", PORT);
  9960. auto res = cli.Get("/dir/");
  9961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9962. EXPECT_EQ(StatusCode::OK_200, res->status);
  9963. res = cli.Get("/dir");
  9964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9965. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9966. res = cli.Get("/file");
  9967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9968. EXPECT_EQ(StatusCode::OK_200, res->status);
  9969. res = cli.Get("/file/");
  9970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9971. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9972. cli.set_follow_location(true);
  9973. res = cli.Get("/dir");
  9974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9975. EXPECT_EQ(StatusCode::OK_200, res->status);
  9976. }
  9977. TEST(MountTest, MultibytesPathName) {
  9978. Server svr;
  9979. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9980. auto se = detail::scope_exit([&] {
  9981. svr.stop();
  9982. listen_thread.join();
  9983. ASSERT_FALSE(svr.is_running());
  9984. });
  9985. svr.set_mount_point("/", "./www");
  9986. svr.wait_until_ready();
  9987. Client cli("localhost", PORT);
  9988. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9990. EXPECT_EQ(StatusCode::OK_200, res->status);
  9991. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9992. }
  9993. #ifdef _WIN32
  9994. // Issue #2435: mmap::open() must succeed even when another handle holds
  9995. // the file open for writing (e.g. an active log file).
  9996. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9997. const char *path = "mmap_concurrent_writer_test.txt";
  9998. const char *content = "hello";
  9999. {
  10000. std::ofstream f(path, std::ios::binary);
  10001. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10002. }
  10003. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10004. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10005. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10006. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10007. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10008. detail::mmap m(path);
  10009. ASSERT_TRUE(m.is_open());
  10010. EXPECT_EQ(strlen(content), m.size());
  10011. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  10012. }
  10013. #endif
  10014. #ifndef _WIN32
  10015. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  10016. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  10017. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  10018. TEST(MmapTest, FailedMappingIsNotOpen) {
  10019. const char *path = "./mmap_failed_mapping_test_dir";
  10020. ASSERT_EQ(0, ::mkdir(path, 0755));
  10021. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10022. detail::mmap m(path);
  10023. EXPECT_FALSE(m.is_open());
  10024. EXPECT_EQ(0U, m.size());
  10025. EXPECT_NE(static_cast<const void *>(m.data()),
  10026. static_cast<const void *>(MAP_FAILED));
  10027. }
  10028. #endif
  10029. TEST(KeepAliveTest, ReadTimeout) {
  10030. Server svr;
  10031. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10032. std::this_thread::sleep_for(std::chrono::seconds(2));
  10033. res.set_content("a", "text/plain");
  10034. });
  10035. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10036. res.set_content("b", "text/plain");
  10037. });
  10038. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10039. auto se = detail::scope_exit([&] {
  10040. svr.stop();
  10041. listen_thread.join();
  10042. ASSERT_FALSE(svr.is_running());
  10043. });
  10044. svr.wait_until_ready();
  10045. Client cli("localhost", PORT);
  10046. cli.set_keep_alive(true);
  10047. cli.set_read_timeout(std::chrono::seconds(1));
  10048. auto resa = cli.Get("/a");
  10049. ASSERT_FALSE(resa);
  10050. EXPECT_EQ(Error::Read, resa.error());
  10051. auto resb = cli.Get("/b");
  10052. ASSERT_TRUE(resb);
  10053. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10054. EXPECT_EQ("b", resb->body);
  10055. }
  10056. TEST(KeepAliveTest, MaxCount) {
  10057. size_t keep_alive_max_count = 3;
  10058. Server svr;
  10059. svr.set_keep_alive_max_count(keep_alive_max_count);
  10060. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10061. res.set_content("Hello World!", "text/plain");
  10062. });
  10063. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10064. auto se = detail::scope_exit([&] {
  10065. svr.stop();
  10066. listen_thread.join();
  10067. ASSERT_FALSE(svr.is_running());
  10068. });
  10069. svr.wait_until_ready();
  10070. Client cli(HOST, PORT);
  10071. cli.set_keep_alive(true);
  10072. for (size_t i = 0; i < 5; i++) {
  10073. auto result = cli.Get("/hi");
  10074. ASSERT_TRUE(result);
  10075. EXPECT_EQ(StatusCode::OK_200, result->status);
  10076. if (i == keep_alive_max_count - 1) {
  10077. EXPECT_EQ("close", result->get_header_value("Connection"));
  10078. } else {
  10079. EXPECT_FALSE(result->has_header("Connection"));
  10080. }
  10081. }
  10082. }
  10083. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10084. // can pull the next one into the server's buffer. The server must serve it
  10085. // without waiting for the socket to become readable again. The keep-alive
  10086. // timeout outlasts the client's read timeout, so a request left waiting for it
  10087. // shows up as a missing response.
  10088. static void serve_pipelining_routes(Server &svr,
  10089. const std::function<void(int)> &client) {
  10090. svr.set_keep_alive_timeout(5);
  10091. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10092. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10093. });
  10094. svr.Post("/echo", [](const Request &req, Response &res) {
  10095. res.set_content("echo " + req.body, "text/plain");
  10096. });
  10097. auto port = svr.bind_to_any_port(HOST);
  10098. thread t = thread([&] { svr.listen_after_bind(); });
  10099. auto se = detail::scope_exit([&] {
  10100. svr.stop();
  10101. t.join();
  10102. });
  10103. svr.wait_until_ready();
  10104. client(port);
  10105. }
  10106. static std::string
  10107. send_pipelined_requests(const std::vector<std::string> &parts) {
  10108. Server svr;
  10109. std::string res;
  10110. serve_pipelining_routes(svr, [&](int port) {
  10111. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10112. });
  10113. return res;
  10114. }
  10115. static void expect_in_order(const std::string &res,
  10116. const std::vector<std::string> &bodies) {
  10117. size_t pos = 0;
  10118. for (const auto &body : bodies) {
  10119. pos = res.find(body, pos);
  10120. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10121. pos += body.size();
  10122. }
  10123. }
  10124. TEST(KeepAliveTest, PipelinedRequests) {
  10125. auto res = send_pipelined_requests(
  10126. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10127. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10128. "Content-Length: 4\r\n\r\nbody"
  10129. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10130. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10131. }
  10132. // The second request starts in the server's buffer and ends on the socket.
  10133. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10134. auto res =
  10135. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10136. "GET /hi/2 HTTP/1.1\r\nHo",
  10137. "st: localhost\r\nConnection: close\r\n\r\n"});
  10138. expect_in_order(res, {"hi 1", "hi 2"});
  10139. }
  10140. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10141. // CRLF after a body does not turn into a 400 for the next request.
  10142. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10143. auto res = send_pipelined_requests(
  10144. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10145. "Content-Length: 4\r\n\r\nbody\r\n"
  10146. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10147. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10148. expect_in_order(res, {"echo body", "hi 2"});
  10149. }
  10150. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10151. // must not be served as the next request.
  10152. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10153. auto res = send_pipelined_requests(
  10154. {"INVALID REQUEST LINE\r\n\r\n"
  10155. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10156. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10157. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10158. }
  10159. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10160. // Over TLS, the next request is held by the TLS library as already decrypted
  10161. // data rather than on the socket.
  10162. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10163. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10164. std::string res;
  10165. serve_pipelining_routes(svr, [&](int port) {
  10166. auto error = Error::Success;
  10167. auto sock = detail::create_client_socket(
  10168. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10169. /*connection_timeout_sec=*/5, 0,
  10170. /*read_timeout_sec=*/2, 0,
  10171. /*write_timeout_sec=*/5, 0, std::string(), error);
  10172. ASSERT_NE(INVALID_SOCKET, sock);
  10173. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10174. auto ctx = SSL_CTX_new(TLS_client_method());
  10175. auto ssl = SSL_new(ctx);
  10176. auto ssl_se = detail::scope_exit([&] {
  10177. SSL_free(ssl);
  10178. SSL_CTX_free(ctx);
  10179. });
  10180. SSL_set_fd(ssl, static_cast<int>(sock));
  10181. ASSERT_EQ(1, SSL_connect(ssl));
  10182. // One write, so all three requests arrive in one TLS record
  10183. const std::string req =
  10184. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10185. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10186. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
  10187. ASSERT_EQ(static_cast<int>(req.size()),
  10188. SSL_write(ssl, req.data(), static_cast<int>(req.size())));
  10189. char buf[512];
  10190. int n;
  10191. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10192. res.append(buf, static_cast<size_t>(n));
  10193. }
  10194. });
  10195. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10196. }
  10197. #endif
  10198. TEST(KeepAliveTest, Issue1041) {
  10199. Server svr;
  10200. svr.set_keep_alive_timeout(3);
  10201. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10202. res.set_content("Hello World!", "text/plain");
  10203. });
  10204. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10205. auto se = detail::scope_exit([&] {
  10206. svr.stop();
  10207. listen_thread.join();
  10208. ASSERT_FALSE(svr.is_running());
  10209. });
  10210. svr.wait_until_ready();
  10211. Client cli(HOST, PORT);
  10212. cli.set_keep_alive(true);
  10213. auto result = cli.Get("/hi");
  10214. ASSERT_TRUE(result);
  10215. EXPECT_EQ(StatusCode::OK_200, result->status);
  10216. std::this_thread::sleep_for(std::chrono::seconds(5));
  10217. result = cli.Get("/hi");
  10218. ASSERT_TRUE(result);
  10219. EXPECT_EQ(StatusCode::OK_200, result->status);
  10220. }
  10221. TEST(KeepAliveTest, Issue1959) {
  10222. Server svr;
  10223. svr.set_keep_alive_timeout(5);
  10224. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10225. res.set_content("a", "text/plain");
  10226. });
  10227. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10228. auto se = detail::scope_exit([&] {
  10229. if (!svr.is_running()) return;
  10230. svr.stop();
  10231. listen_thread.join();
  10232. ASSERT_FALSE(svr.is_running());
  10233. });
  10234. svr.wait_until_ready();
  10235. Client cli("localhost", PORT);
  10236. cli.set_keep_alive(true);
  10237. using namespace std::chrono;
  10238. auto start = steady_clock::now();
  10239. cli.Get("/a");
  10240. svr.stop();
  10241. listen_thread.join();
  10242. auto end = steady_clock::now();
  10243. auto elapsed = duration_cast<milliseconds>(end - start).count();
  10244. EXPECT_LT(elapsed, 5000);
  10245. }
  10246. #ifdef CPPHTTPLIB_SSL_ENABLED
  10247. TEST(KeepAliveTest, SSLClientReconnection) {
  10248. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10249. ASSERT_TRUE(svr.is_valid());
  10250. svr.set_keep_alive_timeout(1);
  10251. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10252. res.set_content("Hello World!", "text/plain");
  10253. });
  10254. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10255. auto se = detail::scope_exit([&] {
  10256. svr.stop();
  10257. listen_thread.join();
  10258. ASSERT_FALSE(svr.is_running());
  10259. });
  10260. svr.wait_until_ready();
  10261. SSLClient cli(HOST, PORT);
  10262. cli.enable_server_certificate_verification(false);
  10263. cli.set_keep_alive(true);
  10264. auto result = cli.Get("/hi");
  10265. ASSERT_TRUE(result);
  10266. EXPECT_EQ(StatusCode::OK_200, result->status);
  10267. result = cli.Get("/hi");
  10268. ASSERT_TRUE(result);
  10269. EXPECT_EQ(StatusCode::OK_200, result->status);
  10270. std::this_thread::sleep_for(std::chrono::seconds(2));
  10271. // Recoonect
  10272. result = cli.Get("/hi");
  10273. ASSERT_TRUE(result);
  10274. EXPECT_EQ(StatusCode::OK_200, result->status);
  10275. result = cli.Get("/hi");
  10276. ASSERT_TRUE(result);
  10277. EXPECT_EQ(StatusCode::OK_200, result->status);
  10278. }
  10279. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  10280. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10281. ASSERT_TRUE(svr.is_valid());
  10282. svr.set_keep_alive_timeout(1);
  10283. std::string content = "reconnect";
  10284. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  10285. res.set_content("Hello World!", "text/plain");
  10286. });
  10287. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10288. auto se = detail::scope_exit([&] {
  10289. svr.stop();
  10290. listen_thread.join();
  10291. ASSERT_FALSE(svr.is_running());
  10292. });
  10293. svr.wait_until_ready();
  10294. SSLClient cli(HOST, PORT);
  10295. cli.enable_server_certificate_verification(false);
  10296. cli.set_keep_alive(true);
  10297. auto result = cli.Post(
  10298. "/hi", content.size(),
  10299. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10300. sink.write(content.c_str(), content.size());
  10301. return true;
  10302. },
  10303. "text/plain");
  10304. ASSERT_TRUE(result);
  10305. EXPECT_EQ(200, result->status);
  10306. std::this_thread::sleep_for(std::chrono::seconds(2));
  10307. // Recoonect
  10308. result = cli.Post(
  10309. "/hi", content.size(),
  10310. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10311. sink.write(content.c_str(), content.size());
  10312. return true;
  10313. },
  10314. "text/plain");
  10315. ASSERT_TRUE(result);
  10316. EXPECT_EQ(200, result->status);
  10317. result = cli.Post(
  10318. "/hi", content.size(),
  10319. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10320. sink.write(content.c_str(), content.size());
  10321. return true;
  10322. },
  10323. "text/plain");
  10324. ASSERT_TRUE(result);
  10325. EXPECT_EQ(200, result->status);
  10326. }
  10327. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  10328. using namespace httplib::tls;
  10329. {
  10330. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10331. ASSERT_TRUE(svr.is_valid());
  10332. svr.Get("/sni", [&](const Request &req, Response &res) {
  10333. std::string expected = req.sni();
  10334. EXPECT_EQ(expected, req.get_param_value("expected"));
  10335. res.set_content("ok", "text/plain");
  10336. });
  10337. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10338. auto se = detail::scope_exit([&] {
  10339. svr.stop();
  10340. listen_thread.join();
  10341. ASSERT_FALSE(svr.is_running());
  10342. });
  10343. svr.wait_until_ready();
  10344. {
  10345. SSLClient cli("localhost", PORT);
  10346. cli.enable_server_certificate_verification(false);
  10347. auto res = cli.Get("/sni?expected=localhost");
  10348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10349. }
  10350. {
  10351. SSLClient cli("::1", PORT);
  10352. cli.enable_server_certificate_verification(false);
  10353. auto res = cli.Get("/sni?expected=");
  10354. // NOTE: This may fail if the server is listening on IPv4 only
  10355. // (e.g., when localhost resolves to 127.0.0.1 only)
  10356. if (res) {
  10357. EXPECT_EQ(StatusCode::OK_200, res->status);
  10358. } else {
  10359. EXPECT_EQ(Error::Connection, res.error());
  10360. }
  10361. }
  10362. }
  10363. }
  10364. #endif
  10365. TEST(ClientProblemDetectionTest, ContentProvider) {
  10366. Server svr;
  10367. size_t content_length = 1024 * 1024;
  10368. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10369. res.set_content_provider(
  10370. content_length, "text/plain",
  10371. [&](size_t offset, size_t length, DataSink &sink) {
  10372. auto out_len = std::min(length, static_cast<size_t>(1024));
  10373. std::string out(out_len, '@');
  10374. sink.write(out.data(), out_len);
  10375. return offset < 4096;
  10376. },
  10377. [](bool success) { ASSERT_FALSE(success); });
  10378. });
  10379. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  10380. res.set_content_provider(
  10381. 0, "text/plain",
  10382. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  10383. EXPECT_TRUE(false);
  10384. return true;
  10385. },
  10386. [](bool success) { ASSERT_FALSE(success); });
  10387. });
  10388. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10389. auto se = detail::scope_exit([&] {
  10390. svr.stop();
  10391. listen_thread.join();
  10392. ASSERT_FALSE(svr.is_running());
  10393. });
  10394. svr.wait_until_ready();
  10395. Client cli("localhost", PORT);
  10396. {
  10397. auto res = cli.Get("/hi", [&](const char * /*data*/,
  10398. size_t /*data_length*/) { return false; });
  10399. ASSERT_FALSE(res);
  10400. }
  10401. {
  10402. auto res = cli.Get("/empty", [&](const char * /*data*/,
  10403. size_t /*data_length*/) { return false; });
  10404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10405. }
  10406. }
  10407. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  10408. // A provider that reports success without writing anything and without
  10409. // calling done() used to be handed the same offset and length again on every
  10410. // pass, so it spun for as long as the peer stayed connected.
  10411. Server svr;
  10412. svr.Post("/", [](const Request & /*req*/, Response &res) {
  10413. res.set_content("ok", "text/plain");
  10414. });
  10415. auto port = svr.bind_to_any_port(HOST);
  10416. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  10417. auto se = detail::scope_exit([&] {
  10418. svr.stop();
  10419. listen_thread.join();
  10420. ASSERT_FALSE(svr.is_running());
  10421. });
  10422. svr.wait_until_ready();
  10423. std::atomic<int> call_count{0};
  10424. Client cli(HOST, port);
  10425. auto res = cli.Post(
  10426. "/", 1024,
  10427. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  10428. // Give up after enough passes to show the spin, so that losing the
  10429. // check below fails this test instead of hanging it.
  10430. return ++call_count < 100;
  10431. },
  10432. "text/plain");
  10433. ASSERT_FALSE(res);
  10434. EXPECT_EQ(Error::Write, res.error());
  10435. EXPECT_EQ(1, call_count.load());
  10436. }
  10437. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  10438. // A writer only has to assign `write`. The other three used to be left as
  10439. // empty std::functions, so a provider calling one threw
  10440. // std::bad_function_call out of the thread running it and took the whole
  10441. // process down.
  10442. DataSink sink;
  10443. std::string written;
  10444. sink.write = [&](const char *data, size_t data_len) {
  10445. written.append(data, data_len);
  10446. return true;
  10447. };
  10448. EXPECT_TRUE(sink.is_writable());
  10449. sink.done();
  10450. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10451. EXPECT_TRUE(written.empty());
  10452. }
  10453. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  10454. // A sink that cannot carry trailers still has to finish.
  10455. DataSink sink;
  10456. auto done_count = 0;
  10457. sink.done = [&]() { done_count++; };
  10458. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  10459. EXPECT_EQ(1, done_count);
  10460. }
  10461. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  10462. Server svr;
  10463. const std::string body(4096, 'x');
  10464. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10465. res.set_content_provider(body.size(), "text/plain",
  10466. [&](size_t offset, size_t length, DataSink &sink) {
  10467. sink.write(body.data() + offset, length);
  10468. sink.done();
  10469. return true;
  10470. });
  10471. });
  10472. auto port = svr.bind_to_any_port(HOST);
  10473. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10474. auto se = detail::scope_exit([&] {
  10475. svr.stop();
  10476. listen_thread.join();
  10477. ASSERT_FALSE(svr.is_running());
  10478. });
  10479. svr.wait_until_ready();
  10480. Client cli(HOST, port);
  10481. auto res = cli.Get("/");
  10482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10483. EXPECT_EQ(StatusCode::OK_200, res->status);
  10484. EXPECT_EQ(body, res->body);
  10485. }
  10486. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  10487. Server svr;
  10488. svr.Get("/", [](const Request & /*req*/, Response &res) {
  10489. res.set_content_provider(
  10490. 1024, "text/plain",
  10491. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10492. sink.write("hello", 5);
  10493. sink.done(); // short of the 1024 bytes the response promised
  10494. return true;
  10495. });
  10496. });
  10497. auto port = svr.bind_to_any_port(HOST);
  10498. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10499. auto se = detail::scope_exit([&] {
  10500. svr.stop();
  10501. listen_thread.join();
  10502. ASSERT_FALSE(svr.is_running());
  10503. });
  10504. svr.wait_until_ready();
  10505. Client cli(HOST, port);
  10506. cli.set_read_timeout(5, 0);
  10507. // The response is short of its Content-Length, so the client cannot read a
  10508. // complete body. What matters is that this returns at all: a no-op done()
  10509. // would leave the writer looping over a provider that never makes progress.
  10510. auto res = cli.Get("/");
  10511. EXPECT_FALSE(res);
  10512. }
  10513. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10514. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  10515. // The compressed path builds the whole body before connecting, so this
  10516. // fails client-side and never reaches a server.
  10517. Client cli(HOST, PORT);
  10518. cli.set_compress(true);
  10519. auto res = cli.Post(
  10520. "/", 1024,
  10521. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  10522. sink.write("hello", 5);
  10523. sink.done(); // short of the 1024 bytes the request announced
  10524. return true;
  10525. },
  10526. "text/plain");
  10527. ASSERT_FALSE(res);
  10528. EXPECT_EQ(Error::Write, res.error());
  10529. }
  10530. #endif
  10531. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  10532. Server svr;
  10533. svr.set_error_handler([](Request const &, Response &res) -> void {
  10534. res.set_chunked_content_provider(
  10535. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10536. sink.os << "hello";
  10537. sink.os << "world";
  10538. sink.done();
  10539. return true;
  10540. });
  10541. });
  10542. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10543. auto se = detail::scope_exit([&] {
  10544. svr.stop();
  10545. listen_thread.join();
  10546. ASSERT_FALSE(svr.is_running());
  10547. });
  10548. svr.wait_until_ready();
  10549. Client cli("localhost", PORT);
  10550. auto res = cli.Get("/");
  10551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10552. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10553. EXPECT_EQ("helloworld", res->body);
  10554. }
  10555. // A body set after a content provider must replace it, not be sent through it.
  10556. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  10557. Server svr;
  10558. svr.set_mount_point("/", "./www");
  10559. svr.set_file_request_handler([](const Request &req, Response &res) {
  10560. if (req.path == "/dir/test.html") {
  10561. res.status = StatusCode::Forbidden_403;
  10562. res.set_content(std::string(5000, 'D'), "text/plain");
  10563. } else if (req.path == "/file") {
  10564. res.status = StatusCode::Forbidden_403;
  10565. res.body = "Denied";
  10566. }
  10567. });
  10568. auto port = svr.bind_to_any_port(HOST);
  10569. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10570. auto se = detail::scope_exit([&] {
  10571. svr.stop();
  10572. t.join();
  10573. ASSERT_FALSE(svr.is_running());
  10574. });
  10575. svr.wait_until_ready();
  10576. Client cli(HOST, port);
  10577. {
  10578. auto res = cli.Get("/dir/test.html");
  10579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10580. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10581. EXPECT_EQ(std::string(5000, 'D'), res->body);
  10582. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  10583. }
  10584. {
  10585. auto res = cli.Get("/file");
  10586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10587. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  10588. EXPECT_EQ("Denied", res->body);
  10589. }
  10590. {
  10591. auto res = cli.Get("/dir/index.html");
  10592. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10593. EXPECT_EQ(StatusCode::OK_200, res->status);
  10594. EXPECT_EQ(0U, res->body.find("<html>"));
  10595. }
  10596. }
  10597. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  10598. Server svr;
  10599. std::vector<bool> released;
  10600. std::mutex released_mutex;
  10601. auto releaser = [&](bool success) {
  10602. std::lock_guard<std::mutex> guard(released_mutex);
  10603. released.push_back(success);
  10604. };
  10605. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  10606. return sink.write(&"hello"[offset], length);
  10607. };
  10608. svr.Get("/sized", [&](const Request &, Response &res) {
  10609. res.status = StatusCode::NotFound_404;
  10610. res.set_content_provider(5, "text/plain", provider, releaser);
  10611. });
  10612. svr.Get("/chunked", [&](const Request &, Response &res) {
  10613. res.status = StatusCode::ServiceUnavailable_503;
  10614. res.set_chunked_content_provider(
  10615. "text/plain",
  10616. [](size_t, DataSink &sink) {
  10617. sink.os << "chunk";
  10618. sink.done();
  10619. return true;
  10620. },
  10621. releaser);
  10622. });
  10623. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  10624. res.set_content_provider(5, "text/plain", provider, releaser);
  10625. throw std::runtime_error("after the provider");
  10626. });
  10627. svr.set_error_handler([](const Request &req, Response &res) {
  10628. // Leave the exception handler's content to it.
  10629. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  10630. res.set_content(std::string(1000, 'E'), "text/html");
  10631. return Server::HandlerResponse::Handled;
  10632. });
  10633. svr.set_exception_handler(
  10634. [](const Request &, Response &res, std::exception_ptr) {
  10635. res.status = StatusCode::InternalServerError_500;
  10636. res.set_content(std::string(1000, 'X'), "text/html");
  10637. });
  10638. auto port = svr.bind_to_any_port(HOST);
  10639. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10640. auto se = detail::scope_exit([&] {
  10641. svr.stop();
  10642. t.join();
  10643. ASSERT_FALSE(svr.is_running());
  10644. });
  10645. svr.wait_until_ready();
  10646. Client cli(HOST, port);
  10647. {
  10648. auto res = cli.Get("/sized");
  10649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10650. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10651. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10652. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  10653. }
  10654. {
  10655. auto res = cli.Get("/chunked");
  10656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10657. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  10658. EXPECT_EQ(std::string(1000, 'E'), res->body);
  10659. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  10660. }
  10661. {
  10662. auto res = cli.Get("/throw");
  10663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10664. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  10665. EXPECT_EQ(std::string(1000, 'X'), res->body);
  10666. }
  10667. std::lock_guard<std::mutex> guard(released_mutex);
  10668. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  10669. }
  10670. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  10671. Server svr;
  10672. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  10673. return sink.write(&"abc"[offset], length);
  10674. };
  10675. svr.Get("/file-then-body", [](const Request &, Response &res) {
  10676. res.set_file_content("./www/dir/test.html");
  10677. res.set_content("body", "text/plain");
  10678. });
  10679. svr.Get("/body-then-file", [](const Request &, Response &res) {
  10680. res.set_content(std::string(100, 'B'), "text/plain");
  10681. res.set_file_content("./www/dir/test.html");
  10682. });
  10683. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  10684. res.set_content(std::string(100, 'B'), "text/plain");
  10685. res.set_content_provider(3, "text/plain", abc);
  10686. });
  10687. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  10688. res.set_content_provider(3, "text/plain", abc);
  10689. res.set_content(std::string(100, 'B'), "text/plain");
  10690. });
  10691. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  10692. res.set_content_provider(3, "text/plain", abc);
  10693. res.body = "direct";
  10694. });
  10695. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  10696. res.set_file_content("./www/dir/test.html");
  10697. res.body = "direct";
  10698. });
  10699. auto port = svr.bind_to_any_port(HOST);
  10700. auto t = std::thread([&]() { svr.listen_after_bind(); });
  10701. auto se = detail::scope_exit([&] {
  10702. svr.stop();
  10703. t.join();
  10704. ASSERT_FALSE(svr.is_running());
  10705. });
  10706. svr.wait_until_ready();
  10707. Client cli(HOST, port);
  10708. auto expect_body = [&](const char *path, const std::string &body) {
  10709. // Uncompressed, so Content-Length can be compared with the body.
  10710. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  10711. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  10712. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10713. EXPECT_EQ(body, res->body) << path;
  10714. EXPECT_EQ(std::to_string(body.size()),
  10715. res->get_header_value("Content-Length"))
  10716. << path;
  10717. };
  10718. expect_body("/file-then-body", "body");
  10719. expect_body("/body-then-file", "test.html");
  10720. expect_body("/body-then-provider", "abc");
  10721. expect_body("/provider-then-body", std::string(100, 'B'));
  10722. expect_body("/provider-then-direct-body", "direct");
  10723. expect_body("/file-then-direct-body", "direct");
  10724. // Ranges are checked against the body, not the dropped provider.
  10725. {
  10726. auto res = cli.Get("/provider-then-direct-body",
  10727. Headers{{make_range_header({{1, 2}})}});
  10728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10729. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10730. EXPECT_EQ("ir", res->body);
  10731. }
  10732. {
  10733. auto res = cli.Get("/file-then-direct-body",
  10734. Headers{{make_range_header({{7, 8}})}});
  10735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10736. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  10737. }
  10738. }
  10739. // Forward declaration (see the base64_encode note).
  10740. namespace httplib {
  10741. namespace detail {
  10742. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  10743. const std::string &content_type,
  10744. EncodingType encoding);
  10745. } // namespace detail
  10746. } // namespace httplib
  10747. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  10748. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  10749. ASSERT_TRUE(mm->is_open());
  10750. Response res;
  10751. detail::set_file_content_provider(res, mm, "text/html",
  10752. detail::EncodingType::None);
  10753. std::string out;
  10754. DataSink sink;
  10755. sink.write = [&](const char *d, size_t l) {
  10756. out.append(d, l);
  10757. return true;
  10758. };
  10759. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  10760. EXPECT_EQ("test.html", out);
  10761. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  10762. EXPECT_EQ("test.html", out);
  10763. }
  10764. TEST(LongPollingTest, ClientCloseDetection) {
  10765. Server svr;
  10766. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10767. res.set_chunked_content_provider(
  10768. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10769. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10770. sink.os << "hello";
  10771. auto count = 10;
  10772. while (count > 0 && sink.is_writable()) {
  10773. this_thread::sleep_for(chrono::milliseconds(10));
  10774. count--;
  10775. }
  10776. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  10777. return true;
  10778. });
  10779. });
  10780. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10781. auto se = detail::scope_exit([&] {
  10782. svr.stop();
  10783. listen_thread.join();
  10784. ASSERT_FALSE(svr.is_running());
  10785. });
  10786. svr.wait_until_ready();
  10787. Client cli("localhost", PORT);
  10788. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10789. EXPECT_EQ("hello", string(data, data_length));
  10790. return false; // close the socket immediately.
  10791. });
  10792. ASSERT_FALSE(res);
  10793. }
  10794. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  10795. Server svr;
  10796. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  10797. res.set_chunked_content_provider(
  10798. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  10799. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  10800. sink.os << "hello";
  10801. EXPECT_TRUE(sink.os.good());
  10802. // Wait for the client to close the connection
  10803. auto count = 10;
  10804. while (count > 0 && sink.is_writable()) {
  10805. this_thread::sleep_for(chrono::milliseconds(10));
  10806. count--;
  10807. }
  10808. // After client disconnect, write repeatedly until the socket
  10809. // write actually fails (small writes may be absorbed by the
  10810. // kernel buffer)
  10811. std::string chunk(1024, 'x');
  10812. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10813. sink.os << chunk;
  10814. }
  10815. EXPECT_TRUE(sink.os.fail());
  10816. return true;
  10817. });
  10818. });
  10819. auto port = svr.bind_to_any_port("localhost");
  10820. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10821. auto se = detail::scope_exit([&] {
  10822. svr.stop();
  10823. listen_thread.join();
  10824. ASSERT_FALSE(svr.is_running());
  10825. });
  10826. svr.wait_until_ready();
  10827. Client cli("localhost", port);
  10828. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10829. EXPECT_EQ("hello", string(data, data_length));
  10830. return false; // close the socket immediately.
  10831. });
  10832. ASSERT_FALSE(res);
  10833. }
  10834. TEST(GetWithParametersTest, GetWithParameters) {
  10835. Server svr;
  10836. svr.Get("/", [&](const Request &req, Response &) {
  10837. EXPECT_EQ("world", req.get_param_value("hello"));
  10838. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10839. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10840. });
  10841. svr.Get("/params", [&](const Request &req, Response &) {
  10842. EXPECT_EQ("world", req.get_param_value("hello"));
  10843. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10844. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10845. });
  10846. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10847. EXPECT_EQ("resource-id", req.matches[1]);
  10848. EXPECT_EQ("foo", req.get_param_value("param1"));
  10849. EXPECT_EQ("bar", req.get_param_value("param2"));
  10850. });
  10851. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10852. EXPECT_EQ("user-id", req.path_params.at("id"));
  10853. EXPECT_EQ("foo", req.get_param_value("param1"));
  10854. EXPECT_EQ("bar", req.get_param_value("param2"));
  10855. });
  10856. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10857. auto se = detail::scope_exit([&] {
  10858. svr.stop();
  10859. listen_thread.join();
  10860. ASSERT_FALSE(svr.is_running());
  10861. });
  10862. svr.wait_until_ready();
  10863. {
  10864. Client cli(HOST, PORT);
  10865. Params params;
  10866. params.emplace("hello", "world");
  10867. params.emplace("hello2", "world2");
  10868. params.emplace("hello3", "world3");
  10869. auto res = cli.Get("/", params, Headers{});
  10870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10871. EXPECT_EQ(StatusCode::OK_200, res->status);
  10872. }
  10873. {
  10874. Client cli(HOST, PORT);
  10875. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10877. EXPECT_EQ(StatusCode::OK_200, res->status);
  10878. }
  10879. {
  10880. Client cli(HOST, PORT);
  10881. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10883. EXPECT_EQ(StatusCode::OK_200, res->status);
  10884. }
  10885. {
  10886. Client cli(HOST, PORT);
  10887. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10889. EXPECT_EQ(StatusCode::OK_200, res->status);
  10890. }
  10891. }
  10892. TEST(GetWithParametersTest, GetWithParameters2) {
  10893. Server svr;
  10894. svr.Get("/", [&](const Request &req, Response &res) {
  10895. auto text = req.get_param_value("hello");
  10896. res.set_content(text, "text/plain");
  10897. });
  10898. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10899. auto se = detail::scope_exit([&] {
  10900. svr.stop();
  10901. listen_thread.join();
  10902. ASSERT_FALSE(svr.is_running());
  10903. });
  10904. svr.wait_until_ready();
  10905. Client cli("localhost", PORT);
  10906. Params params;
  10907. params.emplace("hello", "world");
  10908. std::string body;
  10909. auto res = cli.Get("/", params, Headers{},
  10910. [&](const char *data, size_t data_length) {
  10911. body.append(data, data_length);
  10912. return true;
  10913. });
  10914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10915. EXPECT_EQ(StatusCode::OK_200, res->status);
  10916. EXPECT_EQ("world", body);
  10917. }
  10918. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10919. Server svr;
  10920. svr.Get("/search", [&](const Request &req, Response &res) {
  10921. auto q = req.get_param_value("q");
  10922. res.set_content(q, "text/plain");
  10923. });
  10924. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10925. auto se = detail::scope_exit([&] {
  10926. svr.stop();
  10927. listen_thread.join();
  10928. ASSERT_FALSE(svr.is_running());
  10929. });
  10930. svr.wait_until_ready();
  10931. Client cli("localhost", PORT);
  10932. // Verify that Get(path, params) works without requiring Headers argument
  10933. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10935. EXPECT_EQ(StatusCode::OK_200, res->status);
  10936. EXPECT_EQ("cpp-httplib", res->body);
  10937. }
  10938. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10939. auto host = "httpbingo.org";
  10940. auto path = std::string{"/range/32"};
  10941. #ifdef CPPHTTPLIB_SSL_ENABLED
  10942. SSLClient cli(host);
  10943. #else
  10944. Client cli(host);
  10945. #endif
  10946. cli.set_default_headers({make_range_header({{1, 10}})});
  10947. cli.set_connection_timeout(5);
  10948. {
  10949. auto res = cli.Get(path);
  10950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10951. EXPECT_EQ("bcdefghijk", res->body);
  10952. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10953. }
  10954. {
  10955. auto res = cli.Get(path);
  10956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10957. EXPECT_EQ("bcdefghijk", res->body);
  10958. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10959. }
  10960. }
  10961. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10962. Server svr;
  10963. svr.set_default_headers({{"Hello", "World"}});
  10964. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10965. res.set_content("ok", "text/plain");
  10966. });
  10967. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10968. auto se = detail::scope_exit([&] {
  10969. svr.stop();
  10970. listen_thread.join();
  10971. ASSERT_FALSE(svr.is_running());
  10972. });
  10973. svr.wait_until_ready();
  10974. Client cli("localhost", PORT);
  10975. auto res = cli.Get("/");
  10976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10977. EXPECT_EQ(StatusCode::OK_200, res->status);
  10978. EXPECT_EQ("ok", res->body);
  10979. EXPECT_EQ("World", res->get_header_value("Hello"));
  10980. }
  10981. #ifdef CPPHTTPLIB_SSL_ENABLED
  10982. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10983. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10984. ASSERT_TRUE(svr.is_valid());
  10985. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10986. std::this_thread::sleep_for(std::chrono::seconds(2));
  10987. res.set_content("a", "text/plain");
  10988. });
  10989. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10990. res.set_content("b", "text/plain");
  10991. });
  10992. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10993. auto se = detail::scope_exit([&] {
  10994. svr.stop();
  10995. listen_thread.join();
  10996. ASSERT_FALSE(svr.is_running());
  10997. });
  10998. svr.wait_until_ready();
  10999. SSLClient cli("localhost", PORT);
  11000. cli.enable_server_certificate_verification(false);
  11001. cli.set_keep_alive(true);
  11002. cli.set_read_timeout(std::chrono::seconds(1));
  11003. auto resa = cli.Get("/a");
  11004. ASSERT_TRUE(!resa);
  11005. EXPECT_EQ(Error::Read, resa.error());
  11006. auto resb = cli.Get("/b");
  11007. ASSERT_TRUE(resb);
  11008. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11009. EXPECT_EQ("b", resb->body);
  11010. }
  11011. // Closing an idle keep-alive connection sends close_notify and returns. The
  11012. // server must not wait for the client's close_notify: an idle client never
  11013. // sends one, so the worker would be held until the read timeout expires, and
  11014. // stop() would wait for it.
  11015. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11016. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11017. ASSERT_TRUE(svr.is_valid());
  11018. svr.set_keep_alive_timeout(1);
  11019. svr.set_read_timeout(10, 0);
  11020. svr.Get("/", [](const Request &, Response &res) {
  11021. res.set_content("ok", "text/plain");
  11022. });
  11023. auto port = svr.bind_to_any_port(HOST);
  11024. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11025. auto se = detail::scope_exit([&] {
  11026. if (listen_thread.joinable()) {
  11027. svr.stop();
  11028. listen_thread.join();
  11029. }
  11030. });
  11031. svr.wait_until_ready();
  11032. SSLClient cli(HOST, port);
  11033. cli.enable_server_certificate_verification(false);
  11034. cli.set_keep_alive(true);
  11035. auto res = cli.Get("/");
  11036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11037. EXPECT_EQ(StatusCode::OK_200, res->status);
  11038. // Stay idle past the keep-alive timeout so the server closes the connection.
  11039. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  11040. auto start = std::chrono::steady_clock::now();
  11041. svr.stop();
  11042. listen_thread.join();
  11043. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  11044. std::chrono::steady_clock::now() - start)
  11045. .count();
  11046. EXPECT_LT(elapsed, 3000);
  11047. }
  11048. #endif
  11049. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  11050. protected:
  11051. ServerTestWithAI_PASSIVE()
  11052. : cli_(HOST, PORT)
  11053. #ifdef CPPHTTPLIB_SSL_ENABLED
  11054. ,
  11055. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11056. #endif
  11057. {
  11058. #ifdef CPPHTTPLIB_SSL_ENABLED
  11059. cli_.enable_server_certificate_verification(false);
  11060. #endif
  11061. }
  11062. virtual void SetUp() {
  11063. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11064. res.set_content("Hello World!", "text/plain");
  11065. });
  11066. t_ = thread(
  11067. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  11068. svr_.wait_until_ready();
  11069. }
  11070. virtual void TearDown() {
  11071. svr_.stop();
  11072. t_.join();
  11073. }
  11074. #ifdef CPPHTTPLIB_SSL_ENABLED
  11075. SSLClient cli_;
  11076. SSLServer svr_;
  11077. #else
  11078. Client cli_;
  11079. Server svr_;
  11080. #endif
  11081. thread t_;
  11082. };
  11083. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  11084. auto res = cli_.Get("/hi");
  11085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11086. EXPECT_EQ(StatusCode::OK_200, res->status);
  11087. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  11088. EXPECT_EQ("Hello World!", res->body);
  11089. }
  11090. class ServerUpDownTest : public ::testing::Test {
  11091. protected:
  11092. ServerUpDownTest() : cli_(HOST, PORT) {}
  11093. virtual void SetUp() {
  11094. t_ = thread([&]() {
  11095. svr_.bind_to_any_port(HOST);
  11096. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11097. ASSERT_TRUE(svr_.listen_after_bind());
  11098. });
  11099. svr_.wait_until_ready();
  11100. }
  11101. virtual void TearDown() {
  11102. svr_.stop();
  11103. t_.join();
  11104. }
  11105. Client cli_;
  11106. Server svr_;
  11107. thread t_;
  11108. };
  11109. TEST_F(ServerUpDownTest, QuickStartStop) {
  11110. // Should not crash, especially when run with
  11111. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  11112. }
  11113. class PayloadMaxLengthTest : public ::testing::Test {
  11114. protected:
  11115. PayloadMaxLengthTest()
  11116. : cli_(HOST, PORT)
  11117. #ifdef CPPHTTPLIB_SSL_ENABLED
  11118. ,
  11119. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11120. #endif
  11121. {
  11122. #ifdef CPPHTTPLIB_SSL_ENABLED
  11123. cli_.enable_server_certificate_verification(false);
  11124. #endif
  11125. }
  11126. virtual void SetUp() {
  11127. svr_.set_payload_max_length(8);
  11128. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11129. res.set_content("test", "text/plain");
  11130. });
  11131. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11132. svr_.wait_until_ready();
  11133. }
  11134. virtual void TearDown() {
  11135. svr_.stop();
  11136. t_.join();
  11137. }
  11138. #ifdef CPPHTTPLIB_SSL_ENABLED
  11139. SSLClient cli_;
  11140. SSLServer svr_;
  11141. #else
  11142. Client cli_;
  11143. Server svr_;
  11144. #endif
  11145. thread t_;
  11146. };
  11147. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  11148. auto res = cli_.Post("/test", "123456789", "text/plain");
  11149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11150. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11151. res = cli_.Post("/test", "12345678", "text/plain");
  11152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11153. EXPECT_EQ(StatusCode::OK_200, res->status);
  11154. }
  11155. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  11156. // Test chunked encoding with payload exceeding the 8-byte limit
  11157. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  11158. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  11159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11160. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11161. }
  11162. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  11163. // Test chunked encoding with payload within the 8-byte limit
  11164. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  11165. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  11166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11167. EXPECT_EQ(StatusCode::OK_200, res->status);
  11168. }
  11169. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  11170. // Test using send_request to send chunked data exceeding payload limit
  11171. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  11172. "Host: " +
  11173. std::string(HOST) + ":" + std::to_string(PORT) +
  11174. "\r\n"
  11175. "Transfer-Encoding: chunked\r\n"
  11176. "Connection: close\r\n"
  11177. "\r\n"
  11178. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  11179. "0123456789\r\n"
  11180. "0\r\n" // End chunk
  11181. "\r\n";
  11182. std::string response;
  11183. bool result = send_request(1, chunked_request, &response);
  11184. if (!result) {
  11185. // If send_request fails, it might be because the server closed the
  11186. // connection due to payload limit enforcement, which is acceptable
  11187. SUCCEED()
  11188. << "Server rejected oversized chunked request (connection closed)";
  11189. } else {
  11190. // If we got a response, check if it's an error response or connection was
  11191. // closed early Short response length indicates connection was closed due to
  11192. // payload limit
  11193. if (response.length() <= 10) {
  11194. SUCCEED() << "Server closed connection for oversized chunked request";
  11195. } else {
  11196. // Check for error status codes
  11197. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11198. response.find("Payload Too Large") != std::string::npos ||
  11199. response.find("400") != std::string::npos);
  11200. }
  11201. }
  11202. }
  11203. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  11204. // Test request without Content-Length header exceeding payload limit
  11205. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11206. "Host: " +
  11207. std::string(HOST) + ":" +
  11208. std::to_string(PORT) +
  11209. "\r\n"
  11210. "Connection: close\r\n"
  11211. "\r\n";
  11212. // Add payload exceeding the 8-byte limit
  11213. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  11214. request_without_content_length += large_payload;
  11215. std::string response;
  11216. bool result = send_request(1, request_without_content_length, &response);
  11217. if (!result) {
  11218. // If send_request fails, server likely closed connection due to payload
  11219. // limit
  11220. SUCCEED() << "Server rejected oversized request without Content-Length "
  11221. "(connection closed)";
  11222. } else {
  11223. // Check if server responded with error or closed connection early
  11224. if (response.length() <= 10) {
  11225. SUCCEED() << "Server closed connection for oversized request without "
  11226. "Content-Length";
  11227. } else {
  11228. // Check for error status codes
  11229. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11230. response.find("Payload Too Large") != std::string::npos ||
  11231. response.find("400") != std::string::npos);
  11232. }
  11233. }
  11234. }
  11235. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  11236. // Test request without Content-Length header within payload limit
  11237. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11238. "Host: " +
  11239. std::string(HOST) + ":" +
  11240. std::to_string(PORT) +
  11241. "\r\n"
  11242. "Connection: close\r\n"
  11243. "\r\n";
  11244. // Add payload within the 8-byte limit
  11245. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  11246. request_without_content_length += small_payload;
  11247. std::string response;
  11248. bool result = send_request(1, request_without_content_length, &response);
  11249. // For requests without Content-Length, the server may have different behavior
  11250. // The key is that it should not reject due to payload limit for small
  11251. // payloads
  11252. if (result) {
  11253. // Check for any HTTP response (success or error, but not connection closed)
  11254. if (response.length() > 10) {
  11255. SUCCEED()
  11256. << "Server processed request without Content-Length within limit";
  11257. } else {
  11258. // Short response might indicate connection closed, which is acceptable
  11259. SUCCEED() << "Server closed connection for request without "
  11260. "Content-Length (acceptable behavior)";
  11261. }
  11262. } else {
  11263. // Connection failure might be due to protocol requirements
  11264. SUCCEED() << "Connection issue with request without Content-Length "
  11265. "(environment-specific)";
  11266. }
  11267. }
  11268. class LargePayloadMaxLengthTest : public ::testing::Test {
  11269. protected:
  11270. LargePayloadMaxLengthTest()
  11271. : cli_(HOST, PORT)
  11272. #ifdef CPPHTTPLIB_SSL_ENABLED
  11273. ,
  11274. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  11275. #endif
  11276. {
  11277. #ifdef CPPHTTPLIB_SSL_ENABLED
  11278. cli_.enable_server_certificate_verification(false);
  11279. #endif
  11280. }
  11281. virtual void SetUp() {
  11282. // Set 10MB payload limit
  11283. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  11284. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  11285. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  11286. res.set_content("Large payload test", "text/plain");
  11287. });
  11288. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  11289. svr_.wait_until_ready();
  11290. }
  11291. virtual void TearDown() {
  11292. svr_.stop();
  11293. t_.join();
  11294. }
  11295. #ifdef CPPHTTPLIB_SSL_ENABLED
  11296. SSLClient cli_;
  11297. SSLServer svr_;
  11298. #else
  11299. Client cli_;
  11300. Server svr_;
  11301. #endif
  11302. thread t_;
  11303. };
  11304. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  11305. // Test chunked encoding with payload within 10MB limit
  11306. std::string medium_payload(5 * 1024 * 1024,
  11307. 'A'); // 5MB payload, within 10MB limit
  11308. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  11309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11310. EXPECT_EQ(StatusCode::OK_200, res->status);
  11311. }
  11312. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  11313. // Test chunked encoding with payload exceeding 10MB limit
  11314. std::string large_payload(12 * 1024 * 1024,
  11315. 'B'); // 12MB payload, exceeds 10MB limit
  11316. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  11317. // Server may either return 413 or close the connection
  11318. if (res) {
  11319. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11320. } else {
  11321. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  11322. }
  11323. }
  11324. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  11325. // Test request without Content-Length header within 10MB limit
  11326. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11327. "Host: " +
  11328. std::string(HOST) + ":" +
  11329. std::to_string(PORT) +
  11330. "\r\n"
  11331. "Connection: close\r\n"
  11332. "\r\n";
  11333. // Add 1MB payload (within 10MB limit)
  11334. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  11335. request_without_content_length += medium_payload;
  11336. std::string response;
  11337. bool result = send_request(5, request_without_content_length, &response);
  11338. if (result) {
  11339. // Should get a proper HTTP response for payloads within limit
  11340. if (response.length() > 10) {
  11341. SUCCEED() << "Server processed 1MB request without Content-Length within "
  11342. "10MB limit";
  11343. } else {
  11344. SUCCEED() << "Server closed connection (acceptable behavior for no "
  11345. "Content-Length)";
  11346. }
  11347. } else {
  11348. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  11349. }
  11350. }
  11351. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  11352. // Test request without Content-Length header exceeding 10MB limit
  11353. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  11354. "Host: " +
  11355. std::string(HOST) + ":" +
  11356. std::to_string(PORT) +
  11357. "\r\n"
  11358. "Connection: close\r\n"
  11359. "\r\n";
  11360. // Add 12MB payload (exceeds 10MB limit)
  11361. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  11362. request_without_content_length += large_payload;
  11363. std::string response;
  11364. bool result = send_request(10, request_without_content_length, &response);
  11365. if (!result) {
  11366. // Server should close connection due to payload limit
  11367. SUCCEED() << "Server rejected 12MB request without Content-Length "
  11368. "(connection closed)";
  11369. } else {
  11370. // Check for error response
  11371. if (response.length() <= 10) {
  11372. SUCCEED()
  11373. << "Server closed connection for 12MB request exceeding 10MB limit";
  11374. } else {
  11375. EXPECT_TRUE(response.find("413") != std::string::npos ||
  11376. response.find("Payload Too Large") != std::string::npos ||
  11377. response.find("400") != std::string::npos);
  11378. }
  11379. }
  11380. }
  11381. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  11382. Server svr;
  11383. svr.Get("/", [](const Request &, Response &res) {
  11384. // Claims far more than it sends, then drops the connection.
  11385. res.set_content_provider(size_t(1) << 41, "text/plain",
  11386. [](size_t, size_t, DataSink &sink) {
  11387. sink.write("abc", 3);
  11388. return false;
  11389. });
  11390. });
  11391. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11392. auto se = detail::scope_exit([&] {
  11393. svr.stop();
  11394. thread.join();
  11395. ASSERT_FALSE(svr.is_running());
  11396. });
  11397. svr.wait_until_ready();
  11398. Client cli(HOST, PORT);
  11399. cli.set_payload_max_length(0);
  11400. EXPECT_FALSE(cli.Get("/"));
  11401. }
  11402. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11403. // `payload_max_length` is not enforced on decompressed body in ContentReader
  11404. // path.
  11405. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  11406. Server svr;
  11407. const size_t LIMIT = 64 * 1024; // 64KB
  11408. svr.set_payload_max_length(LIMIT);
  11409. size_t total = 0;
  11410. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11411. const ContentReader &content_reader) {
  11412. content_reader([&](const char * /*data*/, size_t len) {
  11413. total += len;
  11414. return true;
  11415. });
  11416. res.status = 200;
  11417. res.set_content("stream_ok", "text/plain");
  11418. });
  11419. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11420. auto se = detail::scope_exit([&] {
  11421. svr.stop();
  11422. thread.join();
  11423. ASSERT_FALSE(svr.is_running());
  11424. });
  11425. svr.wait_until_ready();
  11426. // Prepare 256KB raw data and gzip-compress it
  11427. std::string raw(256 * 1024, 'A');
  11428. std::string gz;
  11429. {
  11430. z_stream zs{};
  11431. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  11432. Z_DEFAULT_STRATEGY);
  11433. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  11434. zs.avail_in = static_cast<uInt>(raw.size());
  11435. char outbuf[4096];
  11436. int ret;
  11437. do {
  11438. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  11439. zs.avail_out = sizeof(outbuf);
  11440. ret = deflate(&zs, Z_FINISH);
  11441. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  11442. } while (ret != Z_STREAM_END);
  11443. deflateEnd(&zs);
  11444. }
  11445. Client cli(HOST, PORT);
  11446. cli.set_connection_timeout(std::chrono::seconds(5));
  11447. Headers headers = {{"Content-Encoding", "gzip"}};
  11448. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  11449. "application/octet-stream");
  11450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11451. // Server must reject oversized decompressed payloads with 413.
  11452. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  11453. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11454. EXPECT_LE(total, LIMIT);
  11455. }
  11456. #ifndef CPPHTTPLIB_SSL_ENABLED
  11457. // For a request with neither Content-Length nor Transfer-Encoding, the
  11458. // non-SSL raw-socket fallback in read_content_core() used to hand the
  11459. // compressed wire bytes straight to the ContentReader without ever routing
  11460. // them through the decompressor, so payload_max_length_ only bounded the
  11461. // compressed size on the wire, not the decompressed size.
  11462. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  11463. Server svr;
  11464. const size_t LIMIT = 64 * 1024; // 64KB
  11465. svr.set_payload_max_length(LIMIT);
  11466. size_t total = 0;
  11467. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  11468. const ContentReader &content_reader) {
  11469. content_reader([&](const char * /*data*/, size_t len) {
  11470. total += len;
  11471. return true;
  11472. });
  11473. res.status = 200;
  11474. res.set_content("stream_ok", "text/plain");
  11475. });
  11476. auto port = svr.bind_to_any_port(HOST);
  11477. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  11478. auto se = detail::scope_exit([&] {
  11479. svr.stop();
  11480. thread.join();
  11481. ASSERT_FALSE(svr.is_running());
  11482. });
  11483. svr.wait_until_ready();
  11484. // Prepare 256KB raw data and gzip-compress it, same payload as the
  11485. // StreamingGzipDecompression test above.
  11486. std::string raw(256 * 1024, 'A');
  11487. std::string gz;
  11488. {
  11489. httplib::detail::gzip_compressor compressor;
  11490. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  11491. [&](const char *chunk, size_t len) {
  11492. gz.append(chunk, len);
  11493. return true;
  11494. });
  11495. ASSERT_TRUE(result);
  11496. }
  11497. // Send the gzip body over raw TCP with neither Content-Length nor
  11498. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  11499. // kicks in.
  11500. std::string req = "POST /stream HTTP/1.1\r\n"
  11501. "Host: " +
  11502. std::string(HOST) + ":" + std::to_string(port) +
  11503. "\r\n"
  11504. "Content-Encoding: gzip\r\n"
  11505. "Connection: close\r\n"
  11506. "\r\n" +
  11507. gz;
  11508. std::string response;
  11509. ASSERT_TRUE(send_request(5, req, &response, port));
  11510. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  11511. EXPECT_LE(total, LIMIT);
  11512. }
  11513. #endif
  11514. #endif
  11515. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  11516. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  11517. // the payload must be passed through untouched instead of being rejected.
  11518. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  11519. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11520. Server svr;
  11521. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  11522. res.set_content(body, "image/jpeg");
  11523. res.set_header("Content-Encoding", "UTF-8");
  11524. });
  11525. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  11526. res.set_content(body, "image/jpeg");
  11527. res.set_header("Content-Encoding", "identity");
  11528. });
  11529. svr.Post("/echo", [](const Request &req, Response &res) {
  11530. res.set_content(req.body, "image/jpeg");
  11531. });
  11532. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11533. auto se = detail::scope_exit([&] {
  11534. svr.stop();
  11535. t.join();
  11536. ASSERT_FALSE(svr.is_running());
  11537. });
  11538. svr.wait_until_ready();
  11539. Client cli(HOST, PORT);
  11540. {
  11541. auto res = cli.Get("/image");
  11542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11543. EXPECT_EQ(StatusCode::OK_200, res->status);
  11544. EXPECT_EQ(body, res->body);
  11545. }
  11546. {
  11547. auto res = cli.Get("/identity");
  11548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11549. EXPECT_EQ(StatusCode::OK_200, res->status);
  11550. EXPECT_EQ(body, res->body);
  11551. }
  11552. {
  11553. // The same applies to a request body reaching the server.
  11554. Headers headers = {{"Content-Encoding", "UTF-8"}};
  11555. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  11556. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11557. EXPECT_EQ(StatusCode::OK_200, res->status);
  11558. EXPECT_EQ(body, res->body);
  11559. }
  11560. }
  11561. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  11562. // gzip-encoded response even when the build has no zlib support.
  11563. static const char GZIPPED_HELLO_WORLD[] = {
  11564. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  11565. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  11566. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  11567. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  11568. // A content coding is a whole token, not something the field value merely
  11569. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  11570. // as "fibre" look like Brotli, and turned a multi-coding value like
  11571. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  11572. // it was never meant to see.
  11573. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  11574. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11575. Server svr;
  11576. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  11577. res.set_content(body, "image/jpeg");
  11578. res.set_header("Content-Encoding", "fibre");
  11579. });
  11580. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  11581. res.set_content(body, "image/jpeg");
  11582. res.set_header("Content-Encoding", "gzip, br");
  11583. });
  11584. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  11585. res.set_content(body, "image/jpeg");
  11586. res.set_header("Content-Encoding", "x-zstd-ish");
  11587. });
  11588. auto port = svr.bind_to_any_port(HOST);
  11589. thread t = thread([&]() { svr.listen_after_bind(); });
  11590. auto se = detail::scope_exit([&] {
  11591. svr.stop();
  11592. t.join();
  11593. ASSERT_FALSE(svr.is_running());
  11594. });
  11595. svr.wait_until_ready();
  11596. Client cli(HOST, port);
  11597. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  11598. auto res = cli.Get(path);
  11599. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11600. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11601. // Not a coding we recognize, so the payload comes back untouched
  11602. EXPECT_EQ(body, res->body) << path;
  11603. }
  11604. }
  11605. // A content coding cpp-httplib recognizes but was not built with must be
  11606. // reported as such. Handing the still-compressed payload back to the caller
  11607. // would silently corrupt it.
  11608. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  11609. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11610. Server svr;
  11611. // "image/jpeg" keeps the server from applying a content coding of its own,
  11612. // so the hand-crafted Content-Encoding below survives.
  11613. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  11614. res.set_content(gzipped, "image/jpeg");
  11615. res.set_header("Content-Encoding", "gzip");
  11616. });
  11617. // Content codings are case-insensitive (RFC 9110 8.4.1).
  11618. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  11619. res.set_content(gzipped, "image/jpeg");
  11620. res.set_header("Content-Encoding", "GZIP");
  11621. });
  11622. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11623. auto se = detail::scope_exit([&] {
  11624. svr.stop();
  11625. t.join();
  11626. ASSERT_FALSE(svr.is_running());
  11627. });
  11628. svr.wait_until_ready();
  11629. Client cli(HOST, PORT);
  11630. {
  11631. auto res = cli.Get("/gzipped");
  11632. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11634. EXPECT_EQ("Hello World!", res->body);
  11635. #else
  11636. ASSERT_FALSE(res);
  11637. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11638. #endif
  11639. }
  11640. {
  11641. // open_stream() must behave the same way.
  11642. auto handle = cli.open_stream("GET", "/gzipped");
  11643. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11644. ASSERT_TRUE(handle.is_valid());
  11645. std::string received;
  11646. char buf[256];
  11647. ssize_t n;
  11648. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  11649. received.append(buf, static_cast<size_t>(n));
  11650. }
  11651. EXPECT_EQ("Hello World!", received);
  11652. #else
  11653. EXPECT_FALSE(handle.is_valid());
  11654. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  11655. #endif
  11656. }
  11657. {
  11658. // A differently-cased coding must not be mistaken for an unknown one, or
  11659. // the body would be handed back still compressed.
  11660. auto res = cli.Get("/gzipped-uppercase");
  11661. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11663. EXPECT_EQ("Hello World!", res->body);
  11664. #else
  11665. ASSERT_FALSE(res);
  11666. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  11667. #endif
  11668. }
  11669. }
  11670. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11671. // A handler serving pre-compressed content (e.g. build-time gzipped static
  11672. // assets) sets Content-Encoding itself. The server used to pick a coding from
  11673. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  11674. // body a second time and appending a second Content-Encoding field line, so
  11675. // clients that decode one coding per listed value handed back raw gzip bytes.
  11676. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  11677. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11678. Server svr;
  11679. // text/plain is a compressible type, so only the pre-set Content-Encoding
  11680. // keeps the server from applying a coding of its own.
  11681. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11682. res.set_content(gzipped, "text/plain");
  11683. res.set_header("Content-Encoding", "gzip");
  11684. });
  11685. auto port = svr.bind_to_any_port(HOST);
  11686. thread t = thread([&]() { svr.listen_after_bind(); });
  11687. auto se = detail::scope_exit([&] {
  11688. svr.stop();
  11689. t.join();
  11690. ASSERT_FALSE(svr.is_running());
  11691. });
  11692. svr.wait_until_ready();
  11693. Client cli(HOST, port);
  11694. Headers headers = {{"Accept-Encoding", "gzip"}};
  11695. auto res = cli.Get("/pre-gzipped", headers);
  11696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11697. EXPECT_EQ(StatusCode::OK_200, res->status);
  11698. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11699. EXPECT_EQ("Hello World!", res->body);
  11700. }
  11701. // A chunked provider settles its coding where the headers are written and
  11702. // reuses it at write time. Both ends of that have to hold: a handler's own
  11703. // Content-Encoding suppresses the coding, and a response without one is still
  11704. // compressed as it always was.
  11705. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  11706. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  11707. const std::string plain = "Hello World! Hello World! Hello World!";
  11708. Server svr;
  11709. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  11710. res.set_header("Content-Encoding", "gzip");
  11711. res.set_chunked_content_provider(
  11712. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  11713. sink.write(gzipped.data(), gzipped.size());
  11714. sink.done();
  11715. return true;
  11716. });
  11717. });
  11718. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  11719. res.set_chunked_content_provider(
  11720. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  11721. sink.write(plain.data(), plain.size());
  11722. sink.done();
  11723. return true;
  11724. });
  11725. });
  11726. auto port = svr.bind_to_any_port(HOST);
  11727. thread t = thread([&]() { svr.listen_after_bind(); });
  11728. auto se = detail::scope_exit([&] {
  11729. svr.stop();
  11730. t.join();
  11731. ASSERT_FALSE(svr.is_running());
  11732. });
  11733. svr.wait_until_ready();
  11734. Client cli(HOST, port);
  11735. Headers headers = {{"Accept-Encoding", "gzip"}};
  11736. {
  11737. auto res = cli.Get("/pre-gzipped", headers);
  11738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11739. EXPECT_EQ(StatusCode::OK_200, res->status);
  11740. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  11741. EXPECT_EQ("Hello World!", res->body);
  11742. }
  11743. {
  11744. auto res = cli.Get("/negotiated", headers);
  11745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11746. EXPECT_EQ(StatusCode::OK_200, res->status);
  11747. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  11748. EXPECT_EQ(plain, res->body);
  11749. }
  11750. }
  11751. #endif
  11752. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  11753. // the same message as the comma-joined one, so both have to be read the same
  11754. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  11755. // single gzip coding, and a body the sender says was encoded twice was handed
  11756. // back after one pass, still compressed but presented as decoded.
  11757. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  11758. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  11759. Server svr;
  11760. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  11761. res.set_content(body, "image/jpeg");
  11762. res.headers.emplace("Content-Encoding", "gzip");
  11763. res.headers.emplace("Content-Encoding", "gzip");
  11764. });
  11765. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  11766. res.set_content(body, "image/jpeg");
  11767. res.set_header("Content-Encoding", "gzip, gzip");
  11768. });
  11769. auto port = svr.bind_to_any_port(HOST);
  11770. thread t = thread([&]() { svr.listen_after_bind(); });
  11771. auto se = detail::scope_exit([&] {
  11772. svr.stop();
  11773. t.join();
  11774. ASSERT_FALSE(svr.is_running());
  11775. });
  11776. svr.wait_until_ready();
  11777. Client cli(HOST, port);
  11778. // Two codings is not something cpp-httplib decodes, so both representations
  11779. // take the pass-through path rather than one of them being gunzipped once.
  11780. for (const char *path : {"/split", "/joined"}) {
  11781. auto res = cli.Get(path);
  11782. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  11783. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11784. EXPECT_EQ(body, res->body) << path;
  11785. }
  11786. }
  11787. // Regression test for DoS vulnerability: a malicious server sending a response
  11788. // without Content-Length header must not cause unbounded memory consumption on
  11789. // the client side. The client should stop reading after a reasonable limit,
  11790. // similar to the server-side set_payload_max_length protection.
  11791. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  11792. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11793. #ifndef _WIN32
  11794. signal(SIGPIPE, SIG_IGN);
  11795. #endif
  11796. auto server_thread = std::thread([] {
  11797. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  11798. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11799. default_socket_options(srv);
  11800. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11801. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11802. sockaddr_in addr{};
  11803. addr.sin_family = AF_INET;
  11804. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11805. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11806. int opt = 1;
  11807. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11808. #ifdef _WIN32
  11809. reinterpret_cast<const char *>(&opt),
  11810. #else
  11811. &opt,
  11812. #endif
  11813. sizeof(opt));
  11814. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11815. ::listen(srv, 1);
  11816. sockaddr_in cli_addr{};
  11817. socklen_t cli_len = sizeof(cli_addr);
  11818. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11819. if (cli != INVALID_SOCKET) {
  11820. char buf[4096];
  11821. ::recv(cli, buf, sizeof(buf), 0);
  11822. // Malicious response: no Content-Length, no chunked encoding
  11823. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11824. "Connection: close\r\n"
  11825. "\r\n";
  11826. ::send(cli,
  11827. #ifdef _WIN32
  11828. static_cast<const char *>(response_header.c_str()),
  11829. static_cast<int>(response_header.size()),
  11830. #else
  11831. response_header.c_str(), response_header.size(),
  11832. #endif
  11833. 0);
  11834. // Send 10MB of data
  11835. std::string chunk(64 * 1024, 'A');
  11836. size_t total_sent = 0;
  11837. while (total_sent < MALICIOUS_DATA_SIZE) {
  11838. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11839. auto sent = ::send(cli,
  11840. #ifdef _WIN32
  11841. static_cast<const char *>(chunk.c_str()),
  11842. static_cast<int>(to_send),
  11843. #else
  11844. chunk.c_str(), to_send,
  11845. #endif
  11846. 0);
  11847. if (sent <= 0) break;
  11848. total_sent += static_cast<size_t>(sent);
  11849. }
  11850. detail::close_socket(cli);
  11851. }
  11852. detail::close_socket(srv);
  11853. });
  11854. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11855. size_t total_read = 0;
  11856. {
  11857. Client cli("127.0.0.1", PORT + 2);
  11858. cli.set_read_timeout(5, 0);
  11859. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11860. auto stream = cli.open_stream("GET", "/malicious");
  11861. ASSERT_TRUE(stream.is_valid());
  11862. char buffer[64 * 1024];
  11863. ssize_t n;
  11864. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11865. total_read += static_cast<size_t>(n);
  11866. }
  11867. } // StreamHandle and Client destroyed here, closing the socket
  11868. server_thread.join();
  11869. // With set_payload_max_length, the client must stop reading before consuming
  11870. // all 10MB. The read loop should be cut off at or near the configured limit.
  11871. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11872. << "Client read " << total_read << " bytes, exceeding the configured "
  11873. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11874. }
  11875. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11876. // the entire response body without truncation.
  11877. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11878. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11879. #ifndef _WIN32
  11880. signal(SIGPIPE, SIG_IGN);
  11881. #endif
  11882. auto server_thread = std::thread([] {
  11883. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11884. default_socket_options(srv);
  11885. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11886. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11887. sockaddr_in addr{};
  11888. addr.sin_family = AF_INET;
  11889. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11890. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11891. int opt = 1;
  11892. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11893. #ifdef _WIN32
  11894. reinterpret_cast<const char *>(&opt),
  11895. #else
  11896. &opt,
  11897. #endif
  11898. sizeof(opt));
  11899. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11900. ::listen(srv, 1);
  11901. sockaddr_in cli_addr{};
  11902. socklen_t cli_len = sizeof(cli_addr);
  11903. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11904. if (cli != INVALID_SOCKET) {
  11905. char buf[4096];
  11906. ::recv(cli, buf, sizeof(buf), 0);
  11907. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11908. "Connection: close\r\n"
  11909. "\r\n";
  11910. ::send(cli,
  11911. #ifdef _WIN32
  11912. static_cast<const char *>(response_header.c_str()),
  11913. static_cast<int>(response_header.size()),
  11914. #else
  11915. response_header.c_str(), response_header.size(),
  11916. #endif
  11917. 0);
  11918. std::string chunk(64 * 1024, 'A');
  11919. size_t total_sent = 0;
  11920. while (total_sent < DATA_SIZE) {
  11921. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11922. auto sent = ::send(cli,
  11923. #ifdef _WIN32
  11924. static_cast<const char *>(chunk.c_str()),
  11925. static_cast<int>(to_send),
  11926. #else
  11927. chunk.c_str(), to_send,
  11928. #endif
  11929. 0);
  11930. if (sent <= 0) break;
  11931. total_sent += static_cast<size_t>(sent);
  11932. }
  11933. #ifdef _WIN32
  11934. ::shutdown(cli, SD_SEND);
  11935. #else
  11936. ::shutdown(cli, SHUT_WR);
  11937. #endif
  11938. // Drain until the client closes its end, ensuring all data is delivered
  11939. char drain[1024];
  11940. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11941. detail::close_socket(cli);
  11942. }
  11943. detail::close_socket(srv);
  11944. });
  11945. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11946. size_t total_read = 0;
  11947. {
  11948. Client cli("127.0.0.1", PORT + 2);
  11949. cli.set_read_timeout(5, 0);
  11950. cli.set_payload_max_length(0); // 0 means no limit
  11951. auto stream = cli.open_stream("GET", "/data");
  11952. ASSERT_TRUE(stream.is_valid());
  11953. char buffer[64 * 1024];
  11954. ssize_t n;
  11955. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11956. total_read += static_cast<size_t>(n);
  11957. }
  11958. }
  11959. server_thread.join();
  11960. EXPECT_EQ(total_read, DATA_SIZE)
  11961. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11962. << " bytes without truncation, but only read " << total_read << " bytes.";
  11963. }
  11964. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11965. // enormous Content-Length must not cause the client to pre-allocate a huge
  11966. // response body buffer. The reservation is capped at payload_max_length_, and
  11967. // the read itself fails when the body exceeds the limit.
  11968. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11969. #ifndef _WIN32
  11970. signal(SIGPIPE, SIG_IGN);
  11971. #endif
  11972. auto server_thread = std::thread([] {
  11973. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11974. default_socket_options(srv);
  11975. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11976. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11977. sockaddr_in addr{};
  11978. addr.sin_family = AF_INET;
  11979. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11980. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11981. int opt = 1;
  11982. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11983. #ifdef _WIN32
  11984. reinterpret_cast<const char *>(&opt),
  11985. #else
  11986. &opt,
  11987. #endif
  11988. sizeof(opt));
  11989. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11990. ::listen(srv, 1);
  11991. sockaddr_in cli_addr{};
  11992. socklen_t cli_len = sizeof(cli_addr);
  11993. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11994. if (cli != INVALID_SOCKET) {
  11995. char buf[4096];
  11996. ::recv(cli, buf, sizeof(buf), 0);
  11997. // Malicious response: claim a 20GB body but send only a tiny payload.
  11998. std::string response = "HTTP/1.1 200 OK\r\n"
  11999. "Content-Length: 20000000000\r\n"
  12000. "\r\n"
  12001. "abc";
  12002. ::send(cli,
  12003. #ifdef _WIN32
  12004. static_cast<const char *>(response.c_str()),
  12005. static_cast<int>(response.size()),
  12006. #else
  12007. response.c_str(), response.size(),
  12008. #endif
  12009. 0);
  12010. detail::close_socket(cli);
  12011. }
  12012. detail::close_socket(srv);
  12013. });
  12014. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12015. {
  12016. Client cli("127.0.0.1", PORT + 2);
  12017. cli.set_read_timeout(5, 0);
  12018. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12019. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12020. // (server claims more bytes than payload_max_length permits), but it must
  12021. // not exhaust memory before getting there.
  12022. auto res = cli.Get("/malicious");
  12023. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12024. }
  12025. server_thread.join();
  12026. }
  12027. // Verify that content_receiver bypasses the default payload_max_length,
  12028. // allowing streaming downloads larger than 100MB without requiring an explicit
  12029. // set_payload_max_length call.
  12030. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12031. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12032. #ifndef _WIN32
  12033. signal(SIGPIPE, SIG_IGN);
  12034. #endif
  12035. auto server_thread = std::thread([] {
  12036. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12037. default_socket_options(srv);
  12038. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12039. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12040. sockaddr_in addr{};
  12041. addr.sin_family = AF_INET;
  12042. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12043. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12044. int opt = 1;
  12045. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12046. #ifdef _WIN32
  12047. reinterpret_cast<const char *>(&opt),
  12048. #else
  12049. &opt,
  12050. #endif
  12051. sizeof(opt));
  12052. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12053. ::listen(srv, 1);
  12054. sockaddr_in cli_addr{};
  12055. socklen_t cli_len = sizeof(cli_addr);
  12056. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12057. if (cli != INVALID_SOCKET) {
  12058. char buf[4096];
  12059. ::recv(cli, buf, sizeof(buf), 0);
  12060. // Response with Content-Length larger than default 100MB limit
  12061. auto content_length = std::to_string(DATA_SIZE);
  12062. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12063. "Content-Length: " +
  12064. content_length +
  12065. "\r\n"
  12066. "Connection: close\r\n"
  12067. "\r\n";
  12068. ::send(cli,
  12069. #ifdef _WIN32
  12070. static_cast<const char *>(response_header.c_str()),
  12071. static_cast<int>(response_header.size()),
  12072. #else
  12073. response_header.c_str(), response_header.size(),
  12074. #endif
  12075. 0);
  12076. std::string chunk(64 * 1024, 'A');
  12077. size_t total_sent = 0;
  12078. while (total_sent < DATA_SIZE) {
  12079. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12080. auto sent = ::send(cli,
  12081. #ifdef _WIN32
  12082. static_cast<const char *>(chunk.c_str()),
  12083. static_cast<int>(to_send),
  12084. #else
  12085. chunk.c_str(), to_send,
  12086. #endif
  12087. 0);
  12088. if (sent <= 0) break;
  12089. total_sent += static_cast<size_t>(sent);
  12090. }
  12091. detail::close_socket(cli);
  12092. }
  12093. detail::close_socket(srv);
  12094. });
  12095. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12096. size_t total_received = 0;
  12097. {
  12098. Client cli("127.0.0.1", PORT + 2);
  12099. cli.set_read_timeout(10, 0);
  12100. // Do NOT call set_payload_max_length — use the default 100MB limit
  12101. auto res =
  12102. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12103. total_received += data_length;
  12104. return true;
  12105. });
  12106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12107. EXPECT_EQ(StatusCode::OK_200, res->status);
  12108. }
  12109. server_thread.join();
  12110. EXPECT_EQ(total_received, DATA_SIZE)
  12111. << "With content_receiver, the client should read all " << DATA_SIZE
  12112. << " bytes despite the default 100MB payload_max_length, but only read "
  12113. << total_received << " bytes.";
  12114. }
  12115. // Verify that an explicit set_payload_max_length smaller than the response is
  12116. // enforced even when a content_receiver is used.
  12117. TEST(ClientVulnerabilityTest,
  12118. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12119. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12120. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12121. #ifndef _WIN32
  12122. signal(SIGPIPE, SIG_IGN);
  12123. #endif
  12124. auto server_thread = std::thread([] {
  12125. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12126. default_socket_options(srv);
  12127. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12128. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12129. sockaddr_in addr{};
  12130. addr.sin_family = AF_INET;
  12131. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12132. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12133. int opt = 1;
  12134. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12135. #ifdef _WIN32
  12136. reinterpret_cast<const char *>(&opt),
  12137. #else
  12138. &opt,
  12139. #endif
  12140. sizeof(opt));
  12141. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12142. ::listen(srv, 1);
  12143. sockaddr_in cli_addr{};
  12144. socklen_t cli_len = sizeof(cli_addr);
  12145. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12146. if (cli != INVALID_SOCKET) {
  12147. char buf[4096];
  12148. ::recv(cli, buf, sizeof(buf), 0);
  12149. auto content_length = std::to_string(DATA_SIZE);
  12150. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12151. "Content-Length: " +
  12152. content_length +
  12153. "\r\n"
  12154. "Connection: close\r\n"
  12155. "\r\n";
  12156. ::send(cli,
  12157. #ifdef _WIN32
  12158. static_cast<const char *>(response_header.c_str()),
  12159. static_cast<int>(response_header.size()),
  12160. #else
  12161. response_header.c_str(), response_header.size(),
  12162. #endif
  12163. 0);
  12164. std::string chunk(64 * 1024, 'A');
  12165. size_t total_sent = 0;
  12166. while (total_sent < DATA_SIZE) {
  12167. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12168. auto sent = ::send(cli,
  12169. #ifdef _WIN32
  12170. static_cast<const char *>(chunk.c_str()),
  12171. static_cast<int>(to_send),
  12172. #else
  12173. chunk.c_str(), to_send,
  12174. #endif
  12175. 0);
  12176. if (sent <= 0) break;
  12177. total_sent += static_cast<size_t>(sent);
  12178. }
  12179. detail::close_socket(cli);
  12180. }
  12181. detail::close_socket(srv);
  12182. });
  12183. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12184. size_t total_received = 0;
  12185. {
  12186. Client cli("127.0.0.1", PORT + 2);
  12187. cli.set_read_timeout(10, 0);
  12188. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  12189. auto res =
  12190. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12191. total_received += data_length;
  12192. return true;
  12193. });
  12194. // Should fail because 200MB exceeds the explicit 150MB limit
  12195. EXPECT_FALSE(res);
  12196. }
  12197. server_thread.join();
  12198. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  12199. << "Client with content_receiver should respect the explicit "
  12200. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  12201. << total_received << " bytes.";
  12202. }
  12203. // Verify that an explicit set_payload_max_length larger than the response
  12204. // allows the content_receiver to read all data successfully.
  12205. TEST(ClientVulnerabilityTest,
  12206. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  12207. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12208. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  12209. #ifndef _WIN32
  12210. signal(SIGPIPE, SIG_IGN);
  12211. #endif
  12212. auto server_thread = std::thread([] {
  12213. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12214. default_socket_options(srv);
  12215. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12216. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12217. sockaddr_in addr{};
  12218. addr.sin_family = AF_INET;
  12219. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12220. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12221. int opt = 1;
  12222. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12223. #ifdef _WIN32
  12224. reinterpret_cast<const char *>(&opt),
  12225. #else
  12226. &opt,
  12227. #endif
  12228. sizeof(opt));
  12229. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12230. ::listen(srv, 1);
  12231. sockaddr_in cli_addr{};
  12232. socklen_t cli_len = sizeof(cli_addr);
  12233. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12234. if (cli != INVALID_SOCKET) {
  12235. char buf[4096];
  12236. ::recv(cli, buf, sizeof(buf), 0);
  12237. auto content_length = std::to_string(DATA_SIZE);
  12238. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12239. "Content-Length: " +
  12240. content_length +
  12241. "\r\n"
  12242. "Connection: close\r\n"
  12243. "\r\n";
  12244. ::send(cli,
  12245. #ifdef _WIN32
  12246. static_cast<const char *>(response_header.c_str()),
  12247. static_cast<int>(response_header.size()),
  12248. #else
  12249. response_header.c_str(), response_header.size(),
  12250. #endif
  12251. 0);
  12252. std::string chunk(64 * 1024, 'A');
  12253. size_t total_sent = 0;
  12254. while (total_sent < DATA_SIZE) {
  12255. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12256. auto sent = ::send(cli,
  12257. #ifdef _WIN32
  12258. static_cast<const char *>(chunk.c_str()),
  12259. static_cast<int>(to_send),
  12260. #else
  12261. chunk.c_str(), to_send,
  12262. #endif
  12263. 0);
  12264. if (sent <= 0) break;
  12265. total_sent += static_cast<size_t>(sent);
  12266. }
  12267. #ifdef _WIN32
  12268. ::shutdown(cli, SD_SEND);
  12269. #else
  12270. ::shutdown(cli, SHUT_WR);
  12271. #endif
  12272. char drain[1024];
  12273. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12274. detail::close_socket(cli);
  12275. }
  12276. detail::close_socket(srv);
  12277. });
  12278. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12279. size_t total_received = 0;
  12280. {
  12281. Client cli("127.0.0.1", PORT + 2);
  12282. cli.set_read_timeout(10, 0);
  12283. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  12284. auto res =
  12285. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12286. total_received += data_length;
  12287. return true;
  12288. });
  12289. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12290. EXPECT_EQ(StatusCode::OK_200, res->status);
  12291. }
  12292. server_thread.join();
  12293. EXPECT_EQ(total_received, DATA_SIZE)
  12294. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  12295. << " bytes (larger than " << DATA_SIZE
  12296. << " bytes response), content_receiver should read all data, but only "
  12297. "read "
  12298. << total_received << " bytes.";
  12299. }
  12300. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  12301. // Regression test for "zip bomb" attack on the client side: a malicious server
  12302. // sends a small gzip-compressed response that decompresses to a huge payload.
  12303. // The client must enforce payload_max_length on the decompressed size.
  12304. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  12305. constexpr size_t DECOMPRESSED_SIZE =
  12306. 10 * 1024 * 1024; // 10MB after decompression
  12307. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12308. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  12309. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  12310. std::string compressed;
  12311. {
  12312. httplib::detail::gzip_compressor compressor;
  12313. bool ok =
  12314. compressor.compress(uncompressed.data(), uncompressed.size(),
  12315. /*last=*/true, [&](const char *buf, size_t len) {
  12316. compressed.append(buf, len);
  12317. return true;
  12318. });
  12319. ASSERT_TRUE(ok);
  12320. }
  12321. // Sanity: compressed data should be much smaller than the decompressed size
  12322. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  12323. #ifndef _WIN32
  12324. signal(SIGPIPE, SIG_IGN);
  12325. #endif
  12326. // Set up the listening socket in the main thread so the server is guaranteed
  12327. // to be ready before the client connects (eliminates race condition).
  12328. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12329. default_socket_options(srv);
  12330. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12331. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12332. sockaddr_in addr{};
  12333. addr.sin_family = AF_INET;
  12334. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  12335. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12336. int opt = 1;
  12337. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12338. #ifdef _WIN32
  12339. reinterpret_cast<const char *>(&opt),
  12340. #else
  12341. &opt,
  12342. #endif
  12343. sizeof(opt));
  12344. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  12345. ASSERT_EQ(0, ::listen(srv, 1));
  12346. auto server_thread = std::thread([&compressed, srv] {
  12347. sockaddr_in cli_addr{};
  12348. socklen_t cli_len = sizeof(cli_addr);
  12349. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12350. if (cli != INVALID_SOCKET) {
  12351. // Read the full HTTP request (until \r\n\r\n)
  12352. char buf[4096];
  12353. size_t total = 0;
  12354. while (total < sizeof(buf)) {
  12355. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  12356. if (n <= 0) break;
  12357. total += static_cast<size_t>(n);
  12358. // Check for end of headers
  12359. if (total >= 4) {
  12360. std::string req(buf, total);
  12361. if (req.find("\r\n\r\n") != std::string::npos) break;
  12362. }
  12363. }
  12364. // Malicious response: gzip-compressed body, no Content-Length
  12365. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12366. "Content-Encoding: gzip\r\n"
  12367. "Connection: close\r\n"
  12368. "\r\n";
  12369. ::send(cli,
  12370. #ifdef _WIN32
  12371. static_cast<const char *>(response_header.c_str()),
  12372. static_cast<int>(response_header.size()),
  12373. #else
  12374. response_header.c_str(), response_header.size(),
  12375. #endif
  12376. 0);
  12377. // Send the compressed payload (small on the wire, huge when decompressed)
  12378. size_t total_sent = 0;
  12379. while (total_sent < compressed.size()) {
  12380. auto to_send = std::min(compressed.size() - total_sent,
  12381. static_cast<size_t>(64 * 1024));
  12382. auto sent =
  12383. ::send(cli,
  12384. #ifdef _WIN32
  12385. static_cast<const char *>(compressed.c_str() + total_sent),
  12386. static_cast<int>(to_send),
  12387. #else
  12388. compressed.c_str() + total_sent, to_send,
  12389. #endif
  12390. 0);
  12391. if (sent <= 0) break;
  12392. total_sent += static_cast<size_t>(sent);
  12393. }
  12394. detail::close_socket(cli);
  12395. }
  12396. });
  12397. auto se = detail::scope_exit([&] {
  12398. detail::close_socket(srv);
  12399. server_thread.join();
  12400. });
  12401. size_t total_decompressed = 0;
  12402. {
  12403. Client cli("127.0.0.1", PORT + 3);
  12404. cli.set_read_timeout(5, 0);
  12405. cli.set_decompress(true);
  12406. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12407. auto stream = cli.open_stream("GET", "/zipbomb");
  12408. ASSERT_TRUE(stream.is_valid());
  12409. char buffer[64 * 1024];
  12410. ssize_t n;
  12411. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12412. total_decompressed += static_cast<size_t>(n);
  12413. }
  12414. }
  12415. // The decompressed size must be capped by payload_max_length. Without
  12416. // protection, the client would decompress the full 10MB from a tiny
  12417. // compressed payload, enabling a zip bomb DoS attack.
  12418. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  12419. << "Client decompressed " << total_decompressed
  12420. << " bytes from a gzip response. The decompressed size should be "
  12421. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  12422. }
  12423. #endif
  12424. TEST(HostAndPortPropertiesTest, NoSSL) {
  12425. httplib::Client cli("www.google.com", 1234);
  12426. ASSERT_EQ("www.google.com", cli.host());
  12427. ASSERT_EQ(1234, cli.port());
  12428. }
  12429. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  12430. httplib::Client cli("www.google.com:1234");
  12431. ASSERT_EQ("www.google.com", cli.host());
  12432. ASSERT_EQ(1234, cli.port());
  12433. }
  12434. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  12435. // Port number that overflows int — should not crash, client becomes invalid
  12436. httplib::Client cli("http://www.google.com:99999999999999999999");
  12437. ASSERT_FALSE(cli.is_valid());
  12438. }
  12439. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  12440. // Port 99999 exceeds valid range (1-65535) — should not crash
  12441. httplib::Client cli("http://www.google.com:99999");
  12442. ASSERT_FALSE(cli.is_valid());
  12443. auto res = cli.Get("/");
  12444. EXPECT_FALSE(res);
  12445. EXPECT_EQ(Error::Connection, res.error());
  12446. }
  12447. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  12448. httplib::Client cli("http://www.google.com:80abc");
  12449. ASSERT_FALSE(cli.is_valid());
  12450. }
  12451. #ifdef CPPHTTPLIB_SSL_ENABLED
  12452. TEST(HostAndPortPropertiesTest, SSL) {
  12453. httplib::SSLClient cli("www.google.com");
  12454. ASSERT_EQ("www.google.com", cli.host());
  12455. ASSERT_EQ(443, cli.port());
  12456. }
  12457. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  12458. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  12459. std::string cert;
  12460. read_file(CA_CERT_FILE, cert);
  12461. httplib::SSLClient httplib_client("www.google.com");
  12462. // Load CA store first time
  12463. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12464. // Load CA store second time (update)
  12465. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  12466. // Verify client is still valid and can make connections
  12467. httplib_client.enable_server_certificate_verification(true);
  12468. auto res = httplib_client.Get("/");
  12469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12470. // Google may return 200 or 301 depending on various factors
  12471. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  12472. res->status == StatusCode::MovedPermanently_301);
  12473. }
  12474. TEST(SSLClientTest, ServerNameIndication_Online) {
  12475. auto host = "httpbingo.org";
  12476. auto path = std::string{"/get"};
  12477. SSLClient cli(host, 443);
  12478. auto res = cli.Get(path);
  12479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12480. ASSERT_EQ(StatusCode::OK_200, res->status);
  12481. }
  12482. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  12483. // Use a site that will cause SSL verification failure due to self-signed cert
  12484. SSLClient cli("self-signed.badssl.com", 443);
  12485. cli.enable_server_certificate_verification(true);
  12486. auto res = cli.Get("/");
  12487. ASSERT_TRUE(!res);
  12488. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12489. // Verify backend error is captured for SSLServerVerification
  12490. // This occurs when certificate verification fails
  12491. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  12492. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  12493. EXPECT_NE(0UL, res.ssl_backend_error());
  12494. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12495. // For OpenSSL, ssl_error is 0 for verification errors
  12496. EXPECT_EQ(0, res.ssl_error());
  12497. #if !defined(_WIN32) || \
  12498. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12499. // On non-Windows or when Windows Schannel is disabled, the error comes
  12500. // from OpenSSL's verification
  12501. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  12502. res.ssl_backend_error());
  12503. #endif
  12504. #endif
  12505. }
  12506. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  12507. // Use a site where hostname doesn't match the certificate
  12508. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  12509. SSLClient cli("wrong.host.badssl.com", 443);
  12510. cli.enable_server_certificate_verification(true);
  12511. cli.enable_server_hostname_verification(true);
  12512. auto res = cli.Get("/");
  12513. ASSERT_TRUE(!res);
  12514. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  12515. // Verify backend error is captured for hostname verification failure
  12516. EXPECT_NE(0UL, res.ssl_backend_error());
  12517. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12518. // For OpenSSL, ssl_error is 0 for verification errors
  12519. EXPECT_EQ(0, res.ssl_error());
  12520. #if !defined(_WIN32) || \
  12521. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12522. // On non-Windows or when Windows Schannel is disabled, the error comes
  12523. // from OpenSSL's hostname verification
  12524. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  12525. res.ssl_backend_error());
  12526. #endif
  12527. #endif
  12528. }
  12529. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  12530. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  12531. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  12532. SSLClient cli("www.google.com", 443);
  12533. cli.enable_server_certificate_verification(true);
  12534. auto res = cli.Get("/");
  12535. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12536. }
  12537. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  12538. SSLClient cli("www.google.com", 443);
  12539. cli.enable_server_certificate_verification(true);
  12540. cli.enable_windows_certificate_verification(false);
  12541. auto res = cli.Get("/");
  12542. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  12543. }
  12544. // The server sends an intermediate cross-signed by a root Windows trusts,
  12545. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  12546. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  12547. SSLClient cli("accounts.spotify.com", 443);
  12548. auto res = cli.Get("/");
  12549. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  12550. << " ssl_backend_error=" << res.ssl_backend_error();
  12551. }
  12552. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  12553. // policy status, which no backend reports for a self-signed certificate.
  12554. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  12555. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12556. ASSERT_TRUE(svr.is_valid());
  12557. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12558. auto se = detail::scope_exit([&] {
  12559. svr.stop();
  12560. t.join();
  12561. ASSERT_FALSE(svr.is_running());
  12562. });
  12563. svr.wait_until_ready();
  12564. SSLClient cli("127.0.0.1", PORT);
  12565. cli.set_connection_timeout(30);
  12566. auto res = cli.Get("/");
  12567. ASSERT_FALSE(res);
  12568. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12569. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  12570. }
  12571. #endif
  12572. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  12573. Client cli("https://google.com");
  12574. auto res = cli.Get("/");
  12575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12576. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12577. }
  12578. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  12579. SSLClient cli("google.com");
  12580. cli.set_ca_cert_path(CA_CERT_FILE);
  12581. auto res = cli.Get("/");
  12582. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12583. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12584. }
  12585. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  12586. SSLClient cli("google.com");
  12587. cli.enable_server_certificate_verification(true);
  12588. cli.set_ca_cert_path("hello");
  12589. auto res = cli.Get("/");
  12590. ASSERT_TRUE(!res);
  12591. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  12592. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  12593. // should be set
  12594. EXPECT_EQ(0, res.ssl_error());
  12595. // Verify backend error is captured for SSLLoadingCerts
  12596. // This error occurs when loading CA certificates fails
  12597. EXPECT_NE(0UL, res.ssl_backend_error());
  12598. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  12599. // OpenSSL specific error codes:
  12600. // > openssl errstr 0x80000002
  12601. // error:80000002:system library::No such file or directory
  12602. // > openssl errstr 0xA000126
  12603. // error:0A000126:SSL routines::unexpected eof while reading
  12604. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  12605. res.ssl_backend_error() == 0xA000126);
  12606. #endif
  12607. }
  12608. TEST(SSLClientTest, ServerCertificateVerification4) {
  12609. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12610. ASSERT_TRUE(svr.is_valid());
  12611. svr.Get("/test", [&](const Request &, Response &res) {
  12612. res.set_content("test", "text/plain");
  12613. svr.stop();
  12614. ASSERT_TRUE(true);
  12615. });
  12616. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12617. auto se = detail::scope_exit([&] {
  12618. t.join();
  12619. ASSERT_FALSE(svr.is_running());
  12620. });
  12621. svr.wait_until_ready();
  12622. SSLClient cli("127.0.0.1", PORT);
  12623. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12624. cli.enable_server_certificate_verification(true);
  12625. cli.set_connection_timeout(30);
  12626. auto res = cli.Get("/test");
  12627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12628. ASSERT_EQ(StatusCode::OK_200, res->status);
  12629. }
  12630. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  12631. std::string cert;
  12632. read_file(CA_CERT_FILE, cert);
  12633. SSLClient cli("google.com");
  12634. cli.load_ca_cert_store(cert.data(), cert.size());
  12635. const auto res = cli.Get("/");
  12636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12637. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12638. }
  12639. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  12640. // clang-format off
  12641. static constexpr char cert[] =
  12642. "GlobalSign Root CA\n"
  12643. "==================\n"
  12644. "-----BEGIN CERTIFICATE-----\n"
  12645. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  12646. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  12647. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  12648. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  12649. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  12650. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  12651. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  12652. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  12653. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  12654. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  12655. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  12656. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  12657. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  12658. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  12659. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  12660. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  12661. "-----END CERTIFICATE-----\n";
  12662. // clang-format on
  12663. SSLClient cli("google.com");
  12664. cli.load_ca_cert_store(cert, sizeof(cert));
  12665. const auto res = cli.Get("/");
  12666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12667. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12668. }
  12669. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  12670. SSLClient cli("www.youtube.com");
  12671. cli.set_ca_cert_path(CA_CERT_FILE);
  12672. cli.enable_server_certificate_verification(true);
  12673. cli.set_follow_location(true);
  12674. auto res = cli.Get("/");
  12675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12676. ASSERT_EQ(StatusCode::OK_200, res->status);
  12677. }
  12678. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  12679. SSLClient cli("wWw.YouTube.Com");
  12680. cli.set_ca_cert_path(CA_CERT_FILE);
  12681. cli.enable_server_certificate_verification(true);
  12682. cli.enable_server_hostname_verification(true);
  12683. cli.set_follow_location(true);
  12684. auto res = cli.Get("/");
  12685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12686. ASSERT_EQ(StatusCode::OK_200, res->status);
  12687. }
  12688. TEST(SSLClientTest, HostNameMatchCase_Online) {
  12689. SSLClient cli("gOoGlE.COm");
  12690. cli.enable_server_certificate_verification(true);
  12691. cli.enable_server_hostname_verification(true);
  12692. cli.set_follow_location(true);
  12693. auto res = cli.Get("/");
  12694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12695. ASSERT_EQ(StatusCode::OK_200, res->status);
  12696. }
  12697. TEST(SSLClientTest, Issue2004_Online) {
  12698. Client client("https://google.com");
  12699. client.set_follow_location(true);
  12700. auto res = client.Get("/");
  12701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12702. ASSERT_EQ(StatusCode::OK_200, res->status);
  12703. auto body = res->body;
  12704. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  12705. }
  12706. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  12707. // Create SSLClient with invalid cert/key to make is_valid() return false
  12708. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  12709. "nonexistent_key.pem");
  12710. // is_valid() should be false due to cert loading failure
  12711. ASSERT_FALSE(cli.is_valid());
  12712. auto res = cli.Get("/");
  12713. ASSERT_FALSE(res);
  12714. EXPECT_EQ(Error::SSLConnection, res.error());
  12715. }
  12716. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  12717. // Test for Issue #2251: SSL error not properly reported when client cert
  12718. // and key paths are swapped or mismatched
  12719. // This simulates the scenario where user accidentally swaps the cert and key
  12720. // files
  12721. // Using client cert file as private key and vice versa (completely wrong)
  12722. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  12723. // Should fail validation due to cert/key mismatch
  12724. ASSERT_FALSE(cli.is_valid());
  12725. // Attempt to make a request should fail with proper error
  12726. auto res = cli.Get("/");
  12727. ASSERT_FALSE(res);
  12728. EXPECT_EQ(Error::SSLConnection, res.error());
  12729. // SSL error should be recorded in the Result object (this is the key fix for
  12730. // Issue #2251)
  12731. auto backend_error = res.ssl_backend_error();
  12732. EXPECT_NE(0u, backend_error);
  12733. }
  12734. // Tests cert/key mismatch detection at the TLS context level
  12735. TEST(TlsApiTest, ClientCertKeyMismatch) {
  12736. // Test that using mismatched cert/key causes connection failure.
  12737. // We verify this at the SSLClient level rather than through internal
  12738. // TLS API functions.
  12739. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  12740. cli.enable_server_certificate_verification(false);
  12741. cli.set_connection_timeout(2);
  12742. // The mismatch should cause a connection or handshake error
  12743. auto res = cli.Get("/test");
  12744. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  12745. // Either way, the request should fail
  12746. EXPECT_FALSE(res);
  12747. }
  12748. #endif
  12749. #if 0
  12750. TEST(SSLClientTest, SetInterfaceWithINET6) {
  12751. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  12752. ASSERT_TRUE(cli != nullptr);
  12753. cli->set_address_family(AF_INET6);
  12754. cli->set_interface("en0");
  12755. auto res = cli->Get("/get");
  12756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12757. ASSERT_EQ(StatusCode::OK_200, res->status);
  12758. }
  12759. #endif
  12760. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  12761. #ifdef CPPHTTPLIB_SSL_ENABLED
  12762. void ClientCertPresent(
  12763. const std::string &client_cert_file,
  12764. const std::string &client_private_key_file,
  12765. const std::string &client_encrypted_private_key_pass = std::string()) {
  12766. using namespace httplib::tls;
  12767. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12768. CLIENT_CA_CERT_DIR);
  12769. ASSERT_TRUE(svr.is_valid());
  12770. svr.Get("/test", [&](const Request &req, Response &res) {
  12771. res.set_content("test", "text/plain");
  12772. auto cert = req.peer_cert();
  12773. ASSERT_TRUE(static_cast<bool>(cert));
  12774. std::string common_name = cert.subject_cn();
  12775. EXPECT_EQ("Common Name", common_name);
  12776. });
  12777. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12778. auto se = detail::scope_exit([&] {
  12779. svr.stop();
  12780. t.join();
  12781. ASSERT_FALSE(svr.is_running());
  12782. });
  12783. svr.wait_until_ready();
  12784. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  12785. client_encrypted_private_key_pass);
  12786. cli.enable_server_certificate_verification(false);
  12787. cli.set_connection_timeout(30);
  12788. auto res = cli.Get("/test");
  12789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12790. ASSERT_EQ(StatusCode::OK_200, res->status);
  12791. }
  12792. TEST(SSLClientServerTest, ClientCertPresent) {
  12793. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12794. }
  12795. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  12796. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12797. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12798. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12799. }
  12800. // PEM memory-based constructor tests (works with all TLS backends)
  12801. void PemMemoryClientCertPresent(
  12802. const std::string &client_cert_file,
  12803. const std::string &client_private_key_file,
  12804. const std::string &client_encrypted_private_key_pass = std::string()) {
  12805. // Read PEM files into memory
  12806. std::string server_cert_pem, server_key_pem;
  12807. std::string client_ca_pem;
  12808. std::string client_cert_pem, client_key_pem;
  12809. read_file(SERVER_CERT_FILE, server_cert_pem);
  12810. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12811. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12812. read_file(client_cert_file, client_cert_pem);
  12813. read_file(client_private_key_file, client_key_pem);
  12814. // Create server with PEM memory
  12815. SSLServer::PemMemory server_pem = {
  12816. server_cert_pem.c_str(),
  12817. server_cert_pem.size(),
  12818. server_key_pem.c_str(),
  12819. server_key_pem.size(),
  12820. client_ca_pem.c_str(),
  12821. client_ca_pem.size(),
  12822. nullptr // no password for server key
  12823. };
  12824. SSLServer svr(server_pem);
  12825. ASSERT_TRUE(svr.is_valid());
  12826. svr.Get("/test", [&](const Request &, Response &res) {
  12827. res.set_content("test", "text/plain");
  12828. });
  12829. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12830. auto se = detail::scope_exit([&] {
  12831. svr.stop();
  12832. t.join();
  12833. ASSERT_FALSE(svr.is_running());
  12834. });
  12835. svr.wait_until_ready();
  12836. // Create client with PEM memory
  12837. const char *password = client_encrypted_private_key_pass.empty()
  12838. ? nullptr
  12839. : client_encrypted_private_key_pass.c_str();
  12840. SSLClient::PemMemory client_pem = {
  12841. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  12842. client_key_pem.size(), password};
  12843. SSLClient cli(HOST, PORT, client_pem);
  12844. cli.enable_server_certificate_verification(false);
  12845. cli.set_connection_timeout(30);
  12846. auto res = cli.Get("/test");
  12847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12848. ASSERT_EQ(StatusCode::OK_200, res->status);
  12849. }
  12850. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  12851. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12852. }
  12853. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  12854. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  12855. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  12856. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  12857. }
  12858. TEST(SSLClientServerTest, ClientCertMissing) {
  12859. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12860. CLIENT_CA_CERT_DIR);
  12861. ASSERT_TRUE(svr.is_valid());
  12862. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  12863. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12864. auto se = detail::scope_exit([&] {
  12865. svr.stop();
  12866. t.join();
  12867. ASSERT_FALSE(svr.is_running());
  12868. });
  12869. svr.wait_until_ready();
  12870. SSLClient cli(HOST, PORT);
  12871. cli.set_connection_timeout(30);
  12872. // cert.pem does not match HOST. Skip the hostname check, which runs before
  12873. // the chain check on Windows, so the result does not depend on the order.
  12874. cli.enable_server_hostname_verification(false);
  12875. auto res = cli.Get("/test");
  12876. ASSERT_TRUE(!res);
  12877. // When client cert is missing and server requires it, connection fails
  12878. // Error type depends on backend implementation
  12879. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12880. res.error() == Error::SSLConnection);
  12881. // Verify backend error is captured
  12882. // Note: This test may have different error codes depending on the exact
  12883. // verification failure
  12884. EXPECT_NE(0UL, res.ssl_backend_error());
  12885. }
  12886. TEST(SSLClientServerTest, TrustDirOptional) {
  12887. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12888. ASSERT_TRUE(svr.is_valid());
  12889. svr.Get("/test", [&](const Request &, Response &res) {
  12890. res.set_content("test", "text/plain");
  12891. });
  12892. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12893. auto se = detail::scope_exit([&] {
  12894. svr.stop();
  12895. t.join();
  12896. ASSERT_FALSE(svr.is_running());
  12897. });
  12898. svr.wait_until_ready();
  12899. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12900. cli.enable_server_certificate_verification(false);
  12901. cli.set_connection_timeout(30);
  12902. auto res = cli.Get("/test");
  12903. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12904. ASSERT_EQ(StatusCode::OK_200, res->status);
  12905. }
  12906. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12907. class NoListenSSLServer : public SSLServer {
  12908. public:
  12909. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12910. const char *client_ca_cert_file_path,
  12911. const char *client_ca_cert_dir_path = nullptr)
  12912. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12913. client_ca_cert_dir_path),
  12914. stop_(false) {}
  12915. std::atomic_bool stop_;
  12916. private:
  12917. bool process_and_close_socket(socket_t /*sock*/) override {
  12918. // Don't create SSL context
  12919. while (!stop_.load()) {
  12920. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12921. }
  12922. return true;
  12923. }
  12924. };
  12925. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12926. CLIENT_CA_CERT_FILE);
  12927. ASSERT_TRUE(svr.is_valid());
  12928. svr.Get("/test", [&](const Request &, Response &res) {
  12929. res.set_content("test", "text/plain");
  12930. });
  12931. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12932. auto se = detail::scope_exit([&] {
  12933. svr.stop_ = true;
  12934. svr.stop();
  12935. t.join();
  12936. ASSERT_FALSE(svr.is_running());
  12937. });
  12938. svr.wait_until_ready();
  12939. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12940. cli.enable_server_certificate_verification(false);
  12941. cli.set_connection_timeout(1);
  12942. auto res = cli.Get("/test");
  12943. ASSERT_TRUE(!res);
  12944. EXPECT_EQ(Error::SSLConnection, res.error());
  12945. // Timeout results in WantRead error code (maps to backend-specific value)
  12946. EXPECT_NE(0, res.ssl_error());
  12947. }
  12948. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12949. // Test SSLServer with client certificate verification using the standard
  12950. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12952. CLIENT_CA_CERT_DIR);
  12953. ASSERT_TRUE(svr.is_valid());
  12954. svr.Get("/test", [&](const Request &req, Response &res) {
  12955. res.set_content("test", "text/plain");
  12956. auto cert = req.peer_cert();
  12957. ASSERT_TRUE(static_cast<bool>(cert));
  12958. auto common_name = cert.subject_cn();
  12959. EXPECT_EQ("Common Name", common_name);
  12960. });
  12961. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12962. auto se = detail::scope_exit([&] {
  12963. svr.stop();
  12964. t.join();
  12965. ASSERT_FALSE(svr.is_running());
  12966. });
  12967. svr.wait_until_ready();
  12968. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12969. cli.enable_server_certificate_verification(false);
  12970. cli.set_connection_timeout(30);
  12971. auto res = cli.Get("/test");
  12972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12973. ASSERT_EQ(StatusCode::OK_200, res->status);
  12974. }
  12975. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12976. // Verifies that wildcard matching and exact matching work consistently
  12977. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12978. using namespace httplib::tls;
  12979. // We need a running server to test against
  12980. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12981. ASSERT_TRUE(svr.is_valid());
  12982. svr.Get("/test", [](const Request &, Response &res) {
  12983. res.set_content("ok", "text/plain");
  12984. });
  12985. thread t([&]() { svr.listen(HOST, PORT); });
  12986. auto se = detail::scope_exit([&] {
  12987. svr.stop();
  12988. t.join();
  12989. });
  12990. svr.wait_until_ready();
  12991. bool verify_callback_called = false;
  12992. bool verify_result_wrong = false;
  12993. SSLClient cli(HOST, PORT);
  12994. cli.enable_server_certificate_verification(true);
  12995. cli.set_ca_cert_path(CA_CERT_FILE);
  12996. cli.set_connection_timeout(5);
  12997. // Note: Test certificate has CN="Common Name", not "localhost"
  12998. bool verify_result_cn = false;
  12999. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13000. verify_callback_called = true;
  13001. if (!ctx.cert) return false;
  13002. // Test 1: "Common Name" should match (our test server cert CN)
  13003. verify_result_cn = ctx.check_hostname("Common Name");
  13004. // Test 2: wrong hostname should not match
  13005. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  13006. return true; // Accept for the purpose of this test
  13007. });
  13008. auto res = cli.Get("/test");
  13009. // The request may succeed or fail depending on cert configuration
  13010. // but the callback should have been called
  13011. ASSERT_TRUE(verify_callback_called)
  13012. << "Verify callback should have been called";
  13013. // CN="Common Name" should match our test certificate
  13014. //
  13015. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  13016. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  13017. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  13018. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  13019. // <openssl/base.h>, which is included transitively when
  13020. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  13021. #if defined(OPENSSL_IS_BORINGSSL)
  13022. EXPECT_FALSE(verify_result_cn)
  13023. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  13024. #else
  13025. EXPECT_TRUE(verify_result_cn)
  13026. << "verify_hostname should match 'Common Name' (certificate CN)";
  13027. #endif
  13028. // Wrong hostname should not match
  13029. EXPECT_FALSE(verify_result_wrong)
  13030. << "verify_hostname should not match 'wronghost.example.com'";
  13031. }
  13032. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  13033. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  13034. // X509_check_ip behavior and must hold for every backend.
  13035. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  13036. using namespace httplib::tls;
  13037. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  13038. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  13039. ASSERT_TRUE(svr.is_valid());
  13040. svr.Get("/test", [](const Request &, Response &res) {
  13041. res.set_content("ok", "text/plain");
  13042. });
  13043. thread t([&]() { svr.listen(HOST, PORT); });
  13044. auto se = detail::scope_exit([&] {
  13045. svr.stop();
  13046. t.join();
  13047. });
  13048. svr.wait_until_ready();
  13049. bool verify_callback_called = false;
  13050. bool ip_matched_via_cn = true;
  13051. SSLClient cli(HOST, PORT);
  13052. cli.enable_server_certificate_verification(true);
  13053. cli.set_ca_cert_path(CA_CERT_FILE);
  13054. cli.set_connection_timeout(5);
  13055. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13056. verify_callback_called = true;
  13057. if (!ctx.cert) return false;
  13058. // The IP appears only in the CN, so it must NOT be accepted.
  13059. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  13060. return true; // Accept for the purpose of this test
  13061. });
  13062. cli.Get("/test");
  13063. ASSERT_TRUE(verify_callback_called)
  13064. << "Verify callback should have been called";
  13065. EXPECT_FALSE(ip_matched_via_cn)
  13066. << "An IP host must not be authenticated via the certificate CN";
  13067. }
  13068. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  13069. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  13070. using namespace httplib::tls;
  13071. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  13072. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  13073. ASSERT_TRUE(svr.is_valid());
  13074. svr.Get("/test", [](const Request &, Response &res) {
  13075. res.set_content("ok", "text/plain");
  13076. });
  13077. thread t([&]() { svr.listen(HOST, PORT); });
  13078. auto se = detail::scope_exit([&] {
  13079. svr.stop();
  13080. t.join();
  13081. });
  13082. svr.wait_until_ready();
  13083. bool verify_callback_called = false;
  13084. bool san_matched = false;
  13085. bool wrong_ipv6_matched = true;
  13086. bool cn_ipv6_matched = true;
  13087. SSLClient cli(HOST, PORT);
  13088. cli.enable_server_certificate_verification(true);
  13089. cli.set_ca_cert_path(CA_CERT_FILE);
  13090. cli.set_connection_timeout(5);
  13091. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13092. verify_callback_called = true;
  13093. if (!ctx.cert) return false;
  13094. // Matches the IPv6 iPAddress SAN.
  13095. san_matched = ctx.check_hostname("2001:db8::1");
  13096. // A different IPv6 address must not match.
  13097. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  13098. // "::1" lives only in the CN, so it must not be accepted.
  13099. cn_ipv6_matched = ctx.check_hostname("::1");
  13100. return true; // Accept for the purpose of this test
  13101. });
  13102. cli.Get("/test");
  13103. ASSERT_TRUE(verify_callback_called)
  13104. << "Verify callback should have been called";
  13105. EXPECT_TRUE(san_matched)
  13106. << "verify_hostname should match an IPv6 iPAddress SAN";
  13107. EXPECT_FALSE(wrong_ipv6_matched)
  13108. << "verify_hostname should not match a non-matching IPv6 address";
  13109. EXPECT_FALSE(cn_ipv6_matched)
  13110. << "An IPv6 host must not be authenticated via the certificate CN";
  13111. }
  13112. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  13113. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  13114. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  13115. using namespace httplib::tls;
  13116. // SANs: DNS:a.zz, IP:42.46.122.122
  13117. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13118. ASSERT_TRUE(svr.is_valid());
  13119. svr.Get("/test", [](const Request &, Response &res) {
  13120. res.set_content("ok", "text/plain");
  13121. });
  13122. auto port = svr.bind_to_any_port(HOST);
  13123. thread t([&]() { svr.listen_after_bind(); });
  13124. auto se = detail::scope_exit([&] {
  13125. svr.stop();
  13126. t.join();
  13127. });
  13128. svr.wait_until_ready();
  13129. bool verify_callback_called = false;
  13130. bool dns_san_matched = false;
  13131. bool ip_san_matched = false;
  13132. bool ip_matched_via_dns_san = true;
  13133. bool dns_matched_via_ip_san = true;
  13134. SSLClient cli(HOST, port);
  13135. cli.enable_server_certificate_verification(true);
  13136. cli.set_ca_cert_path(CA_CERT_FILE);
  13137. cli.set_connection_timeout(5);
  13138. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13139. verify_callback_called = true;
  13140. if (!ctx.cert) return false;
  13141. dns_san_matched = ctx.check_hostname("a.zz");
  13142. ip_san_matched = ctx.check_hostname("42.46.122.122");
  13143. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  13144. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  13145. return true; // Accept for the purpose of this test
  13146. });
  13147. cli.Get("/test");
  13148. ASSERT_TRUE(verify_callback_called)
  13149. << "Verify callback should have been called";
  13150. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  13151. EXPECT_TRUE(ip_san_matched)
  13152. << "verify_hostname should match an iPAddress SAN";
  13153. EXPECT_FALSE(ip_matched_via_dns_san)
  13154. << "An IP host must not be authenticated via a dNSName SAN";
  13155. EXPECT_FALSE(dns_matched_via_ip_san)
  13156. << "A DNS host must not be authenticated via an iPAddress SAN";
  13157. }
  13158. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  13159. // "www.*.example.test" names one host and not every host under example.test.
  13160. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  13161. using namespace httplib::tls;
  13162. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  13163. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  13164. ASSERT_TRUE(svr.is_valid());
  13165. svr.Get("/test", [](const Request &, Response &res) {
  13166. res.set_content("ok", "text/plain");
  13167. });
  13168. auto port = svr.bind_to_any_port(HOST);
  13169. thread t([&]() { svr.listen_after_bind(); });
  13170. auto se = detail::scope_exit([&] {
  13171. svr.stop();
  13172. t.join();
  13173. });
  13174. svr.wait_until_ready();
  13175. bool verify_callback_called = false;
  13176. bool leftmost_wildcard_matched = false;
  13177. bool wildcard_spanned_labels = true;
  13178. bool inner_wildcard_matched = true;
  13179. SSLClient cli(HOST, port);
  13180. cli.enable_server_certificate_verification(true);
  13181. cli.set_ca_cert_path(CA_CERT_FILE);
  13182. cli.set_connection_timeout(5);
  13183. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13184. verify_callback_called = true;
  13185. if (!ctx.cert) return false;
  13186. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  13187. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  13188. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  13189. return true; // Accept for the purpose of this test
  13190. });
  13191. cli.Get("/test");
  13192. ASSERT_TRUE(verify_callback_called)
  13193. << "Verify callback should have been called";
  13194. EXPECT_TRUE(leftmost_wildcard_matched)
  13195. << "A leftmost wildcard should match a single label";
  13196. EXPECT_FALSE(wildcard_spanned_labels)
  13197. << "A wildcard label must not match more than one label";
  13198. EXPECT_FALSE(inner_wildcard_matched)
  13199. << "A wildcard outside the leftmost label must not be honoured";
  13200. }
  13201. // sans() must report each SAN entry under its own type.
  13202. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  13203. using namespace httplib::tls;
  13204. // SANs: DNS:a.zz, IP:42.46.122.122
  13205. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  13206. ASSERT_TRUE(svr.is_valid());
  13207. svr.Get("/test", [](const Request &, Response &res) {
  13208. res.set_content("ok", "text/plain");
  13209. });
  13210. auto port = svr.bind_to_any_port(HOST);
  13211. thread t([&]() { svr.listen_after_bind(); });
  13212. auto se = detail::scope_exit([&] {
  13213. svr.stop();
  13214. t.join();
  13215. });
  13216. svr.wait_until_ready();
  13217. bool verify_callback_called = false;
  13218. std::vector<SanEntry> sans;
  13219. SSLClient cli(HOST, port);
  13220. cli.enable_server_certificate_verification(true);
  13221. cli.set_ca_cert_path(CA_CERT_FILE);
  13222. cli.set_connection_timeout(5);
  13223. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13224. verify_callback_called = true;
  13225. if (!ctx.cert) return false;
  13226. sans = ctx.sans();
  13227. return true; // Accept for the purpose of this test
  13228. });
  13229. cli.Get("/test");
  13230. ASSERT_TRUE(verify_callback_called)
  13231. << "Verify callback should have been called";
  13232. auto has_san = [&](SanType type, const std::string &value) {
  13233. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  13234. return san.type == type && san.value == value;
  13235. });
  13236. };
  13237. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  13238. << "sans() should report the dNSName SAN";
  13239. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  13240. << "sans() should report the iPAddress SAN";
  13241. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  13242. << "sans() must not report the dNSName SAN as an address";
  13243. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  13244. << "sans() must not report the iPAddress SAN as a DNS name";
  13245. }
  13246. #endif
  13247. // mbedTLS-specific callback constructor test
  13248. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  13249. #ifdef CPPHTTPLIB_SSL_ENABLED
  13250. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  13251. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13252. ASSERT_TRUE(svr.is_valid());
  13253. // Set up a handler to verify client certificate is present
  13254. bool client_cert_verified = false;
  13255. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  13256. // Verify that client certificate was provided
  13257. client_cert_verified = true;
  13258. res.set_content("success", "text/plain");
  13259. });
  13260. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13261. auto se = detail::scope_exit([&] {
  13262. svr.stop();
  13263. t.join();
  13264. ASSERT_FALSE(svr.is_running());
  13265. });
  13266. svr.wait_until_ready();
  13267. // Client with certificate
  13268. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13269. cli.enable_server_certificate_verification(false);
  13270. cli.set_connection_timeout(30);
  13271. auto res = cli.Get("/test");
  13272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13273. ASSERT_EQ(StatusCode::OK_200, res->status);
  13274. ASSERT_TRUE(client_cert_verified);
  13275. EXPECT_EQ("success", res->body);
  13276. }
  13277. #endif
  13278. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  13279. // backends
  13280. #ifdef CPPHTTPLIB_SSL_ENABLED
  13281. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  13282. using namespace httplib::tls;
  13283. // Test that when client CA cert file is provided,
  13284. // the server properly requests and validates client certificates
  13285. // Create a server with client authentication
  13286. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13287. ASSERT_TRUE(svr.is_valid());
  13288. bool handler_called = false;
  13289. svr.Get("/test", [&](const Request &req, Response &res) {
  13290. handler_called = true;
  13291. // Verify that a client certificate was provided
  13292. auto cert = req.peer_cert();
  13293. ASSERT_TRUE(static_cast<bool>(cert));
  13294. // Get the issuer name
  13295. std::string issuer_str = cert.issuer_name();
  13296. ASSERT_FALSE(issuer_str.empty());
  13297. // The client certificate should be issued by our test CA
  13298. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  13299. res.set_content("authenticated", "text/plain");
  13300. });
  13301. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13302. auto se = detail::scope_exit([&] {
  13303. svr.stop();
  13304. t.join();
  13305. ASSERT_FALSE(svr.is_running());
  13306. });
  13307. svr.wait_until_ready();
  13308. // Connect with a client certificate issued by the CA
  13309. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13310. cli.enable_server_certificate_verification(false);
  13311. cli.set_connection_timeout(30);
  13312. auto res = cli.Get("/test");
  13313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13314. ASSERT_EQ(StatusCode::OK_200, res->status);
  13315. ASSERT_TRUE(handler_called);
  13316. EXPECT_EQ("authenticated", res->body);
  13317. }
  13318. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  13319. using namespace httplib::tls;
  13320. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13321. ASSERT_TRUE(svr.is_valid());
  13322. svr.Get("/test", [](const Request &, Response &res) {
  13323. res.set_content("ok", "text/plain");
  13324. });
  13325. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13326. auto se = detail::scope_exit([&] {
  13327. svr.stop();
  13328. t.join();
  13329. });
  13330. svr.wait_until_ready();
  13331. SSLClient cli(HOST, PORT);
  13332. cli.enable_server_certificate_verification(false);
  13333. cli.set_connection_timeout(30);
  13334. bool cert_checked = false;
  13335. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13336. if (ctx.cert) {
  13337. auto sans = ctx.sans();
  13338. // Test certificate may or may not have SANs - just verify the API
  13339. // works If SANs exist, verify the types are valid
  13340. for (const auto &san : sans) {
  13341. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  13342. san.type == SanType::EMAIL || san.type == SanType::URI ||
  13343. san.type == SanType::OTHER);
  13344. EXPECT_FALSE(san.value.empty());
  13345. }
  13346. cert_checked = true;
  13347. }
  13348. return true;
  13349. });
  13350. auto res = cli.Get("/test");
  13351. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13352. EXPECT_TRUE(cert_checked);
  13353. }
  13354. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  13355. using namespace httplib::tls;
  13356. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13357. ASSERT_TRUE(svr.is_valid());
  13358. svr.Get("/test", [](const Request &, Response &res) {
  13359. res.set_content("ok", "text/plain");
  13360. });
  13361. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13362. auto se = detail::scope_exit([&] {
  13363. svr.stop();
  13364. t.join();
  13365. });
  13366. svr.wait_until_ready();
  13367. SSLClient cli(HOST, PORT);
  13368. cli.enable_server_certificate_verification(false);
  13369. cli.set_connection_timeout(30);
  13370. bool validity_checked = false;
  13371. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13372. if (ctx.cert) {
  13373. time_t not_before = 0, not_after = 0;
  13374. bool result = ctx.validity(not_before, not_after);
  13375. EXPECT_TRUE(result);
  13376. // Verify that not_before < now < not_after for a valid cert
  13377. time_t now = time(nullptr);
  13378. EXPECT_LT(not_before, now);
  13379. EXPECT_GT(not_after, now);
  13380. validity_checked = true;
  13381. }
  13382. return true;
  13383. });
  13384. auto res = cli.Get("/test");
  13385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13386. EXPECT_TRUE(validity_checked);
  13387. }
  13388. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  13389. using namespace httplib::tls;
  13390. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13391. ASSERT_TRUE(svr.is_valid());
  13392. svr.Get("/test", [](const Request &, Response &res) {
  13393. res.set_content("ok", "text/plain");
  13394. });
  13395. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13396. auto se = detail::scope_exit([&] {
  13397. svr.stop();
  13398. t.join();
  13399. });
  13400. svr.wait_until_ready();
  13401. SSLClient cli(HOST, PORT);
  13402. cli.enable_server_certificate_verification(false);
  13403. cli.set_connection_timeout(30);
  13404. bool serial_checked = false;
  13405. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13406. if (ctx.cert) {
  13407. std::string serial = ctx.serial();
  13408. EXPECT_FALSE(serial.empty());
  13409. // Serial should be a hex string
  13410. for (char c : serial) {
  13411. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  13412. (c >= 'a' && c <= 'f'));
  13413. }
  13414. serial_checked = true;
  13415. }
  13416. return true;
  13417. });
  13418. auto res = cli.Get("/test");
  13419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13420. EXPECT_TRUE(serial_checked);
  13421. }
  13422. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  13423. // Test 1: Valid CA file - no error should be recorded
  13424. {
  13425. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13426. CLIENT_CA_CERT_FILE);
  13427. ASSERT_TRUE(svr.is_valid());
  13428. // With valid setup, last_ssl_error should be 0
  13429. EXPECT_EQ(0, svr.ssl_last_error());
  13430. }
  13431. // Test 2: Invalid CA file content
  13432. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  13433. {
  13434. // Create a temporary file with completely invalid content
  13435. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  13436. {
  13437. std::ofstream ofs(temp_invalid_ca);
  13438. ofs << "This is not a certificate file at all\n";
  13439. ofs << "Just plain text content\n";
  13440. }
  13441. // Create server with invalid CA file
  13442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  13443. // Clean up temporary file
  13444. std::remove(temp_invalid_ca);
  13445. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  13446. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  13447. // Note: SSL_CTX_load_verify_locations typically fails first,
  13448. // but our error handling code path is still exercised
  13449. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  13450. }
  13451. }
  13452. TEST(VerifyCallbackTest, VerifyContextFields) {
  13453. using namespace httplib::tls;
  13454. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13455. ASSERT_TRUE(svr.is_valid());
  13456. svr.Get("/test", [](const Request &, Response &res) {
  13457. res.set_content("ok", "text/plain");
  13458. });
  13459. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13460. auto se = detail::scope_exit([&] {
  13461. svr.stop();
  13462. t.join();
  13463. });
  13464. svr.wait_until_ready();
  13465. SSLClient cli(HOST, PORT);
  13466. cli.enable_server_certificate_verification(false);
  13467. cli.set_connection_timeout(30);
  13468. int callback_count = 0;
  13469. bool saw_leaf_cert = false;
  13470. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  13471. if (ctx.cert) {
  13472. callback_count++;
  13473. // We should see at least one certificate (the leaf)
  13474. std::string cn = ctx.subject_cn();
  13475. if (!cn.empty()) { saw_leaf_cert = true; }
  13476. // Verify context fields are populated
  13477. EXPECT_NE(ctx.session, nullptr);
  13478. EXPECT_GE(ctx.depth, 0);
  13479. }
  13480. return true;
  13481. });
  13482. auto res = cli.Get("/test");
  13483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13484. EXPECT_GT(callback_count, 0);
  13485. EXPECT_TRUE(saw_leaf_cert);
  13486. }
  13487. // A verifier belongs to the client that set it, not to the thread that set it.
  13488. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  13489. using namespace httplib::tls;
  13490. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13491. ASSERT_TRUE(svr.is_valid());
  13492. svr.Get("/test", [](const Request &, Response &res) {
  13493. res.set_content("ok", "text/plain");
  13494. });
  13495. auto port = svr.bind_to_any_port(HOST);
  13496. thread t([&]() { svr.listen_after_bind(); });
  13497. auto se = detail::scope_exit([&] {
  13498. svr.stop();
  13499. t.join();
  13500. });
  13501. svr.wait_until_ready();
  13502. auto rejecting_calls = 0;
  13503. SSLClient rejecting(HOST, port);
  13504. rejecting.enable_server_certificate_verification(false);
  13505. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  13506. rejecting_calls++;
  13507. return false;
  13508. });
  13509. auto accepting_calls = 0;
  13510. SSLClient accepting(HOST, port);
  13511. accepting.enable_server_certificate_verification(false);
  13512. // Set on another thread than the requests below.
  13513. thread([&]() {
  13514. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  13515. accepting_calls++;
  13516. return true;
  13517. });
  13518. }).join();
  13519. // Requested on another thread than the verifier was set on.
  13520. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  13521. EXPECT_GT(rejecting_calls, 0);
  13522. auto res = accepting.Get("/test");
  13523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13524. EXPECT_GT(accepting_calls, 0);
  13525. }
  13526. // VerifyContext::session is the same handle the other tls:: functions take.
  13527. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  13528. using namespace httplib::tls;
  13529. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13530. ASSERT_TRUE(svr.is_valid());
  13531. svr.Get("/test", [](const Request &, Response &res) {
  13532. res.set_content("ok", "text/plain");
  13533. });
  13534. auto port = svr.bind_to_any_port(HOST);
  13535. thread t([&]() { svr.listen_after_bind(); });
  13536. auto se = detail::scope_exit([&] {
  13537. svr.stop();
  13538. t.join();
  13539. });
  13540. svr.wait_until_ready();
  13541. SSLClient cli(HOST, port);
  13542. cli.enable_server_certificate_verification(false);
  13543. session_t verifier_session = nullptr;
  13544. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  13545. verifier_session = ctx.session;
  13546. return true;
  13547. });
  13548. session_t session_verifier_session = nullptr;
  13549. cli.set_session_verifier([&](session_t session) {
  13550. session_verifier_session = session;
  13551. return SSLVerifierResponse::NoDecisionMade;
  13552. });
  13553. auto res = cli.Get("/test");
  13554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13555. EXPECT_NE(nullptr, verifier_session);
  13556. EXPECT_EQ(session_verifier_session, verifier_session);
  13557. }
  13558. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  13559. using httplib::tls::TlsError;
  13560. // Test that verify_error_to_string returns empty for success
  13561. std::string success_str = TlsError::verify_error_to_string(0);
  13562. EXPECT_TRUE(success_str.empty());
  13563. // Test that verify_error_to_string returns non-empty for error codes
  13564. // Using a common error code (certificate expired)
  13565. std::string error_str =
  13566. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  13567. EXPECT_FALSE(error_str.empty());
  13568. }
  13569. TEST(SessionVerifierTest, CertificateAccepted) {
  13570. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13571. ASSERT_TRUE(svr.is_valid());
  13572. svr.Get("/test", [](const Request &, Response &res) {
  13573. res.set_content("ok", "text/plain");
  13574. });
  13575. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13576. auto se = detail::scope_exit([&] {
  13577. svr.stop();
  13578. t.join();
  13579. });
  13580. svr.wait_until_ready();
  13581. SSLClient cli(HOST, PORT);
  13582. cli.enable_server_certificate_verification(false);
  13583. cli.set_connection_timeout(30);
  13584. bool callback_called = false;
  13585. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13586. EXPECT_NE(session, nullptr);
  13587. callback_called = true;
  13588. return SSLVerifierResponse::CertificateAccepted;
  13589. });
  13590. auto res = cli.Get("/test");
  13591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13592. EXPECT_EQ(200, res->status);
  13593. EXPECT_TRUE(callback_called);
  13594. }
  13595. TEST(SessionVerifierTest, CertificateRejected) {
  13596. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13597. ASSERT_TRUE(svr.is_valid());
  13598. svr.Get("/test", [](const Request &, Response &res) {
  13599. res.set_content("ok", "text/plain");
  13600. });
  13601. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13602. auto se = detail::scope_exit([&] {
  13603. svr.stop();
  13604. t.join();
  13605. });
  13606. svr.wait_until_ready();
  13607. SSLClient cli(HOST, PORT);
  13608. cli.enable_server_certificate_verification(false);
  13609. cli.set_connection_timeout(30);
  13610. bool callback_called = false;
  13611. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13612. EXPECT_NE(session, nullptr);
  13613. callback_called = true;
  13614. return SSLVerifierResponse::CertificateRejected;
  13615. });
  13616. auto res = cli.Get("/test");
  13617. EXPECT_FALSE(res);
  13618. EXPECT_TRUE(callback_called);
  13619. }
  13620. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  13621. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13622. ASSERT_TRUE(svr.is_valid());
  13623. svr.Get("/test", [](const Request &, Response &res) {
  13624. res.set_content("ok", "text/plain");
  13625. });
  13626. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13627. auto se = detail::scope_exit([&] {
  13628. svr.stop();
  13629. t.join();
  13630. });
  13631. svr.wait_until_ready();
  13632. // NoDecisionMade with verification disabled should succeed (no default check)
  13633. SSLClient cli(HOST, PORT);
  13634. cli.enable_server_certificate_verification(false);
  13635. cli.set_connection_timeout(30);
  13636. bool callback_called = false;
  13637. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13638. EXPECT_NE(session, nullptr);
  13639. callback_called = true;
  13640. return SSLVerifierResponse::NoDecisionMade;
  13641. });
  13642. auto res = cli.Get("/test");
  13643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13644. EXPECT_EQ(200, res->status);
  13645. EXPECT_TRUE(callback_called);
  13646. }
  13647. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  13648. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13649. ASSERT_TRUE(svr.is_valid());
  13650. svr.Get("/test", [](const Request &, Response &res) {
  13651. res.set_content("ok", "text/plain");
  13652. });
  13653. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13654. auto se = detail::scope_exit([&] {
  13655. svr.stop();
  13656. t.join();
  13657. });
  13658. svr.wait_until_ready();
  13659. // NoDecisionMade with verification enabled should fail (self-signed cert).
  13660. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  13661. // so we only check that the request fails, not whether the callback was
  13662. // called.
  13663. SSLClient cli(HOST, PORT);
  13664. cli.enable_server_certificate_verification(true);
  13665. cli.set_connection_timeout(30);
  13666. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  13667. EXPECT_NE(session, nullptr);
  13668. return SSLVerifierResponse::NoDecisionMade;
  13669. });
  13670. auto res = cli.Get("/test");
  13671. EXPECT_FALSE(res);
  13672. }
  13673. TEST(SSLClientServerTest, ClientCAListFromPem) {
  13674. // Test SSL server using PemMemory constructor with client CA certificates
  13675. // Read PEM files
  13676. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13677. read_file(SERVER_CERT_FILE, server_cert_pem);
  13678. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13679. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13680. // Create SSLServer with PemMemory constructor including client CA
  13681. SSLServer::PemMemory server_pem = {
  13682. server_cert_pem.c_str(),
  13683. server_cert_pem.size(),
  13684. server_key_pem.c_str(),
  13685. server_key_pem.size(),
  13686. client_ca_pem.c_str(),
  13687. client_ca_pem.size(),
  13688. nullptr // no password for server key
  13689. };
  13690. SSLServer svr(server_pem);
  13691. ASSERT_TRUE(svr.is_valid());
  13692. // No SSL error should be recorded for valid setup
  13693. EXPECT_EQ(0, svr.ssl_last_error());
  13694. // Set up server endpoints
  13695. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  13696. res.set_content("ok", "text/plain");
  13697. });
  13698. // Start server in a thread
  13699. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  13700. svr.wait_until_ready();
  13701. // Connect with client certificate (using constructor with paths)
  13702. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13703. cli.enable_server_certificate_verification(false);
  13704. auto res = cli.Get("/test-pem-ca");
  13705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13706. EXPECT_EQ(200, res->status);
  13707. EXPECT_EQ("ok", res->body);
  13708. svr.stop();
  13709. server_thread.join();
  13710. }
  13711. #endif
  13712. #ifdef _WIN32
  13713. TEST(CleanupTest, WSACleanup) {
  13714. int ret = WSACleanup();
  13715. ASSERT_EQ(0, ret);
  13716. }
  13717. #endif
  13718. #ifndef CPPHTTPLIB_SSL_ENABLED
  13719. TEST(NoSSLSupport, SimpleInterface) {
  13720. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  13721. }
  13722. #endif
  13723. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  13724. TEST(InvalidScheme, SimpleInterface) {
  13725. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  13726. }
  13727. #endif
  13728. TEST(NoScheme, SimpleInterface) {
  13729. Client cli("yahoo.com:80");
  13730. ASSERT_TRUE(cli.is_valid());
  13731. }
  13732. TEST(SendAPI, SimpleInterface_Online) {
  13733. Client cli("http://yahoo.com");
  13734. Request req;
  13735. req.method = "GET";
  13736. req.path = "/";
  13737. auto res = cli.send(req);
  13738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13739. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13740. }
  13741. TEST(SendAPI, WithParamsInRequest) {
  13742. Server svr;
  13743. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  13744. EXPECT_TRUE(req.has_param("test"));
  13745. EXPECT_EQ("test_value", req.get_param_value("test"));
  13746. });
  13747. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  13748. auto se = detail::scope_exit([&] {
  13749. svr.stop();
  13750. t.join();
  13751. ASSERT_FALSE(svr.is_running());
  13752. });
  13753. svr.wait_until_ready();
  13754. Client cli(HOST, PORT);
  13755. {
  13756. Request req;
  13757. req.method = "GET";
  13758. req.path = "/";
  13759. req.params.emplace("test", "test_value");
  13760. auto res = cli.send(req);
  13761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13762. }
  13763. {
  13764. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  13765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13766. }
  13767. }
  13768. TEST(ClientImplMethods, GetSocketTest) {
  13769. httplib::Server svr;
  13770. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  13771. res.status = StatusCode::OK_200;
  13772. });
  13773. auto port = svr.bind_to_any_port("127.0.0.1");
  13774. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13775. auto se = detail::scope_exit([&] {
  13776. svr.stop();
  13777. thread.join();
  13778. ASSERT_FALSE(svr.is_running());
  13779. });
  13780. svr.wait_until_ready();
  13781. {
  13782. httplib::Client cli("127.0.0.1", port);
  13783. cli.set_keep_alive(true);
  13784. // Use the behavior of cpp-httplib of opening the connection
  13785. // only when the first request happens. If that changes,
  13786. // this test would be obsolete.
  13787. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  13788. // This also implicitly tests the server. But other tests would fail much
  13789. // earlier than this one to be considered.
  13790. auto res = cli.Get("/");
  13791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13792. EXPECT_EQ(StatusCode::OK_200, res->status);
  13793. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  13794. }
  13795. }
  13796. #ifdef CPPHTTPLIB_SSL_ENABLED
  13797. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  13798. Client cli("http://yahoo.com");
  13799. auto res = cli.Get("/");
  13800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13801. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13802. cli.set_follow_location(true);
  13803. res = cli.Get("/");
  13804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13805. EXPECT_EQ(StatusCode::OK_200, res->status);
  13806. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13807. }
  13808. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  13809. Client cli("https://yahoo.com");
  13810. auto res = cli.Get("/");
  13811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13812. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13813. cli.set_follow_location(true);
  13814. res = cli.Get("/");
  13815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13816. EXPECT_EQ(StatusCode::OK_200, res->status);
  13817. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13818. }
  13819. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  13820. Client cli("https://yahoo.com");
  13821. auto res = cli.Get("/");
  13822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13823. ASSERT_FALSE(!res);
  13824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13825. ASSERT_FALSE(res == nullptr);
  13826. ASSERT_TRUE(res != nullptr);
  13827. EXPECT_EQ(Error::Success, res.error());
  13828. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  13829. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  13830. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  13831. cli.set_follow_location(true);
  13832. res = cli.Get("/");
  13833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13834. EXPECT_EQ(Error::Success, res.error());
  13835. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  13836. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  13837. EXPECT_EQ(StatusCode::OK_200, res->status);
  13838. EXPECT_EQ("https://www.yahoo.com/", res->location);
  13839. }
  13840. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  13841. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  13842. Client cli("https://cdnjs.cloudflare.com");
  13843. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  13844. Headers{{"Accept-Encoding", "br"}});
  13845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13846. EXPECT_EQ(StatusCode::OK_200, res->status);
  13847. EXPECT_EQ(287630U, res->body.size());
  13848. EXPECT_EQ("application/javascript; charset=utf-8",
  13849. res->get_header_value("Content-Type"));
  13850. }
  13851. #endif
  13852. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  13853. #undef REDIR_HOST // Silence compiler warning
  13854. #define REDIR_HOST "https://httpbingo.org"
  13855. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  13856. Client cli(REDIR_HOST);
  13857. cli.set_follow_location(true);
  13858. auto res =
  13859. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  13860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13861. EXPECT_EQ(StatusCode::OK_200, res->status);
  13862. }
  13863. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  13864. Client cli(REDIR_HOST);
  13865. cli.set_follow_location(true);
  13866. Params params;
  13867. params.emplace("url", "http://example.com");
  13868. params.emplace("status_code", "302");
  13869. auto res = cli.Get(REDIR_PATH, params, Headers{});
  13870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13871. EXPECT_EQ(StatusCode::OK_200, res->status);
  13872. }
  13873. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  13874. Client cli(REDIR_HOST);
  13875. cli.set_follow_location(true);
  13876. Params params;
  13877. params.emplace("url", "http://example.com");
  13878. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  13879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13880. EXPECT_EQ(StatusCode::OK_200, res->status);
  13881. }
  13882. TEST(HttpToHttpsRedirectTest, CertFile) {
  13883. auto ssl_port = PORT + 1;
  13884. Server svr;
  13885. ASSERT_TRUE(svr.is_valid());
  13886. svr.Get("/index", [&](const Request &, Response &res) {
  13887. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13888. "/index");
  13889. svr.stop();
  13890. });
  13891. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13892. ASSERT_TRUE(ssl_svr.is_valid());
  13893. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  13894. res.set_content("test", "text/plain");
  13895. ssl_svr.stop();
  13896. });
  13897. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13898. thread t2 =
  13899. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  13900. auto se = detail::scope_exit([&] {
  13901. t2.join();
  13902. t.join();
  13903. ASSERT_FALSE(svr.is_running());
  13904. });
  13905. svr.wait_until_ready();
  13906. ssl_svr.wait_until_ready();
  13907. Client cli("127.0.0.1", PORT);
  13908. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13909. cli.enable_server_certificate_verification(true);
  13910. cli.set_follow_location(true);
  13911. cli.set_connection_timeout(30);
  13912. auto res = cli.Get("/index");
  13913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13914. ASSERT_EQ(StatusCode::OK_200, res->status);
  13915. }
  13916. TEST(SSLClientRedirectTest, CertFile) {
  13917. auto ssl_port = PORT + 1;
  13918. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13919. ASSERT_TRUE(ssl_svr1.is_valid());
  13920. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13921. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13922. "/index");
  13923. ssl_svr1.stop();
  13924. });
  13925. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13926. ASSERT_TRUE(ssl_svr2.is_valid());
  13927. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13928. res.set_content("test", "text/plain");
  13929. ssl_svr2.stop();
  13930. });
  13931. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  13932. thread t2 =
  13933. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  13934. auto se = detail::scope_exit([&] {
  13935. t2.join();
  13936. t.join();
  13937. ASSERT_FALSE(ssl_svr1.is_running());
  13938. });
  13939. ssl_svr1.wait_until_ready();
  13940. ssl_svr2.wait_until_ready();
  13941. SSLClient cli("127.0.0.1", PORT);
  13942. std::string cert;
  13943. read_file(SERVER_CERT2_FILE, cert);
  13944. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13945. cli.enable_server_certificate_verification(true);
  13946. cli.set_follow_location(true);
  13947. cli.set_connection_timeout(30);
  13948. auto res = cli.Get("/index");
  13949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13950. ASSERT_EQ(StatusCode::OK_200, res->status);
  13951. }
  13952. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  13953. // another port, so the client follows it with a new client.
  13954. static Result GetThroughTlsRedirectToDifferentPort(
  13955. const std::function<void(SSLClient &)> &setup,
  13956. const char *target_cert = SERVER_CERT2_FILE) {
  13957. auto ssl_port = PORT + 1;
  13958. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13959. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  13960. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  13961. "/index");
  13962. });
  13963. SSLServer ssl_svr2(target_cert, SERVER_PRIVATE_KEY_FILE);
  13964. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  13965. res.set_content("test", "text/plain");
  13966. });
  13967. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  13968. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  13969. auto se = detail::scope_exit([&] {
  13970. ssl_svr2.stop();
  13971. ssl_svr1.stop();
  13972. t2.join();
  13973. t.join();
  13974. });
  13975. ssl_svr1.wait_until_ready();
  13976. ssl_svr2.wait_until_ready();
  13977. SSLClient cli("127.0.0.1", PORT);
  13978. cli.set_follow_location(true);
  13979. cli.set_connection_timeout(30);
  13980. setup(cli);
  13981. return cli.Get("/index");
  13982. }
  13983. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  13984. auto calls = 0;
  13985. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  13986. cli.enable_server_certificate_verification(false);
  13987. // Accept the first server only.
  13988. cli.set_session_verifier([&](tls::session_t) {
  13989. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  13990. : SSLVerifierResponse::CertificateRejected;
  13991. });
  13992. });
  13993. EXPECT_FALSE(res);
  13994. EXPECT_EQ(2, calls);
  13995. }
  13996. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  13997. std::string pinned;
  13998. auto res = GetThroughTlsRedirectToDifferentPort(
  13999. [&](SSLClient &cli) {
  14000. cli.enable_server_certificate_verification(false);
  14001. // Pin the first certificate seen.
  14002. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  14003. if (pinned.empty()) { pinned = ctx.serial(); }
  14004. return ctx.serial() == pinned;
  14005. });
  14006. },
  14007. // A certificate other than the first server's.
  14008. SERVER_CERT_FILE);
  14009. EXPECT_FALSE(res);
  14010. EXPECT_FALSE(pinned.empty());
  14011. }
  14012. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  14013. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  14014. std::string cert;
  14015. read_file(SERVER_CERT2_FILE, cert);
  14016. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14017. });
  14018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14019. EXPECT_EQ(StatusCode::OK_200, res->status);
  14020. }
  14021. #endif
  14022. #ifdef CPPHTTPLIB_SSL_ENABLED
  14023. // Test that set_ca_cert_store() skips system certs (consistent with
  14024. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  14025. // should be trusted - system certs should NOT be loaded.
  14026. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  14027. // Load a specific cert that is NOT a system CA cert
  14028. std::string cert;
  14029. read_file(SERVER_CERT2_FILE, cert);
  14030. SSLClient cli("google.com");
  14031. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14032. cli.enable_server_certificate_verification(true);
  14033. // This should FAIL because:
  14034. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  14035. // 2. System certs should NOT be loaded when custom store is set
  14036. // If system certs WERE loaded, this would succeed
  14037. auto res = cli.Get("/");
  14038. ASSERT_FALSE(res);
  14039. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14040. }
  14041. // Same as above, but through the native store handle path. Regression test:
  14042. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  14043. // merged system certs into the user-provided store.
  14044. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  14045. std::string cert;
  14046. read_file(SERVER_CERT2_FILE, cert);
  14047. SSLClient cli("google.com");
  14048. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14049. cli.enable_server_certificate_verification(true);
  14050. auto res = cli.Get("/");
  14051. ASSERT_FALSE(res);
  14052. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14053. }
  14054. // A custom store set via the native handle must still verify a server whose
  14055. // cert it does contain.
  14056. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  14057. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14058. ASSERT_TRUE(svr.is_valid());
  14059. svr.Get("/test", [&](const Request &, Response &res) {
  14060. res.set_content("test", "text/plain");
  14061. });
  14062. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14063. auto se = detail::scope_exit([&] {
  14064. svr.stop();
  14065. t.join();
  14066. ASSERT_FALSE(svr.is_running());
  14067. });
  14068. svr.wait_until_ready();
  14069. SSLClient cli("127.0.0.1", PORT);
  14070. std::string cert;
  14071. read_file(SERVER_CERT2_FILE, cert);
  14072. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  14073. cli.enable_server_certificate_verification(true);
  14074. cli.set_connection_timeout(30);
  14075. auto res = cli.Get("/test");
  14076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14077. ASSERT_EQ(StatusCode::OK_200, res->status);
  14078. }
  14079. // CA certs loaded through the universal Client must be transferred to the
  14080. // client created internally for following an HTTPS redirect. Regression test:
  14081. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  14082. // the CA data for redirect transfer.
  14083. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  14084. auto ssl_port = PORT + 1;
  14085. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14086. ASSERT_TRUE(ssl_svr1.is_valid());
  14087. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  14088. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14089. "/index");
  14090. });
  14091. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14092. ASSERT_TRUE(ssl_svr2.is_valid());
  14093. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  14094. res.set_content("test", "text/plain");
  14095. });
  14096. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  14097. thread t2 =
  14098. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  14099. auto se = detail::scope_exit([&] {
  14100. ssl_svr2.stop();
  14101. ssl_svr1.stop();
  14102. t2.join();
  14103. t.join();
  14104. ASSERT_FALSE(ssl_svr1.is_running());
  14105. });
  14106. ssl_svr1.wait_until_ready();
  14107. ssl_svr2.wait_until_ready();
  14108. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14109. std::string cert;
  14110. read_file(SERVER_CERT2_FILE, cert);
  14111. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14112. cli.enable_server_certificate_verification(true);
  14113. cli.set_follow_location(true);
  14114. cli.set_connection_timeout(30);
  14115. auto res = cli.Get("/index");
  14116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14117. ASSERT_EQ(StatusCode::OK_200, res->status);
  14118. }
  14119. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  14120. // so a host signed by a system CA verifies even though a custom CA is set
  14121. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  14122. std::string cert;
  14123. read_file(SERVER_CERT2_FILE, cert);
  14124. SSLClient cli("google.com");
  14125. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14126. cli.enable_system_ca(true);
  14127. cli.enable_server_certificate_verification(true);
  14128. auto res = cli.Get("/");
  14129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14130. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14131. }
  14132. // The custom CA remains effective when combined with the system CA
  14133. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  14134. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14135. ASSERT_TRUE(svr.is_valid());
  14136. svr.Get("/test", [&](const Request &, Response &res) {
  14137. res.set_content("test", "text/plain");
  14138. });
  14139. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14140. auto se = detail::scope_exit([&] {
  14141. svr.stop();
  14142. t.join();
  14143. ASSERT_FALSE(svr.is_running());
  14144. });
  14145. svr.wait_until_ready();
  14146. SSLClient cli("127.0.0.1", PORT);
  14147. std::string cert;
  14148. read_file(SERVER_CERT2_FILE, cert);
  14149. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14150. cli.enable_system_ca(true);
  14151. cli.enable_server_certificate_verification(true);
  14152. cli.set_connection_timeout(30);
  14153. auto res = cli.Get("/test");
  14154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14155. ASSERT_EQ(StatusCode::OK_200, res->status);
  14156. }
  14157. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  14158. // skip chain verification entirely (only the certificate identity was
  14159. // checked), so a server presenting an untrusted certificate with a matching
  14160. // IP SAN was accepted. The chain must be validated for IP hosts too.
  14161. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  14162. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14163. ASSERT_TRUE(svr.is_valid());
  14164. svr.Get("/test", [&](const Request &, Response &res) {
  14165. res.set_content("test", "text/plain");
  14166. });
  14167. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14168. auto se = detail::scope_exit([&] {
  14169. svr.stop();
  14170. t.join();
  14171. ASSERT_FALSE(svr.is_running());
  14172. });
  14173. svr.wait_until_ready();
  14174. SSLClient cli("127.0.0.1", PORT);
  14175. std::string cert;
  14176. // A trusted CA that did not sign the server certificate. The server cert
  14177. // (cert2) carries the matching IP SAN, so only chain validation can reject
  14178. // this connection.
  14179. read_file(CLIENT_CA_CERT_FILE, cert);
  14180. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14181. cli.enable_server_certificate_verification(true);
  14182. cli.set_connection_timeout(30);
  14183. auto res = cli.Get("/test");
  14184. ASSERT_FALSE(res);
  14185. }
  14186. // enable_system_ca(false) prevents system CA loading entirely
  14187. TEST(SSLClientTest, DisableSystemCa_Online) {
  14188. SSLClient cli("google.com");
  14189. cli.enable_system_ca(false);
  14190. cli.enable_server_certificate_verification(true);
  14191. auto res = cli.Get("/");
  14192. ASSERT_FALSE(res);
  14193. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  14194. // itself when the CA chain is empty
  14195. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  14196. res.error() == Error::SSLConnection);
  14197. }
  14198. // The universal Client forwards enable_system_ca()
  14199. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  14200. std::string cert;
  14201. read_file(SERVER_CERT2_FILE, cert);
  14202. Client cli("https://google.com");
  14203. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14204. cli.enable_system_ca(true);
  14205. cli.enable_server_certificate_verification(true);
  14206. auto res = cli.Get("/");
  14207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14208. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  14209. }
  14210. // The system CA policy must carry over to the client created internally for
  14211. // following a cross-host HTTPS redirect
  14212. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  14213. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14214. ASSERT_TRUE(svr.is_valid());
  14215. svr.Get("/index", [&](const Request &, Response &res) {
  14216. res.set_redirect("https://www.google.com/");
  14217. });
  14218. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14219. auto se = detail::scope_exit([&] {
  14220. svr.stop();
  14221. t.join();
  14222. ASSERT_FALSE(svr.is_running());
  14223. });
  14224. svr.wait_until_ready();
  14225. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  14226. std::string cert;
  14227. read_file(SERVER_CERT2_FILE, cert);
  14228. cli.load_ca_cert_store(cert.c_str(), cert.size());
  14229. cli.enable_system_ca(true);
  14230. cli.enable_server_certificate_verification(true);
  14231. cli.set_follow_location(true);
  14232. cli.set_connection_timeout(30);
  14233. // Receiving any response proves the redirect client completed the TLS
  14234. // handshake with a system-CA-signed host
  14235. auto res = cli.Get("/index");
  14236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14237. }
  14238. TEST(MultipartFormDataTest, LargeData) {
  14239. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14240. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  14241. const ContentReader &content_reader) {
  14242. if (req.is_multipart_form_data()) {
  14243. std::vector<FormData> items;
  14244. content_reader(
  14245. [&](const FormData &file) {
  14246. items.push_back(file);
  14247. return true;
  14248. },
  14249. [&](const char *data, size_t data_length) {
  14250. items.back().content.append(data, data_length);
  14251. return true;
  14252. });
  14253. EXPECT_TRUE(std::string(items[0].name) == "document");
  14254. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14255. EXPECT_TRUE(items[0].filename == "2MB_data");
  14256. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14257. EXPECT_TRUE(items[1].name == "hello");
  14258. EXPECT_TRUE(items[1].content == "world");
  14259. EXPECT_TRUE(items[1].filename == "");
  14260. EXPECT_TRUE(items[1].content_type == "");
  14261. } else {
  14262. std::string body;
  14263. content_reader([&](const char *data, size_t data_length) {
  14264. body.append(data, data_length);
  14265. return true;
  14266. });
  14267. }
  14268. });
  14269. auto port = svr.bind_to_any_port(HOST);
  14270. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14271. auto se = detail::scope_exit([&] {
  14272. svr.stop();
  14273. t.join();
  14274. ASSERT_FALSE(svr.is_running());
  14275. });
  14276. svr.wait_until_ready();
  14277. {
  14278. std::string data(1024 * 1024 * 2, '.');
  14279. std::stringstream buffer;
  14280. buffer << data;
  14281. SSLClient cli(HOST, port);
  14282. cli.enable_server_certificate_verification(false);
  14283. UploadFormDataItems items{
  14284. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14285. {"hello", "world", "", ""},
  14286. };
  14287. auto res = cli.Post("/post", items);
  14288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14289. ASSERT_EQ(StatusCode::OK_200, res->status);
  14290. }
  14291. }
  14292. TEST(MultipartFormDataTest, DataProviderItems) {
  14293. std::random_device seed_gen;
  14294. std::mt19937 random(seed_gen());
  14295. std::string rand1;
  14296. rand1.resize(1000);
  14297. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  14298. std::string rand2;
  14299. rand2.resize(3000);
  14300. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  14301. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14302. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  14303. const ContentReader &content_reader) {
  14304. ASSERT_FALSE(req.is_multipart_form_data());
  14305. std::string body;
  14306. content_reader([&](const char *data, size_t data_length) {
  14307. body.append(data, data_length);
  14308. return true;
  14309. });
  14310. EXPECT_EQ(body, "");
  14311. });
  14312. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  14313. const ContentReader &content_reader) {
  14314. ASSERT_TRUE(req.is_multipart_form_data());
  14315. std::vector<FormData> items;
  14316. content_reader(
  14317. [&](const FormData &file) {
  14318. items.push_back(file);
  14319. return true;
  14320. },
  14321. [&](const char *data, size_t data_length) {
  14322. items.back().content.append(data, data_length);
  14323. return true;
  14324. });
  14325. ASSERT_TRUE(items.size() == 2);
  14326. EXPECT_EQ(std::string(items[0].name), "name1");
  14327. EXPECT_EQ(items[0].content, "Testing123");
  14328. EXPECT_EQ(items[0].filename, "filename1");
  14329. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14330. EXPECT_EQ(items[1].name, "name2");
  14331. EXPECT_EQ(items[1].content, "Testing456");
  14332. EXPECT_EQ(items[1].filename, "");
  14333. EXPECT_EQ(items[1].content_type, "");
  14334. });
  14335. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  14336. const ContentReader &content_reader) {
  14337. ASSERT_TRUE(req.is_multipart_form_data());
  14338. std::vector<FormData> items;
  14339. content_reader(
  14340. [&](const FormData &file) {
  14341. items.push_back(file);
  14342. return true;
  14343. },
  14344. [&](const char *data, size_t data_length) {
  14345. items.back().content.append(data, data_length);
  14346. return true;
  14347. });
  14348. ASSERT_TRUE(items.size() == 2);
  14349. EXPECT_EQ(items[0].name, "name3");
  14350. EXPECT_EQ(items[0].content, rand1);
  14351. EXPECT_EQ(items[0].filename, "filename3");
  14352. EXPECT_EQ(items[0].content_type, "");
  14353. EXPECT_EQ(items[1].name, "name4");
  14354. EXPECT_EQ(items[1].content, rand2);
  14355. EXPECT_EQ(items[1].filename, "filename4");
  14356. EXPECT_EQ(items[1].content_type, "");
  14357. });
  14358. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  14359. const ContentReader &content_reader) {
  14360. ASSERT_TRUE(req.is_multipart_form_data());
  14361. std::vector<FormData> items;
  14362. content_reader(
  14363. [&](const FormData &file) {
  14364. items.push_back(file);
  14365. return true;
  14366. },
  14367. [&](const char *data, size_t data_length) {
  14368. items.back().content.append(data, data_length);
  14369. return true;
  14370. });
  14371. ASSERT_TRUE(items.size() == 4);
  14372. EXPECT_EQ(std::string(items[0].name), "name1");
  14373. EXPECT_EQ(items[0].content, "Testing123");
  14374. EXPECT_EQ(items[0].filename, "filename1");
  14375. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  14376. EXPECT_EQ(items[1].name, "name2");
  14377. EXPECT_EQ(items[1].content, "Testing456");
  14378. EXPECT_EQ(items[1].filename, "");
  14379. EXPECT_EQ(items[1].content_type, "");
  14380. EXPECT_EQ(items[2].name, "name3");
  14381. EXPECT_EQ(items[2].content, rand1);
  14382. EXPECT_EQ(items[2].filename, "filename3");
  14383. EXPECT_EQ(items[2].content_type, "");
  14384. EXPECT_EQ(items[3].name, "name4");
  14385. EXPECT_EQ(items[3].content, rand2);
  14386. EXPECT_EQ(items[3].filename, "filename4");
  14387. EXPECT_EQ(items[3].content_type, "");
  14388. });
  14389. auto port = svr.bind_to_any_port("localhost");
  14390. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14391. auto se = detail::scope_exit([&] {
  14392. svr.stop();
  14393. t.join();
  14394. ASSERT_FALSE(svr.is_running());
  14395. });
  14396. svr.wait_until_ready();
  14397. {
  14398. SSLClient cli("localhost", port);
  14399. cli.enable_server_certificate_verification(false);
  14400. UploadFormDataItems items{
  14401. {"name1", "Testing123", "filename1", "application/octet-stream"},
  14402. {"name2", "Testing456", "", ""}, // not a file
  14403. };
  14404. {
  14405. auto res = cli.Post("/post-none", {}, {}, {});
  14406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14407. ASSERT_EQ(StatusCode::OK_200, res->status);
  14408. }
  14409. FormDataProviderItems providers;
  14410. {
  14411. auto res =
  14412. cli.Post("/post-items", {}, items, providers); // empty providers
  14413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14414. ASSERT_EQ(StatusCode::OK_200, res->status);
  14415. }
  14416. providers.push_back({"name3",
  14417. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14418. // test the offset is given correctly at each step
  14419. if (!offset)
  14420. sink.os.write(rand1.data(), 30);
  14421. else if (offset == 30)
  14422. sink.os.write(rand1.data() + 30, 300);
  14423. else if (offset == 330)
  14424. sink.os.write(rand1.data() + 330, 670);
  14425. else if (offset == rand1.size())
  14426. sink.done();
  14427. return true;
  14428. },
  14429. "filename3",
  14430. {}});
  14431. providers.push_back({"name4",
  14432. [&](size_t offset, httplib::DataSink &sink) -> bool {
  14433. // test the offset is given correctly at each step
  14434. if (!offset)
  14435. sink.os.write(rand2.data(), 2000);
  14436. else if (offset == 2000)
  14437. sink.os.write(rand2.data() + 2000, 1);
  14438. else if (offset == 2001)
  14439. sink.os.write(rand2.data() + 2001, 999);
  14440. else if (offset == rand2.size())
  14441. sink.done();
  14442. return true;
  14443. },
  14444. "filename4",
  14445. {}});
  14446. {
  14447. auto res = cli.Post("/post-providers", {}, {}, providers);
  14448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14449. ASSERT_EQ(StatusCode::OK_200, res->status);
  14450. }
  14451. {
  14452. auto res = cli.Post("/post-both", {}, items, providers);
  14453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14454. ASSERT_EQ(StatusCode::OK_200, res->status);
  14455. }
  14456. }
  14457. }
  14458. TEST(MultipartFormDataTest, BadHeader) {
  14459. Server svr;
  14460. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14461. res.set_content("ok", "text/plain");
  14462. });
  14463. thread t = thread([&] { svr.listen(HOST, PORT); });
  14464. auto se = detail::scope_exit([&] {
  14465. svr.stop();
  14466. t.join();
  14467. ASSERT_FALSE(svr.is_running());
  14468. });
  14469. svr.wait_until_ready();
  14470. const std::string body =
  14471. "This is the preamble. It is to be ignored, though it\r\n"
  14472. "is a handy place for composition agents to include an\r\n"
  14473. "explanatory note to non-MIME conformant readers.\r\n"
  14474. "\r\n"
  14475. "\r\n"
  14476. "--simple boundary\r\n"
  14477. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14478. ": BAD...\r\n"
  14479. "\r\n"
  14480. "value1\r\n"
  14481. "--simple boundary\r\n"
  14482. "Content-Disposition: form-data; name=\"field2\"; "
  14483. "filename=\"example.txt\"\r\n"
  14484. "\r\n"
  14485. "value2\r\n"
  14486. "--simple boundary--\r\n"
  14487. "This is the epilogue. It is also to be ignored.\r\n";
  14488. std::string content_type =
  14489. R"(multipart/form-data; boundary="simple boundary")";
  14490. Client cli(HOST, PORT);
  14491. auto res = cli.Post("/post", body, content_type.c_str());
  14492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14493. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14494. }
  14495. TEST(MultipartFormDataTest, WithPreamble) {
  14496. Server svr;
  14497. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14498. res.set_content("ok", "text/plain");
  14499. });
  14500. thread t = thread([&] { svr.listen(HOST, PORT); });
  14501. auto se = detail::scope_exit([&] {
  14502. svr.stop();
  14503. t.join();
  14504. ASSERT_FALSE(svr.is_running());
  14505. });
  14506. svr.wait_until_ready();
  14507. const std::string body =
  14508. "This is the preamble. It is to be ignored, though it\r\n"
  14509. "is a handy place for composition agents to include an\r\n"
  14510. "explanatory note to non-MIME conformant readers.\r\n"
  14511. "\r\n"
  14512. "\r\n"
  14513. "--simple boundary\r\n"
  14514. "Content-Disposition: form-data; name=\"field1\"\r\n"
  14515. "\r\n"
  14516. "value1\r\n"
  14517. "--simple boundary\r\n"
  14518. "Content-Disposition: form-data; name=\"field2\"; "
  14519. "filename=\"example.txt\"\r\n"
  14520. "\r\n"
  14521. "value2\r\n"
  14522. "--simple boundary--\r\n"
  14523. "This is the epilogue. It is also to be ignored.\r\n";
  14524. std::string content_type =
  14525. R"(multipart/form-data; boundary="simple boundary")";
  14526. Client cli(HOST, PORT);
  14527. auto res = cli.Post("/post", body, content_type.c_str());
  14528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14529. EXPECT_EQ(StatusCode::OK_200, res->status);
  14530. }
  14531. TEST(MultipartFormDataTest, PostCustomBoundary) {
  14532. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14533. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  14534. const ContentReader &content_reader) {
  14535. if (req.is_multipart_form_data()) {
  14536. std::vector<FormData> items;
  14537. content_reader(
  14538. [&](const FormData &file) {
  14539. items.push_back(file);
  14540. return true;
  14541. },
  14542. [&](const char *data, size_t data_length) {
  14543. items.back().content.append(data, data_length);
  14544. return true;
  14545. });
  14546. EXPECT_TRUE(std::string(items[0].name) == "document");
  14547. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14548. EXPECT_TRUE(items[0].filename == "2MB_data");
  14549. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14550. EXPECT_TRUE(items[1].name == "hello");
  14551. EXPECT_TRUE(items[1].content == "world");
  14552. EXPECT_TRUE(items[1].filename == "");
  14553. EXPECT_TRUE(items[1].content_type == "");
  14554. } else {
  14555. std::string body;
  14556. content_reader([&](const char *data, size_t data_length) {
  14557. body.append(data, data_length);
  14558. return true;
  14559. });
  14560. }
  14561. });
  14562. auto port = svr.bind_to_any_port("localhost");
  14563. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14564. auto se = detail::scope_exit([&] {
  14565. svr.stop();
  14566. t.join();
  14567. ASSERT_FALSE(svr.is_running());
  14568. });
  14569. svr.wait_until_ready();
  14570. {
  14571. std::string data(1024 * 1024 * 2, '.');
  14572. std::stringstream buffer;
  14573. buffer << data;
  14574. SSLClient cli("localhost", port);
  14575. cli.enable_server_certificate_verification(false);
  14576. UploadFormDataItems items{
  14577. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14578. {"hello", "world", "", ""},
  14579. };
  14580. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  14581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14582. ASSERT_EQ(StatusCode::OK_200, res->status);
  14583. }
  14584. }
  14585. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  14586. std::string data(1024 * 1024 * 2, '&');
  14587. std::stringstream buffer;
  14588. buffer << data;
  14589. Client cli("https://localhost:8080");
  14590. UploadFormDataItems items{
  14591. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14592. {"hello", "world", "", ""},
  14593. };
  14594. for (const char &c : " \t\r\n") {
  14595. auto res =
  14596. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  14597. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14598. ASSERT_FALSE(res);
  14599. }
  14600. }
  14601. TEST(MultipartFormDataTest, PutFormData) {
  14602. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14603. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  14604. const ContentReader &content_reader) {
  14605. if (req.is_multipart_form_data()) {
  14606. std::vector<FormData> items;
  14607. content_reader(
  14608. [&](const FormData &file) {
  14609. items.push_back(file);
  14610. return true;
  14611. },
  14612. [&](const char *data, size_t data_length) {
  14613. items.back().content.append(data, data_length);
  14614. return true;
  14615. });
  14616. EXPECT_TRUE(std::string(items[0].name) == "document");
  14617. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14618. EXPECT_TRUE(items[0].filename == "2MB_data");
  14619. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14620. EXPECT_TRUE(items[1].name == "hello");
  14621. EXPECT_TRUE(items[1].content == "world");
  14622. EXPECT_TRUE(items[1].filename == "");
  14623. EXPECT_TRUE(items[1].content_type == "");
  14624. } else {
  14625. std::string body;
  14626. content_reader([&](const char *data, size_t data_length) {
  14627. body.append(data, data_length);
  14628. return true;
  14629. });
  14630. }
  14631. });
  14632. auto port = svr.bind_to_any_port("localhost");
  14633. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14634. auto se = detail::scope_exit([&] {
  14635. svr.stop();
  14636. t.join();
  14637. ASSERT_FALSE(svr.is_running());
  14638. });
  14639. svr.wait_until_ready();
  14640. {
  14641. std::string data(1024 * 1024 * 2, '&');
  14642. std::stringstream buffer;
  14643. buffer << data;
  14644. SSLClient cli("localhost", port);
  14645. cli.enable_server_certificate_verification(false);
  14646. UploadFormDataItems items{
  14647. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14648. {"hello", "world", "", ""},
  14649. };
  14650. auto res = cli.Put("/put", items);
  14651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14652. ASSERT_EQ(StatusCode::OK_200, res->status);
  14653. }
  14654. }
  14655. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  14656. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14657. svr.Put("/put_customboundary",
  14658. [&](const Request &req, const Response & /*res*/,
  14659. const ContentReader &content_reader) {
  14660. if (req.is_multipart_form_data()) {
  14661. std::vector<FormData> items;
  14662. content_reader(
  14663. [&](const FormData &file) {
  14664. items.push_back(file);
  14665. return true;
  14666. },
  14667. [&](const char *data, size_t data_length) {
  14668. items.back().content.append(data, data_length);
  14669. return true;
  14670. });
  14671. EXPECT_TRUE(std::string(items[0].name) == "document");
  14672. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  14673. EXPECT_TRUE(items[0].filename == "2MB_data");
  14674. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  14675. EXPECT_TRUE(items[1].name == "hello");
  14676. EXPECT_TRUE(items[1].content == "world");
  14677. EXPECT_TRUE(items[1].filename == "");
  14678. EXPECT_TRUE(items[1].content_type == "");
  14679. } else {
  14680. std::string body;
  14681. content_reader([&](const char *data, size_t data_length) {
  14682. body.append(data, data_length);
  14683. return true;
  14684. });
  14685. }
  14686. });
  14687. auto port = svr.bind_to_any_port("localhost");
  14688. auto t = std::thread([&]() { svr.listen_after_bind(); });
  14689. auto se = detail::scope_exit([&] {
  14690. svr.stop();
  14691. t.join();
  14692. ASSERT_FALSE(svr.is_running());
  14693. });
  14694. svr.wait_until_ready();
  14695. {
  14696. std::string data(1024 * 1024 * 2, '&');
  14697. std::stringstream buffer;
  14698. buffer << data;
  14699. SSLClient cli("localhost", port);
  14700. cli.enable_server_certificate_verification(false);
  14701. UploadFormDataItems items{
  14702. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14703. {"hello", "world", "", ""},
  14704. };
  14705. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  14706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14707. ASSERT_EQ(StatusCode::OK_200, res->status);
  14708. }
  14709. }
  14710. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  14711. std::string data(1024 * 1024 * 2, '&');
  14712. std::stringstream buffer;
  14713. buffer << data;
  14714. Client cli("https://localhost:8080");
  14715. cli.enable_server_certificate_verification(false);
  14716. UploadFormDataItems items{
  14717. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  14718. {"hello", "world", "", ""},
  14719. };
  14720. for (const char &c : " \t\r\n") {
  14721. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  14722. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  14723. ASSERT_FALSE(res);
  14724. }
  14725. }
  14726. TEST(MultipartFormDataTest, AlternateFilename) {
  14727. auto handled = false;
  14728. Server svr;
  14729. svr.Post("/test", [&](const Request &req, Response &res) {
  14730. ASSERT_EQ(2u, req.form.files.size());
  14731. ASSERT_EQ(1u, req.form.fields.size());
  14732. // Test files
  14733. const auto &file1 = req.form.get_file("file1");
  14734. ASSERT_EQ("file1", file1.name);
  14735. ASSERT_EQ("A.txt", file1.filename);
  14736. ASSERT_EQ("text/plain", file1.content_type);
  14737. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  14738. const auto &file2 = req.form.get_file("file2");
  14739. ASSERT_EQ("file2", file2.name);
  14740. ASSERT_EQ("a.html", file2.filename);
  14741. ASSERT_EQ("text/html", file2.content_type);
  14742. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  14743. file2.content);
  14744. // Test text field
  14745. const auto &text = req.form.get_field("text");
  14746. ASSERT_EQ("text default", text);
  14747. res.set_content("ok", "text/plain");
  14748. handled = true;
  14749. });
  14750. thread t = thread([&] { svr.listen(HOST, PORT); });
  14751. auto se = detail::scope_exit([&] {
  14752. svr.stop();
  14753. t.join();
  14754. ASSERT_FALSE(svr.is_running());
  14755. ASSERT_TRUE(handled);
  14756. });
  14757. svr.wait_until_ready();
  14758. auto req = "POST /test HTTP/1.1\r\n"
  14759. "Host: localhost\r\n"
  14760. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14761. "Content-Length: 399\r\n"
  14762. "\r\n"
  14763. "----------\r\n"
  14764. "Content-Disposition: form-data; name=\"text\"\r\n"
  14765. "\r\n"
  14766. "text default\r\n"
  14767. "----------\r\n"
  14768. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  14769. "filename=\"a.txt\"; name=\"file1\"\r\n"
  14770. "Content-Type: text/plain\r\n"
  14771. "\r\n"
  14772. "Content of a.txt.\r\n"
  14773. "\r\n"
  14774. "----------\r\n"
  14775. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  14776. "\"a.html\"\r\n"
  14777. "Content-Type: text/html\r\n"
  14778. "\r\n"
  14779. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  14780. "\r\n"
  14781. "------------\r\n";
  14782. ASSERT_TRUE(send_request(1, req));
  14783. }
  14784. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  14785. auto handled = false;
  14786. Server svr;
  14787. svr.Post("/test", [&](const Request &req, Response &res) {
  14788. // Case-insensitive "utf-8''" prefix with a long value
  14789. const auto &file = req.form.get_file("file1");
  14790. ASSERT_EQ("file1", file.name);
  14791. // 8000 chars exercises both the Content-Disposition parser and the
  14792. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  14793. // Prior to the fix, std::regex_match on this header would cause O(N)
  14794. // stack recursion in libstdc++, leading to SIGSEGV.
  14795. std::string expected_filename(8000, 'A');
  14796. ASSERT_EQ(expected_filename, file.filename);
  14797. res.set_content("ok", "text/plain");
  14798. handled = true;
  14799. });
  14800. thread t = thread([&] { svr.listen(HOST, PORT); });
  14801. auto se = detail::scope_exit([&] {
  14802. svr.stop();
  14803. t.join();
  14804. ASSERT_FALSE(svr.is_running());
  14805. ASSERT_TRUE(handled);
  14806. });
  14807. svr.wait_until_ready();
  14808. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  14809. // Regression test for GHSA-qq6v-r583-3h69
  14810. std::string long_filename(8000, 'A');
  14811. std::string body = "----------\r\n"
  14812. "Content-Disposition: form-data; name=\"file1\"; "
  14813. "filename*=\"Utf-8''" +
  14814. long_filename +
  14815. "\"\r\n"
  14816. "\r\n"
  14817. "hello\r\n"
  14818. "------------\r\n";
  14819. auto req = "POST /test HTTP/1.1\r\n"
  14820. "Host: localhost\r\n"
  14821. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14822. "Content-Length: " +
  14823. std::to_string(body.size()) + "\r\n\r\n" + body;
  14824. ASSERT_TRUE(send_request(1, req));
  14825. }
  14826. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  14827. auto handled = false;
  14828. Server svr;
  14829. svr.Post("/test", [&](const Request &req, Response &) {
  14830. ASSERT_EQ(2u, req.form.fields.size());
  14831. const auto &text1 = req.form.get_field("text1");
  14832. ASSERT_EQ("text1", text1);
  14833. const auto &text2 = req.form.get_field("text2");
  14834. ASSERT_EQ("text2", text2);
  14835. handled = true;
  14836. });
  14837. thread t = thread([&] { svr.listen(HOST, PORT); });
  14838. auto se = detail::scope_exit([&] {
  14839. svr.stop();
  14840. t.join();
  14841. ASSERT_FALSE(svr.is_running());
  14842. ASSERT_TRUE(handled);
  14843. });
  14844. svr.wait_until_ready();
  14845. auto req = "POST /test HTTP/1.1\r\n"
  14846. "Host: localhost\r\n"
  14847. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14848. "Content-Length: 146\r\n"
  14849. "\r\n----------\r\n"
  14850. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14851. "\r\n"
  14852. "text1"
  14853. "\r\n----------\r\n"
  14854. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14855. "\r\n"
  14856. "text2"
  14857. "\r\n------------";
  14858. std::string response;
  14859. ASSERT_TRUE(send_request(1, req, &response));
  14860. ASSERT_EQ("200", response.substr(9, 3));
  14861. }
  14862. TEST(MultipartFormDataTest, ContentLength) {
  14863. auto handled = false;
  14864. Server svr;
  14865. svr.Post("/test", [&](const Request &req, Response &) {
  14866. ASSERT_EQ(2u, req.form.fields.size());
  14867. const auto &text1 = req.form.get_field("text1");
  14868. ASSERT_EQ("text1", text1);
  14869. const auto &text2 = req.form.get_field("text2");
  14870. ASSERT_EQ("text2", text2);
  14871. handled = true;
  14872. });
  14873. thread t = thread([&] { svr.listen(HOST, PORT); });
  14874. auto se = detail::scope_exit([&] {
  14875. svr.stop();
  14876. t.join();
  14877. ASSERT_FALSE(svr.is_running());
  14878. ASSERT_TRUE(handled);
  14879. });
  14880. svr.wait_until_ready();
  14881. auto req = "POST /test HTTP/1.1\r\n"
  14882. "Host: localhost\r\n"
  14883. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14884. "Content-Length: 167\r\n"
  14885. "\r\n----------\r\n"
  14886. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14887. "Content-Length: 5\r\n"
  14888. "\r\n"
  14889. "text1"
  14890. "\r\n----------\r\n"
  14891. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14892. "\r\n"
  14893. "text2"
  14894. "\r\n------------\r\n";
  14895. std::string response;
  14896. ASSERT_TRUE(send_request(1, req, &response));
  14897. ASSERT_EQ("200", response.substr(9, 3));
  14898. }
  14899. TEST(MultipartFormDataTest, AccessPartHeaders) {
  14900. auto handled = false;
  14901. Server svr;
  14902. svr.Post("/test", [&](const Request &req, Response &) {
  14903. ASSERT_EQ(2u, req.form.fields.size());
  14904. const auto &text1 = req.form.get_field("text1");
  14905. ASSERT_EQ("text1", text1);
  14906. // TODO: Add header access for text fields if needed
  14907. const auto &text2 = req.form.get_field("text2");
  14908. ASSERT_EQ("text2", text2);
  14909. // TODO: Header access for text fields needs to be implemented
  14910. // auto &headers = it->second.headers;
  14911. // ASSERT_EQ(3U, headers.size());
  14912. // auto custom_header = headers.find("x-whatever");
  14913. // ASSERT_TRUE(custom_header != headers.end());
  14914. // ASSERT_NE("customvalue", custom_header->second);
  14915. // ASSERT_EQ("CustomValue", custom_header->second);
  14916. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  14917. handled = true;
  14918. });
  14919. thread t = thread([&] { svr.listen(HOST, PORT); });
  14920. auto se = detail::scope_exit([&] {
  14921. svr.stop();
  14922. t.join();
  14923. ASSERT_FALSE(svr.is_running());
  14924. ASSERT_TRUE(handled);
  14925. });
  14926. svr.wait_until_ready();
  14927. auto req = "POST /test HTTP/1.1\r\n"
  14928. "Host: localhost\r\n"
  14929. "Content-Type: multipart/form-data;boundary=--------\r\n"
  14930. "Content-Length: 232\r\n"
  14931. "\r\n----------\r\n"
  14932. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14933. "Content-Length: 5\r\n"
  14934. "X-Test: 1\r\n"
  14935. "\r\n"
  14936. "text1"
  14937. "\r\n----------\r\n"
  14938. "Content-Disposition: form-data; name=\"text2\"\r\n"
  14939. "Content-Type: text/plain\r\n"
  14940. "X-Whatever: CustomValue\r\n"
  14941. "\r\n"
  14942. "text2"
  14943. "\r\n------------\r\n"
  14944. "That should be disregarded. Not even read";
  14945. std::string response;
  14946. ASSERT_TRUE(send_request(1, req, &response));
  14947. ASSERT_EQ("200", response.substr(9, 3));
  14948. }
  14949. TEST(MultipartFormDataTest, LargeHeader) {
  14950. auto handled = false;
  14951. Server svr;
  14952. svr.Post("/test", [&](const Request &req, Response &) {
  14953. ASSERT_EQ(1u, req.form.fields.size());
  14954. const auto &text = req.form.get_field("name1");
  14955. ASSERT_EQ("text1", text);
  14956. handled = true;
  14957. });
  14958. thread t = thread([&] { svr.listen(HOST, PORT); });
  14959. auto se = detail::scope_exit([&] {
  14960. svr.stop();
  14961. t.join();
  14962. ASSERT_FALSE(svr.is_running());
  14963. ASSERT_TRUE(handled);
  14964. });
  14965. svr.wait_until_ready();
  14966. auto boundary = std::string("cpp-httplib-multipart-data");
  14967. std::string content = "--" + boundary +
  14968. "\r\n"
  14969. "Content-Disposition: form-data; name=\"name1\"\r\n"
  14970. "\r\n"
  14971. "text1\r\n"
  14972. "--" +
  14973. boundary + "--\r\n";
  14974. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  14975. "Host: localhost\r\n"
  14976. "Content-Type: multipart/form-data;boundary=" +
  14977. boundary +
  14978. "\r\n"
  14979. "Content-Length: " +
  14980. std::to_string(content.size()) +
  14981. "\r\n"
  14982. "Dummy-Header: ";
  14983. std::string header_suffix = "\r\n"
  14984. "\r\n";
  14985. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  14986. size_t header_dummy_size =
  14987. read_buff_size -
  14988. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  14989. auto header_dummy = std::string(header_dummy_size, '@');
  14990. auto req = header_prefix + header_dummy + header_suffix + content;
  14991. std::string response;
  14992. ASSERT_TRUE(send_request(1, req, &response));
  14993. ASSERT_EQ("200", response.substr(9, 3));
  14994. }
  14995. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  14996. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  14997. // (not chunked Transfer-Encoding) after the streaming refactor.
  14998. auto handled = false;
  14999. Server svr;
  15000. svr.Post("/upload", [&](const Request &req, Response &res) {
  15001. auto cl_it = req.headers.find("Content-Length");
  15002. EXPECT_TRUE(cl_it != req.headers.end());
  15003. auto te_it = req.headers.find("Transfer-Encoding");
  15004. EXPECT_TRUE(te_it == req.headers.end());
  15005. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  15006. res.set_content("ok", "text/plain");
  15007. handled = true;
  15008. });
  15009. auto port = svr.bind_to_any_port(HOST);
  15010. auto t = thread([&] { svr.listen_after_bind(); });
  15011. auto se = detail::scope_exit([&] {
  15012. svr.stop();
  15013. t.join();
  15014. ASSERT_FALSE(svr.is_running());
  15015. ASSERT_TRUE(handled);
  15016. });
  15017. svr.wait_until_ready();
  15018. UploadFormDataItems items = {
  15019. {"field1", "hello", "", "text/plain"},
  15020. {"file1", "world", "test.txt", "application/octet-stream"},
  15021. };
  15022. Client cli(HOST, port);
  15023. auto res = cli.Post("/upload", {}, items);
  15024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15025. EXPECT_EQ(StatusCode::OK_200, res->status);
  15026. }
  15027. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  15028. // Verify that make_multipart_content_provider coalesces many small segments
  15029. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  15030. constexpr size_t kItemCount = 1000;
  15031. UploadFormDataItems items;
  15032. items.reserve(kItemCount);
  15033. for (size_t i = 0; i < kItemCount; i++) {
  15034. items.push_back(
  15035. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15036. }
  15037. const std::string boundary = "----test-boundary";
  15038. auto content_length = detail::get_multipart_content_length(items, boundary);
  15039. auto provider = detail::make_multipart_content_provider(items, boundary);
  15040. // Drive the provider the same way write_content_with_progress does
  15041. size_t write_count = 0;
  15042. size_t total_bytes = 0;
  15043. DataSink sink;
  15044. size_t offset = 0;
  15045. sink.write = [&](const char *d, size_t l) -> bool {
  15046. (void)d;
  15047. write_count++;
  15048. total_bytes += l;
  15049. offset += l;
  15050. return true;
  15051. };
  15052. sink.is_writable = []() -> bool { return true; };
  15053. while (offset < content_length) {
  15054. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  15055. }
  15056. EXPECT_EQ(content_length, total_bytes);
  15057. // The total number of segments is 3 * kItemCount + 1 = 3001.
  15058. // With buffering into 64KB blocks, write_count should be much smaller.
  15059. auto segment_count = 3 * kItemCount + 1;
  15060. EXPECT_LT(write_count, segment_count / 10);
  15061. }
  15062. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  15063. // Integration test: send many UploadFormDataItems and verify the server
  15064. // receives all of them correctly (#2410).
  15065. constexpr size_t kItemCount = 500;
  15066. auto handled = false;
  15067. Server svr;
  15068. svr.Post("/upload", [&](const Request &req, Response &res) {
  15069. EXPECT_EQ(kItemCount, req.form.fields.size());
  15070. for (size_t i = 0; i < kItemCount; i++) {
  15071. auto key = "field" + std::to_string(i);
  15072. auto val = "value" + std::to_string(i);
  15073. auto it = req.form.fields.find(key);
  15074. if (it != req.form.fields.end()) {
  15075. EXPECT_EQ(val, it->second.content);
  15076. } else {
  15077. ADD_FAILURE() << "Missing field: " << key;
  15078. }
  15079. }
  15080. res.set_content("ok", "text/plain");
  15081. handled = true;
  15082. });
  15083. auto port = svr.bind_to_any_port(HOST);
  15084. auto t = thread([&] { svr.listen_after_bind(); });
  15085. auto se = detail::scope_exit([&] {
  15086. svr.stop();
  15087. t.join();
  15088. ASSERT_FALSE(svr.is_running());
  15089. ASSERT_TRUE(handled);
  15090. });
  15091. svr.wait_until_ready();
  15092. UploadFormDataItems items;
  15093. items.reserve(kItemCount);
  15094. for (size_t i = 0; i < kItemCount; i++) {
  15095. items.push_back(
  15096. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  15097. }
  15098. Client cli(HOST, port);
  15099. auto res = cli.Post("/upload", items);
  15100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15101. EXPECT_EQ(StatusCode::OK_200, res->status);
  15102. }
  15103. TEST(MultipartFormDataTest, MakeFileProvider) {
  15104. // Verify make_file_provider sends a file's contents correctly.
  15105. const std::string file_content(4096, 'Z');
  15106. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  15107. {
  15108. std::ofstream ofs(tmp_path, std::ios::binary);
  15109. ofs.write(file_content.data(),
  15110. static_cast<std::streamsize>(file_content.size()));
  15111. }
  15112. auto handled = false;
  15113. Server svr;
  15114. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  15115. const ContentReader &content_reader) {
  15116. ASSERT_TRUE(req.is_multipart_form_data());
  15117. std::vector<FormData> items;
  15118. content_reader(
  15119. [&](const FormData &file) {
  15120. items.push_back(file);
  15121. return true;
  15122. },
  15123. [&](const char *data, size_t data_length) {
  15124. items.back().content.append(data, data_length);
  15125. return true;
  15126. });
  15127. ASSERT_EQ(1u, items.size());
  15128. EXPECT_EQ("myfile", items[0].name);
  15129. EXPECT_EQ("data.bin", items[0].filename);
  15130. EXPECT_EQ("application/octet-stream", items[0].content_type);
  15131. EXPECT_EQ(file_content, items[0].content);
  15132. handled = true;
  15133. });
  15134. auto port = svr.bind_to_any_port(HOST);
  15135. auto t = thread([&] { svr.listen_after_bind(); });
  15136. auto se = detail::scope_exit([&] {
  15137. svr.stop();
  15138. t.join();
  15139. ASSERT_FALSE(svr.is_running());
  15140. ASSERT_TRUE(handled);
  15141. std::remove(tmp_path.c_str());
  15142. });
  15143. svr.wait_until_ready();
  15144. FormDataProviderItems providers;
  15145. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  15146. "application/octet-stream"));
  15147. Client cli(HOST, port);
  15148. auto res = cli.Post("/upload", {}, {}, providers);
  15149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15150. EXPECT_EQ(StatusCode::OK_200, res->status);
  15151. }
  15152. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  15153. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  15154. // (100) headers is rejected with a 400 Bad Request response.
  15155. Server svr;
  15156. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15157. res.set_content("ok", "text/plain");
  15158. });
  15159. thread t = thread([&] { svr.listen(HOST, PORT); });
  15160. auto se = detail::scope_exit([&] {
  15161. svr.stop();
  15162. t.join();
  15163. ASSERT_FALSE(svr.is_running());
  15164. });
  15165. svr.wait_until_ready();
  15166. // Build a multipart part with 101 custom headers (exceeding
  15167. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  15168. std::stringstream body;
  15169. body << "--simpleboundary\r\n"
  15170. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  15171. for (int i = 0; i < 101; i++) {
  15172. body << "X-Custom-Header-" << i << ": value\r\n";
  15173. }
  15174. body << "\r\n"
  15175. << "value1\r\n"
  15176. << "--simpleboundary--\r\n";
  15177. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  15178. Client cli(HOST, PORT);
  15179. auto res = cli.Post("/post", body.str(), content_type.c_str());
  15180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15181. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15182. }
  15183. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  15184. // A body that never contains the declared boundary must not be accumulated
  15185. // while the parser waits for it. Buffering it would also make every read
  15186. // rescan everything seen so far, which is quadratic in the body size.
  15187. Server svr;
  15188. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15189. res.set_content("ok", "text/plain");
  15190. });
  15191. auto port = svr.bind_to_any_port(HOST);
  15192. thread t = thread([&] { svr.listen_after_bind(); });
  15193. auto se = detail::scope_exit([&] {
  15194. svr.stop();
  15195. t.join();
  15196. ASSERT_FALSE(svr.is_running());
  15197. });
  15198. svr.wait_until_ready();
  15199. Client cli(HOST, port);
  15200. cli.set_read_timeout(60, 0);
  15201. cli.set_write_timeout(60, 0);
  15202. // '-' is the worst case: it matches the first character of the boundary, so
  15203. // every position has to be checked against it.
  15204. auto post_dashes = [&](size_t size) {
  15205. const std::string body(size, '-');
  15206. auto start = std::chrono::steady_clock::now();
  15207. auto res =
  15208. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  15209. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  15210. std::chrono::steady_clock::now() - start)
  15211. .count();
  15212. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15213. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  15214. return ms;
  15215. };
  15216. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  15217. // Windows.
  15218. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  15219. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  15220. // Comparing the two sizes rather than checking an absolute duration keeps
  15221. // this meaningful across build types and CI load, both of which move the
  15222. // absolute numbers by more than an order of magnitude. Four times the bytes
  15223. // costs about four times the time when parsing is linear, and about sixteen
  15224. // times when the body is buffered and rescanned.
  15225. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  15226. EXPECT_LT(ms_16mb, ms_4mb * 10)
  15227. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  15228. << "ms, which suggests the body is being buffered and rescanned";
  15229. }
  15230. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  15231. // A boundary can only be followed by CRLF or by "--", so anything else is
  15232. // malformed no matter what comes next. The parser must say so right away
  15233. // instead of buffering the rest of the declared body.
  15234. Server svr;
  15235. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  15236. res.set_content("ok", "text/plain");
  15237. });
  15238. auto port = svr.bind_to_any_port(HOST);
  15239. thread t = thread([&] { svr.listen_after_bind(); });
  15240. auto se = detail::scope_exit([&] {
  15241. svr.stop();
  15242. t.join();
  15243. ASSERT_FALSE(svr.is_running());
  15244. });
  15245. svr.wait_until_ready();
  15246. // Announce a 1 MB body but send only the malformed prefix. A parser that
  15247. // buffers instead of failing would still be waiting for the remaining bytes.
  15248. const std::string body = "--zzzz\r\n"
  15249. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15250. "\r\n"
  15251. "text1"
  15252. "\r\n--zzzzXX";
  15253. const std::string req = "POST /post HTTP/1.1\r\n"
  15254. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15255. "Content-Length: 1048576\r\n"
  15256. "\r\n" +
  15257. body;
  15258. std::string response;
  15259. ASSERT_TRUE(send_request(3, req, &response, port));
  15260. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  15261. EXPECT_EQ("400", response.substr(9, 3));
  15262. }
  15263. // Posts a multipart body split into two writes, so that the server sees the
  15264. // split at whatever offset the caller chose, and expects the single "text1"
  15265. // field to come through.
  15266. static void expect_split_multipart_ok(const std::string &body1,
  15267. const std::string &body2) {
  15268. auto handled = false;
  15269. Server svr;
  15270. svr.Post("/post", [&](const Request &req, Response &) {
  15271. EXPECT_EQ(1u, req.form.fields.size());
  15272. EXPECT_EQ("text1", req.form.get_field("text1"));
  15273. handled = true;
  15274. });
  15275. auto port = svr.bind_to_any_port(HOST);
  15276. thread t = thread([&] { svr.listen_after_bind(); });
  15277. auto se = detail::scope_exit([&] {
  15278. svr.stop();
  15279. t.join();
  15280. ASSERT_FALSE(svr.is_running());
  15281. ASSERT_TRUE(handled);
  15282. });
  15283. svr.wait_until_ready();
  15284. // "Connection: close" makes the server close once it has answered, so the
  15285. // response drain ends immediately instead of idling until the read timeout.
  15286. const std::string head =
  15287. "POST /post HTTP/1.1\r\n"
  15288. "Host: localhost\r\n"
  15289. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  15290. "Connection: close\r\n"
  15291. "Content-Length: " +
  15292. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  15293. std::string response;
  15294. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  15295. ASSERT_GE(response.size(), 12u) << "no response";
  15296. EXPECT_EQ("200", response.substr(9, 3));
  15297. }
  15298. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  15299. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  15300. // ignored, including when it does not arrive in the same read as the
  15301. // close-delimiter itself.
  15302. expect_split_multipart_ok("--zzzz\r\n"
  15303. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15304. "\r\n"
  15305. "text1"
  15306. "\r\n--zzzz--",
  15307. "\r\nthis epilogue must be ignored\r\n");
  15308. }
  15309. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  15310. // The initial boundary may be preceded by a preamble of any length and may
  15311. // straddle a read boundary. Discarding data while waiting for it must not
  15312. // throw away a partial boundary sitting at the end of the buffer.
  15313. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  15314. "zz\r\n"
  15315. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15316. "\r\n"
  15317. "text1"
  15318. "\r\n--zzzz--\r\n");
  15319. }
  15320. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  15321. // The received boundary was only checked for being non-empty, so it could be
  15322. // as long as a header is allowed to be. The parser scans the body for
  15323. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  15324. // costs a nearly full comparison at nearly every position, making the
  15325. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  15326. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  15327. Server svr;
  15328. svr.Post("/post", [](const Request &req, Response &res) {
  15329. EXPECT_EQ(1u, req.form.fields.size());
  15330. EXPECT_EQ("text1", req.form.get_field("text1"));
  15331. res.set_content("ok", "text/plain");
  15332. });
  15333. auto port = svr.bind_to_any_port(HOST);
  15334. thread t = thread([&] { svr.listen_after_bind(); });
  15335. auto se = detail::scope_exit([&] {
  15336. svr.stop();
  15337. t.join();
  15338. ASSERT_FALSE(svr.is_running());
  15339. });
  15340. svr.wait_until_ready();
  15341. Client cli(HOST, port);
  15342. auto post_with_boundary_of_length = [&](size_t len) {
  15343. const std::string boundary(len, 'a');
  15344. const std::string body =
  15345. "--" + boundary +
  15346. "\r\n"
  15347. "Content-Disposition: form-data; name=\"text1\"\r\n"
  15348. "\r\n"
  15349. "text1"
  15350. "\r\n--" +
  15351. boundary + "--\r\n";
  15352. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  15353. };
  15354. auto res = post_with_boundary_of_length(70);
  15355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15356. EXPECT_EQ(StatusCode::OK_200, res->status);
  15357. res = post_with_boundary_of_length(71);
  15358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15359. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15360. }
  15361. TEST(MakeFileBodyTest, Basic) {
  15362. const std::string file_content(4096, 'Z');
  15363. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  15364. {
  15365. std::ofstream ofs(tmp_path, std::ios::binary);
  15366. ofs.write(file_content.data(),
  15367. static_cast<std::streamsize>(file_content.size()));
  15368. }
  15369. auto handled = false;
  15370. Server svr;
  15371. svr.Post("/upload", [&](const Request &req, Response &res) {
  15372. EXPECT_EQ(file_content, req.body);
  15373. handled = true;
  15374. res.status = StatusCode::OK_200;
  15375. });
  15376. auto port = svr.bind_to_any_port(HOST);
  15377. auto t = thread([&] { svr.listen_after_bind(); });
  15378. auto se = detail::scope_exit([&] {
  15379. svr.stop();
  15380. t.join();
  15381. ASSERT_FALSE(svr.is_running());
  15382. ASSERT_TRUE(handled);
  15383. std::remove(tmp_path.c_str());
  15384. });
  15385. svr.wait_until_ready();
  15386. auto fb = make_file_body(tmp_path);
  15387. ASSERT_GT(fb.first, 0u);
  15388. Client cli(HOST, port);
  15389. auto res =
  15390. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  15391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15392. EXPECT_EQ(StatusCode::OK_200, res->status);
  15393. }
  15394. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  15395. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  15396. {
  15397. std::ofstream ofs(path, std::ios::binary);
  15398. const std::string content(100, 'A');
  15399. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15400. }
  15401. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15402. auto body = make_file_body(path);
  15403. ASSERT_EQ(100u, body.first);
  15404. ASSERT_TRUE(static_cast<bool>(body.second));
  15405. // Rewritten shorter after its length was measured - and, on a server, after
  15406. // that length has already gone out as Content-Length.
  15407. {
  15408. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  15409. const std::string content(10, 'A');
  15410. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15411. }
  15412. std::string written;
  15413. DataSink sink;
  15414. sink.write = [&](const char *d, size_t l) {
  15415. written.append(d, l);
  15416. return true;
  15417. };
  15418. // The provider has to report failure. write_content_with_progress() advances
  15419. // its offset only by what was written, so a provider that returns true
  15420. // without completing the length it promised is called again straight away,
  15421. // and again.
  15422. EXPECT_FALSE(body.second(0, body.first, sink));
  15423. EXPECT_EQ(std::string(10, 'A'), written);
  15424. }
  15425. TEST(MakeFileBodyTest, WholeFileIsSent) {
  15426. const std::string path = "./httplib_test_make_file_body_whole.bin";
  15427. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  15428. {
  15429. std::ofstream ofs(path, std::ios::binary);
  15430. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  15431. }
  15432. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  15433. auto body = make_file_body(path);
  15434. ASSERT_EQ(content.size(), body.first);
  15435. ASSERT_TRUE(static_cast<bool>(body.second));
  15436. std::string written;
  15437. DataSink sink;
  15438. sink.write = [&](const char *d, size_t l) {
  15439. written.append(d, l);
  15440. return true;
  15441. };
  15442. EXPECT_TRUE(body.second(0, body.first, sink));
  15443. EXPECT_EQ(content, written);
  15444. }
  15445. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  15446. static constexpr unsigned int number_of_tasks{1000000};
  15447. std::atomic_uint count{0};
  15448. std::unique_ptr<TaskQueue> task_queue{
  15449. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  15450. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15451. auto queued = task_queue->enqueue(
  15452. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  15453. EXPECT_TRUE(queued);
  15454. }
  15455. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15456. task_queue->shutdown();
  15457. #else
  15458. EXPECT_NO_THROW(task_queue->shutdown());
  15459. #endif
  15460. EXPECT_EQ(number_of_tasks, count.load());
  15461. }
  15462. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  15463. static constexpr unsigned int number_of_tasks{1000000};
  15464. static constexpr unsigned int qlimit{2};
  15465. unsigned int queued_count{0};
  15466. std::atomic_uint count{0};
  15467. std::unique_ptr<TaskQueue> task_queue{
  15468. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  15469. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  15470. if (task_queue->enqueue(
  15471. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  15472. queued_count++;
  15473. }
  15474. }
  15475. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15476. task_queue->shutdown();
  15477. #else
  15478. EXPECT_NO_THROW(task_queue->shutdown());
  15479. #endif
  15480. EXPECT_EQ(queued_count, count.load());
  15481. EXPECT_TRUE(queued_count <= number_of_tasks);
  15482. EXPECT_TRUE(queued_count >= qlimit);
  15483. }
  15484. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  15485. // Use a short idle timeout so a dynamic thread spawns, times out and
  15486. // exits during the test, and the pool keeps working afterwards.
  15487. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  15488. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  15489. /*idle_timeout_sec=*/1}};
  15490. std::atomic_uint count{0};
  15491. std::condition_variable cv;
  15492. std::mutex mtx;
  15493. bool release = false;
  15494. // Block the base thread so the second task spawns a dynamic thread.
  15495. EXPECT_TRUE(task_queue->enqueue([&] {
  15496. std::unique_lock<std::mutex> lock(mtx);
  15497. while (!release) {
  15498. cv.wait(lock);
  15499. }
  15500. count++;
  15501. }));
  15502. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15503. // Let the dynamic thread finish its task and exceed the idle timeout.
  15504. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  15505. {
  15506. std::unique_lock<std::mutex> lock(mtx);
  15507. release = true;
  15508. }
  15509. cv.notify_all();
  15510. // The pool must still accept and run tasks after the dynamic thread exited.
  15511. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  15512. task_queue->shutdown();
  15513. EXPECT_EQ(3u, count.load());
  15514. }
  15515. TEST(TaskQueueTest, MaxQueuedRequests) {
  15516. static constexpr unsigned int qlimit{3};
  15517. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  15518. std::condition_variable sem_cv;
  15519. std::mutex sem_mtx;
  15520. int credits = 0;
  15521. bool queued;
  15522. /* Fill up the queue with tasks that will block until we give them credits to
  15523. * complete. */
  15524. for (unsigned int n = 0; n <= qlimit;) {
  15525. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  15526. std::unique_lock<std::mutex> lock(sem_mtx);
  15527. while (credits <= 0) {
  15528. sem_cv.wait(lock);
  15529. }
  15530. /* Consume the credit and signal the test code if they are all gone. */
  15531. if (--credits == 0) { sem_cv.notify_one(); }
  15532. });
  15533. if (n < qlimit) {
  15534. /* The first qlimit enqueues must succeed. */
  15535. EXPECT_TRUE(queued);
  15536. } else {
  15537. /* The last one will succeed only when the worker thread
  15538. * starts and dequeues the first blocking task. Although
  15539. * not necessary for the correctness of this test, we sleep for
  15540. * a short while to avoid busy waiting. */
  15541. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  15542. }
  15543. if (queued) { n++; }
  15544. }
  15545. /* Further enqueues must fail since the queue is full. */
  15546. for (auto i = 0; i < 4; i++) {
  15547. queued = task_queue->enqueue([] {});
  15548. EXPECT_FALSE(queued);
  15549. }
  15550. /* Give the credits to allow the previous tasks to complete. */
  15551. {
  15552. std::unique_lock<std::mutex> lock(sem_mtx);
  15553. credits += qlimit + 1;
  15554. }
  15555. sem_cv.notify_all();
  15556. /* Wait for all the credits to be consumed. */
  15557. {
  15558. std::unique_lock<std::mutex> lock(sem_mtx);
  15559. while (credits > 0) {
  15560. sem_cv.wait(lock);
  15561. }
  15562. }
  15563. /* Check that we are able again to enqueue at least qlimit tasks. */
  15564. for (unsigned int i = 0; i < qlimit; i++) {
  15565. queued = task_queue->enqueue([] {});
  15566. EXPECT_TRUE(queued);
  15567. }
  15568. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  15569. task_queue->shutdown();
  15570. #else
  15571. EXPECT_NO_THROW(task_queue->shutdown());
  15572. #endif
  15573. }
  15574. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  15575. Server svr;
  15576. std::string method;
  15577. std::string body;
  15578. auto has_content_length = false;
  15579. auto has_transfer_encoding = false;
  15580. std::atomic<int> bad_requests{0};
  15581. // Leftover body bytes get parsed as a malformed request and answered with
  15582. // 400
  15583. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  15584. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  15585. });
  15586. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  15587. res.set_redirect("/down", StatusCode::SeeOther_303);
  15588. });
  15589. svr.Get("/down", [&](const Request &req, Response &res) {
  15590. method = req.method;
  15591. body = req.body;
  15592. has_content_length = req.has_header("Content-Length");
  15593. has_transfer_encoding = req.has_header("Transfer-Encoding");
  15594. res.set_content("ok", "text/plain");
  15595. });
  15596. auto port = svr.bind_to_any_port(HOST);
  15597. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15598. auto se = detail::scope_exit([&] {
  15599. svr.stop();
  15600. thread.join();
  15601. ASSERT_FALSE(svr.is_running());
  15602. });
  15603. svr.wait_until_ready();
  15604. const std::string payload = "SECRET-BODY";
  15605. auto check = [&](Client &cli, const Result &res) {
  15606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15607. EXPECT_EQ(StatusCode::OK_200, res->status);
  15608. EXPECT_EQ("ok", res->body);
  15609. EXPECT_EQ("GET", method);
  15610. EXPECT_TRUE(body.empty());
  15611. EXPECT_FALSE(has_content_length);
  15612. EXPECT_FALSE(has_transfer_encoding);
  15613. // Nothing of the original body may be left on the connection
  15614. auto res2 = cli.Get("/down");
  15615. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  15616. EXPECT_EQ(StatusCode::OK_200, res2->status);
  15617. EXPECT_EQ("ok", res2->body);
  15618. EXPECT_EQ(0, bad_requests);
  15619. };
  15620. // With content length
  15621. {
  15622. Client cli(HOST, port);
  15623. cli.set_keep_alive(true);
  15624. cli.set_follow_location(true);
  15625. auto res = cli.Post(
  15626. "/up", payload.size(),
  15627. [&](size_t offset, size_t length, DataSink &sink) {
  15628. return sink.write(payload.data() + offset, length);
  15629. },
  15630. "text/plain");
  15631. check(cli, res);
  15632. }
  15633. // Without content length (chunked)
  15634. {
  15635. Client cli(HOST, port);
  15636. cli.set_keep_alive(true);
  15637. cli.set_follow_location(true);
  15638. auto res = cli.Post(
  15639. "/up",
  15640. [&](size_t /*offset*/, DataSink &sink) {
  15641. sink.write(payload.data(), payload.size());
  15642. sink.done();
  15643. return true;
  15644. },
  15645. "text/plain");
  15646. check(cli, res);
  15647. }
  15648. }
  15649. TEST(RedirectTest, LocationPathIsNotDecoded) {
  15650. Server svr;
  15651. std::string target;
  15652. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  15653. // Echo the still-encoded name back in the Location
  15654. const std::string prefix = "/start/";
  15655. res.status = StatusCode::Found_302;
  15656. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  15657. });
  15658. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  15659. target = req.target;
  15660. res.set_content("ok", "text/plain");
  15661. });
  15662. auto port = svr.bind_to_any_port(HOST);
  15663. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15664. auto se = detail::scope_exit([&] {
  15665. svr.stop();
  15666. thread.join();
  15667. ASSERT_FALSE(svr.is_running());
  15668. });
  15669. svr.wait_until_ready();
  15670. // Decoding the Location path would turn the first four into a path
  15671. // separator, a query delimiter, a fragment delimiter and a different
  15672. // percent-encoded octet. The rest must keep reaching the server as they are.
  15673. const std::vector<std::string> names = {
  15674. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  15675. };
  15676. for (auto path_encode : {true, false}) {
  15677. Client cli(HOST, port);
  15678. cli.set_follow_location(true);
  15679. cli.set_path_encode(path_encode);
  15680. for (const auto &name : names) {
  15681. target.clear();
  15682. auto res = cli.Get("/start/" + name);
  15683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15684. EXPECT_EQ(StatusCode::OK_200, res->status);
  15685. EXPECT_EQ("/dest/" + name, target);
  15686. }
  15687. }
  15688. }
  15689. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  15690. Server svr;
  15691. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15692. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  15693. });
  15694. svr.Get("/hello", [](const Request &req, Response &res) {
  15695. res.set_content(req.get_param_value("key"), "text/plain");
  15696. });
  15697. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15698. auto se = detail::scope_exit([&] {
  15699. svr.stop();
  15700. thread.join();
  15701. ASSERT_FALSE(svr.is_running());
  15702. });
  15703. svr.wait_until_ready();
  15704. {
  15705. Client cli(HOST, PORT);
  15706. cli.set_follow_location(true);
  15707. auto res = cli.Get("/");
  15708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15709. EXPECT_EQ(StatusCode::OK_200, res->status);
  15710. EXPECT_EQ("val&key2=val2", res->body);
  15711. }
  15712. }
  15713. #endif
  15714. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  15715. Server svr;
  15716. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15717. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  15718. });
  15719. svr.Get("/hello", [](const Request &req, Response &res) {
  15720. res.set_content(req.get_param_value("key"), "text/plain");
  15721. });
  15722. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15723. auto se = detail::scope_exit([&] {
  15724. svr.stop();
  15725. thread.join();
  15726. ASSERT_FALSE(svr.is_running());
  15727. });
  15728. svr.wait_until_ready();
  15729. {
  15730. Client cli(HOST, PORT);
  15731. cli.set_follow_location(true);
  15732. auto res = cli.Get("/");
  15733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15734. EXPECT_EQ(StatusCode::OK_200, res->status);
  15735. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  15736. }
  15737. }
  15738. TEST(RedirectTest, RedirectWithPlusInPath) {
  15739. Server svr;
  15740. svr.Get("/", [](const Request & /*req*/, Response &res) {
  15741. res.set_redirect("/a+b");
  15742. });
  15743. // Route pattern uses regex; escape + as \\+
  15744. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  15745. res.set_content(req.path, "text/plain");
  15746. });
  15747. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15748. auto se = detail::scope_exit([&] {
  15749. svr.stop();
  15750. thread.join();
  15751. ASSERT_FALSE(svr.is_running());
  15752. });
  15753. svr.wait_until_ready();
  15754. {
  15755. Client cli(HOST, PORT);
  15756. cli.set_follow_location(true);
  15757. auto res = cli.Get("/");
  15758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15759. EXPECT_EQ(StatusCode::OK_200, res->status);
  15760. EXPECT_EQ("/a+b", res->body);
  15761. }
  15762. }
  15763. TEST(RedirectTest, ResolveRelativeLocation) {
  15764. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  15765. const std::vector<std::pair<std::string, std::string>> cases = {
  15766. {"g", "/b/c/g"},
  15767. {"./g", "/b/c/g"},
  15768. {"g/", "/b/c/g/"},
  15769. {"?y", "/b/c/d;p?y"},
  15770. {"g?y", "/b/c/g?y"},
  15771. {"#s", "/b/c/d;p?q#s"},
  15772. {"g#s", "/b/c/g#s"},
  15773. {"g?y#s", "/b/c/g?y#s"},
  15774. {";x", "/b/c/;x"},
  15775. {"g;x", "/b/c/g;x"},
  15776. {".", "/b/c/"},
  15777. {"./", "/b/c/"},
  15778. {"..", "/b/"},
  15779. {"../", "/b/"},
  15780. {"../g", "/b/g"},
  15781. {"../..", "/"},
  15782. {"../../", "/"},
  15783. {"../../g", "/g"},
  15784. {"../../../g", "/g"},
  15785. {"g.", "/b/c/g."},
  15786. {".g", "/b/c/.g"},
  15787. {"g..", "/b/c/g.."},
  15788. {"..g", "/b/c/..g"},
  15789. {"./../g", "/b/g"},
  15790. {"./g/.", "/b/c/g/"},
  15791. {"g/./h", "/b/c/g/h"},
  15792. {"g/../h", "/b/c/h"},
  15793. {"g;x=1/./y", "/b/c/g;x=1/y"},
  15794. {"g;x=1/../y", "/b/c/y"},
  15795. {"g?y/./x", "/b/c/g?y/./x"},
  15796. {"g#s/../x", "/b/c/g#s/../x"},
  15797. // Not relative-path references, so left for parse_url.
  15798. {"/g", "/g"},
  15799. {"//g", "//g"},
  15800. {"http://g/x", "http://g/x"},
  15801. {"g:h", "g:h"},
  15802. };
  15803. for (const auto &c : cases) {
  15804. EXPECT_EQ(c.second,
  15805. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  15806. << c.first;
  15807. }
  15808. }
  15809. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  15810. Server svr;
  15811. svr.Get("/dir/page", [](const Request &req, Response &res) {
  15812. res.set_redirect(req.get_param_value("to"));
  15813. });
  15814. svr.Get("/dir/next", [](const Request &req, Response &res) {
  15815. res.set_content(req.target, "text/plain");
  15816. });
  15817. svr.Get("/other", [](const Request &req, Response &res) {
  15818. res.set_content(req.target, "text/plain");
  15819. });
  15820. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15821. auto se = detail::scope_exit([&] {
  15822. svr.stop();
  15823. thread.join();
  15824. ASSERT_FALSE(svr.is_running());
  15825. });
  15826. svr.wait_until_ready();
  15827. const std::vector<std::pair<std::string, std::string>> cases = {
  15828. {"next", "/dir/next"},
  15829. {"./next?x=1", "/dir/next?x=1"},
  15830. {"../other", "/other"},
  15831. };
  15832. for (const auto &c : cases) {
  15833. Client cli(HOST, PORT);
  15834. cli.set_follow_location(true);
  15835. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  15836. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  15837. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  15838. EXPECT_EQ(c.second, res->body) << c.first;
  15839. }
  15840. }
  15841. #ifdef CPPHTTPLIB_SSL_ENABLED
  15842. TEST(RedirectTest, Issue2185_Online) {
  15843. SSLClient client("github.com");
  15844. client.set_follow_location(true);
  15845. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  15846. "Coollab-Windows.zip");
  15847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15848. EXPECT_EQ(StatusCode::OK_200, res->status);
  15849. EXPECT_EQ(9920427U, res->body.size());
  15850. }
  15851. #endif
  15852. TEST(VulnerabilityTest, CRLFInjection) {
  15853. Server svr;
  15854. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  15855. res.set_content("Hello 1", "text/plain");
  15856. });
  15857. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  15858. res.set_content("Hello 2", "text/plain");
  15859. });
  15860. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  15861. res.set_content("Hello 3", "text/plain");
  15862. });
  15863. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  15864. res.set_content("Hello 4", "text/plain");
  15865. });
  15866. svr.set_logger([](const Request &req, const Response & /*res*/) {
  15867. for (const auto &x : req.headers) {
  15868. auto key = x.first;
  15869. EXPECT_STRNE("evil", key.c_str());
  15870. }
  15871. });
  15872. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15873. auto se = detail::scope_exit([&] {
  15874. svr.stop();
  15875. thread.join();
  15876. ASSERT_FALSE(svr.is_running());
  15877. });
  15878. svr.wait_until_ready();
  15879. {
  15880. Client cli(HOST, PORT);
  15881. cli.Post("/test1", "A=B",
  15882. "application/x-www-form-urlencoded\r\nevil: hello1");
  15883. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  15884. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  15885. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  15886. }
  15887. }
  15888. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  15889. auto server_thread = std::thread([] {
  15890. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15891. default_socket_options(srv);
  15892. sockaddr_in addr{};
  15893. addr.sin_family = AF_INET;
  15894. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15895. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15896. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  15897. ::listen(srv, 1);
  15898. sockaddr_in cli_addr{};
  15899. socklen_t cli_len = sizeof(cli_addr);
  15900. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15901. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  15902. std::string buf_all;
  15903. char buf[2048];
  15904. ssize_t n;
  15905. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  15906. buf_all.append(buf, static_cast<size_t>(n));
  15907. size_t pos;
  15908. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  15909. auto request_block = buf_all.substr(0, pos + 4); // include separator
  15910. auto e = request_block.find("\r\n");
  15911. if (e != std::string::npos) {
  15912. auto request_line = request_block.substr(0, e);
  15913. std::string msg =
  15914. "CRLF injection detected in request line: '" + request_line + "'";
  15915. EXPECT_FALSE(true) << msg;
  15916. }
  15917. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  15918. ::send(cli,
  15919. #ifdef _WIN32
  15920. static_cast<const char *>(resp.c_str()),
  15921. static_cast<int>(resp.size()),
  15922. #else
  15923. resp.c_str(), resp.size(),
  15924. #endif
  15925. 0);
  15926. buf_all.erase(0, pos + 4);
  15927. }
  15928. }
  15929. detail::close_socket(cli);
  15930. detail::close_socket(srv);
  15931. });
  15932. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  15933. auto cli = Client("127.0.0.1", PORT + 1);
  15934. auto headers = Headers{
  15935. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  15936. {"Connection", "keep-alive"}};
  15937. auto res = cli.Get("/hi", headers);
  15938. EXPECT_FALSE(res);
  15939. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15940. server_thread.join();
  15941. }
  15942. // A request rejected before any byte reaches the socket must fail right away
  15943. // instead of waiting for a response the server will never send.
  15944. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  15945. // The kernel completes the TCP handshake from the listen backlog, so the
  15946. // client connects, but nothing ever reads, responds or closes.
  15947. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15948. default_socket_options(srv);
  15949. sockaddr_in addr{};
  15950. addr.sin_family = AF_INET;
  15951. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15952. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15953. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15954. ASSERT_EQ(0, ::listen(srv, 8));
  15955. auto cli = Client("127.0.0.1", PORT + 1);
  15956. cli.set_read_timeout(10, 0);
  15957. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  15958. return std::chrono::duration_cast<std::chrono::milliseconds>(
  15959. std::chrono::steady_clock::now() - start)
  15960. .count();
  15961. };
  15962. {
  15963. Request req;
  15964. req.method = "GE T";
  15965. req.path = "/";
  15966. auto start = std::chrono::steady_clock::now();
  15967. auto res = cli.send(req);
  15968. EXPECT_FALSE(res);
  15969. EXPECT_EQ(Error::Write, res.error());
  15970. EXPECT_LT(elapsed_ms(start), 1000);
  15971. }
  15972. {
  15973. auto start = std::chrono::steady_clock::now();
  15974. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  15975. EXPECT_FALSE(res);
  15976. EXPECT_EQ(Error::InvalidHeaders, res.error());
  15977. EXPECT_LT(elapsed_ms(start), 1000);
  15978. }
  15979. EXPECT_FALSE(cli.is_socket_open());
  15980. detail::close_socket(srv);
  15981. }
  15982. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  15983. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15984. default_socket_options(srv);
  15985. sockaddr_in addr{};
  15986. addr.sin_family = AF_INET;
  15987. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  15988. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15989. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15990. ASSERT_EQ(0, ::listen(srv, 1));
  15991. std::string received;
  15992. auto server_thread = std::thread([&] {
  15993. auto sock = ::accept(srv, nullptr, nullptr);
  15994. if (sock == INVALID_SOCKET) { return; }
  15995. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  15996. char buf[2048];
  15997. ssize_t n;
  15998. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  15999. received.append(buf, static_cast<size_t>(n));
  16000. }
  16001. detail::close_socket(sock);
  16002. });
  16003. {
  16004. auto cli = Client("127.0.0.1", PORT + 1);
  16005. // "Z" sorts after the default headers, so writing straight to the socket
  16006. // would have sent the request line and those headers before the rejection.
  16007. auto handle =
  16008. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  16009. EXPECT_FALSE(handle.is_valid());
  16010. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  16011. }
  16012. server_thread.join();
  16013. detail::close_socket(srv);
  16014. EXPECT_TRUE(received.empty()) << received;
  16015. }
  16016. TEST(PathParamsTest, StaticMatch) {
  16017. const auto pattern = "/users/all";
  16018. detail::PathParamsMatcher matcher(pattern);
  16019. Request request;
  16020. request.path = "/users/all";
  16021. ASSERT_TRUE(matcher.match(request));
  16022. std::unordered_map<std::string, std::string> expected_params = {};
  16023. EXPECT_EQ(request.path_params, expected_params);
  16024. }
  16025. TEST(PathParamsTest, StaticMismatch) {
  16026. const auto pattern = "/users/all";
  16027. detail::PathParamsMatcher matcher(pattern);
  16028. Request request;
  16029. request.path = "/users/1";
  16030. ASSERT_FALSE(matcher.match(request));
  16031. }
  16032. TEST(PathParamsTest, SingleParamInTheMiddle) {
  16033. const auto pattern = "/users/:id/subscriptions";
  16034. detail::PathParamsMatcher matcher(pattern);
  16035. Request request;
  16036. request.path = "/users/42/subscriptions";
  16037. ASSERT_TRUE(matcher.match(request));
  16038. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16039. EXPECT_EQ(request.path_params, expected_params);
  16040. }
  16041. TEST(PathParamsTest, SingleParamInTheEnd) {
  16042. const auto pattern = "/users/:id";
  16043. detail::PathParamsMatcher matcher(pattern);
  16044. Request request;
  16045. request.path = "/users/24";
  16046. ASSERT_TRUE(matcher.match(request));
  16047. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  16048. EXPECT_EQ(request.path_params, expected_params);
  16049. }
  16050. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  16051. const auto pattern = "/users/:id/";
  16052. detail::PathParamsMatcher matcher(pattern);
  16053. Request request;
  16054. request.path = "/users/42/";
  16055. ASSERT_TRUE(matcher.match(request));
  16056. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  16057. EXPECT_EQ(request.path_params, expected_params);
  16058. }
  16059. TEST(PathParamsTest, EmptyParam) {
  16060. const auto pattern = "/users/:id/";
  16061. detail::PathParamsMatcher matcher(pattern);
  16062. Request request;
  16063. request.path = "/users//";
  16064. ASSERT_TRUE(matcher.match(request));
  16065. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  16066. EXPECT_EQ(request.path_params, expected_params);
  16067. }
  16068. TEST(PathParamsTest, FragmentMismatch) {
  16069. const auto pattern = "/users/:id/";
  16070. detail::PathParamsMatcher matcher(pattern);
  16071. Request request;
  16072. request.path = "/admins/24/";
  16073. ASSERT_FALSE(matcher.match(request));
  16074. }
  16075. TEST(PathParamsTest, ExtraFragments) {
  16076. const auto pattern = "/users/:id";
  16077. detail::PathParamsMatcher matcher(pattern);
  16078. Request request;
  16079. request.path = "/users/42/subscriptions";
  16080. ASSERT_FALSE(matcher.match(request));
  16081. }
  16082. TEST(PathParamsTest, MissingTrailingParam) {
  16083. const auto pattern = "/users/:id";
  16084. detail::PathParamsMatcher matcher(pattern);
  16085. Request request;
  16086. request.path = "/users";
  16087. ASSERT_FALSE(matcher.match(request));
  16088. }
  16089. TEST(PathParamsTest, MissingParamInTheMiddle) {
  16090. const auto pattern = "/users/:id/subscriptions";
  16091. detail::PathParamsMatcher matcher(pattern);
  16092. Request request;
  16093. request.path = "/users/subscriptions";
  16094. ASSERT_FALSE(matcher.match(request));
  16095. }
  16096. TEST(PathParamsTest, MultipleParams) {
  16097. const auto pattern = "/users/:userid/subscriptions/:subid";
  16098. detail::PathParamsMatcher matcher(pattern);
  16099. Request request;
  16100. request.path = "/users/42/subscriptions/2";
  16101. ASSERT_TRUE(matcher.match(request));
  16102. std::unordered_map<std::string, std::string> expected_params = {
  16103. {"userid", "42"}, {"subid", "2"}};
  16104. EXPECT_EQ(request.path_params, expected_params);
  16105. }
  16106. TEST(PathParamsTest, SequenceOfParams) {
  16107. const auto pattern = "/values/:x/:y/:z";
  16108. detail::PathParamsMatcher matcher(pattern);
  16109. Request request;
  16110. request.path = "/values/1/2/3";
  16111. ASSERT_TRUE(matcher.match(request));
  16112. std::unordered_map<std::string, std::string> expected_params = {
  16113. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  16114. EXPECT_EQ(request.path_params, expected_params);
  16115. }
  16116. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  16117. const auto pattern = "/prefix:suffix";
  16118. detail::PathParamsMatcher matcher(pattern);
  16119. Request request;
  16120. request.path = "/prefix:suffix";
  16121. ASSERT_TRUE(matcher.match(request));
  16122. const std::unordered_map<std::string, std::string> expected_params = {};
  16123. EXPECT_EQ(request.path_params, expected_params);
  16124. }
  16125. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  16126. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  16127. // calling thread's stack on a long enough path for a quantified pattern;
  16128. // RegexMatcher must refuse to run regex matching on paths beyond
  16129. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  16130. detail::RegexMatcher matcher("/files/(.*)");
  16131. Request within_limit;
  16132. within_limit.path = "/files/" + std::string(10, 'A');
  16133. EXPECT_TRUE(matcher.match(within_limit));
  16134. Request over_limit;
  16135. over_limit.path =
  16136. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  16137. EXPECT_FALSE(matcher.match(over_limit));
  16138. }
  16139. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  16140. Server svr;
  16141. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  16142. res.set_content("ok", "text/plain");
  16143. });
  16144. auto port = svr.bind_to_any_port(HOST);
  16145. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16146. auto se = detail::scope_exit([&] {
  16147. svr.stop();
  16148. thread.join();
  16149. ASSERT_FALSE(svr.is_running());
  16150. });
  16151. svr.wait_until_ready();
  16152. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  16153. // request URI limit; this used to be able to crash the process.
  16154. std::string path =
  16155. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  16156. std::string req = "GET " + path +
  16157. " HTTP/1.1\r\n"
  16158. "Host: " +
  16159. std::string(HOST) + ":" + std::to_string(port) +
  16160. "\r\n"
  16161. "Connection: close\r\n"
  16162. "\r\n";
  16163. std::string response;
  16164. ASSERT_TRUE(send_request(5, req, &response, port));
  16165. EXPECT_NE(std::string::npos, response.find("404"));
  16166. }
  16167. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  16168. Server svr;
  16169. auto handler = [](const Request & /*req*/, Response &res) {
  16170. res.set_content("hit", "text/plain");
  16171. };
  16172. // No regex metacharacter, so this one is compared literally
  16173. svr.Get("/literal/route", handler);
  16174. // '.' is a regex metacharacter, so this one must keep regex semantics
  16175. svr.Get("/a.c", handler);
  16176. auto port = svr.bind_to_any_port(HOST);
  16177. std::thread t([&]() { svr.listen_after_bind(); });
  16178. auto se = detail::scope_exit([&] {
  16179. svr.stop();
  16180. t.join();
  16181. ASSERT_FALSE(svr.is_running());
  16182. });
  16183. svr.wait_until_ready();
  16184. Client cli(HOST, port);
  16185. struct {
  16186. const char *path;
  16187. int status;
  16188. } cases[] = {
  16189. {"/literal/route", StatusCode::OK_200},
  16190. {"/literal/routes", StatusCode::NotFound_404},
  16191. {"/literal/rout", StatusCode::NotFound_404},
  16192. {"/abc", StatusCode::OK_200},
  16193. {"/a.c", StatusCode::OK_200},
  16194. };
  16195. for (const auto &x : cases) {
  16196. auto res = cli.Get(x.path);
  16197. ASSERT_TRUE(res) << x.path;
  16198. EXPECT_EQ(x.status, res->status) << x.path;
  16199. }
  16200. }
  16201. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  16202. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  16203. // from exhausting the stack, so it must only constrain routes that actually
  16204. // run a regular expression. A literal route is matched by comparison and
  16205. // stays usable at any length.
  16206. Server svr;
  16207. const std::string pattern =
  16208. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  16209. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  16210. res.set_content("hit", "text/plain");
  16211. });
  16212. auto port = svr.bind_to_any_port(HOST);
  16213. std::thread t([&]() { svr.listen_after_bind(); });
  16214. auto se = detail::scope_exit([&] {
  16215. svr.stop();
  16216. t.join();
  16217. ASSERT_FALSE(svr.is_running());
  16218. });
  16219. svr.wait_until_ready();
  16220. Client cli(HOST, port);
  16221. auto res = cli.Get(pattern);
  16222. ASSERT_TRUE(res);
  16223. EXPECT_EQ(StatusCode::OK_200, res->status);
  16224. }
  16225. TEST(ParseUrlTest, VariousPatterns) {
  16226. {
  16227. detail::UrlComponents uc;
  16228. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  16229. EXPECT_EQ("http", uc.scheme);
  16230. EXPECT_EQ("example.com", uc.host);
  16231. EXPECT_EQ("8080", uc.port);
  16232. EXPECT_EQ("/path", uc.path);
  16233. EXPECT_EQ("?q=1", uc.query);
  16234. }
  16235. {
  16236. detail::UrlComponents uc;
  16237. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  16238. EXPECT_EQ("https", uc.scheme);
  16239. EXPECT_EQ("example.com", uc.host);
  16240. EXPECT_TRUE(uc.port.empty());
  16241. EXPECT_EQ("/path", uc.path);
  16242. }
  16243. {
  16244. detail::UrlComponents uc;
  16245. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  16246. EXPECT_EQ("::1", uc.host);
  16247. EXPECT_EQ("8080", uc.port);
  16248. EXPECT_EQ("/path", uc.path);
  16249. }
  16250. {
  16251. detail::UrlComponents uc;
  16252. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  16253. }
  16254. {
  16255. // Bytes after the IPv6 literal must be a delimiter, not folded into
  16256. // the path while the connection still targets the bracketed host.
  16257. detail::UrlComponents uc;
  16258. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  16259. }
  16260. {
  16261. detail::UrlComponents uc;
  16262. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  16263. }
  16264. {
  16265. detail::UrlComponents uc;
  16266. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  16267. EXPECT_EQ("::1", uc.host);
  16268. EXPECT_TRUE(uc.port.empty());
  16269. EXPECT_EQ("/path", uc.path);
  16270. }
  16271. {
  16272. detail::UrlComponents uc;
  16273. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  16274. EXPECT_TRUE(uc.scheme.empty());
  16275. EXPECT_EQ("example.com", uc.host);
  16276. EXPECT_EQ("/path", uc.path);
  16277. EXPECT_EQ("?q=1", uc.query);
  16278. }
  16279. {
  16280. detail::UrlComponents uc;
  16281. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  16282. EXPECT_TRUE(uc.host.empty());
  16283. EXPECT_EQ("/path", uc.path);
  16284. EXPECT_EQ("?q=1", uc.query);
  16285. }
  16286. {
  16287. detail::UrlComponents uc;
  16288. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  16289. EXPECT_EQ("example.com", uc.host);
  16290. EXPECT_EQ("8080", uc.port);
  16291. }
  16292. {
  16293. // Unix socket path — must not be parsed as host
  16294. detail::UrlComponents uc;
  16295. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  16296. EXPECT_TRUE(uc.host.empty());
  16297. }
  16298. {
  16299. detail::UrlComponents uc;
  16300. ASSERT_TRUE(detail::parse_url("", uc));
  16301. EXPECT_TRUE(uc.host.empty());
  16302. EXPECT_TRUE(uc.path.empty());
  16303. }
  16304. {
  16305. detail::UrlComponents uc;
  16306. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  16307. }
  16308. {
  16309. detail::UrlComponents uc;
  16310. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  16311. }
  16312. {
  16313. // Accepted by parse_url; callers restrict to http/https
  16314. detail::UrlComponents uc;
  16315. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  16316. EXPECT_EQ("ftp", uc.scheme);
  16317. }
  16318. {
  16319. detail::UrlComponents uc;
  16320. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  16321. }
  16322. {
  16323. detail::UrlComponents uc;
  16324. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  16325. }
  16326. }
  16327. TEST(ParseUrlTest, FragmentHandling) {
  16328. {
  16329. detail::UrlComponents uc;
  16330. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  16331. EXPECT_EQ("/path", uc.path);
  16332. EXPECT_TRUE(uc.query.empty());
  16333. }
  16334. {
  16335. detail::UrlComponents uc;
  16336. ASSERT_TRUE(detail::parse_url("#frag", uc));
  16337. EXPECT_TRUE(uc.path.empty());
  16338. EXPECT_TRUE(uc.query.empty());
  16339. }
  16340. }
  16341. TEST(ParseUrlTest, UserinfoHandling) {
  16342. // Userinfo with @ but no colon — host includes @
  16343. detail::UrlComponents uc;
  16344. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  16345. EXPECT_EQ("user@host.com", uc.host);
  16346. EXPECT_EQ("/path", uc.path);
  16347. }
  16348. TEST(ParseUrlTest, IPv6EdgeCases) {
  16349. {
  16350. detail::UrlComponents uc;
  16351. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  16352. EXPECT_TRUE(uc.scheme.empty());
  16353. EXPECT_EQ("::1", uc.host);
  16354. EXPECT_EQ("8080", uc.port);
  16355. }
  16356. {
  16357. // Zone ID '%25' is not in [a-fA-F0-9:]
  16358. detail::UrlComponents uc;
  16359. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  16360. }
  16361. }
  16362. TEST(ParseUrlTest, SchemeEdgeCases) {
  16363. {
  16364. detail::UrlComponents uc;
  16365. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  16366. }
  16367. {
  16368. detail::UrlComponents uc;
  16369. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  16370. }
  16371. {
  16372. detail::UrlComponents uc;
  16373. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  16374. }
  16375. }
  16376. TEST(ParseUrlTest, PortEdgeCases) {
  16377. {
  16378. detail::UrlComponents uc;
  16379. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  16380. EXPECT_TRUE(uc.port.empty());
  16381. EXPECT_EQ("/path", uc.path);
  16382. }
  16383. {
  16384. // parse_url accepts any port string; validation is done by parse_port
  16385. detail::UrlComponents uc;
  16386. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  16387. EXPECT_EQ("abc", uc.port);
  16388. }
  16389. }
  16390. TEST(ParseUrlTest, WebSocketPatterns) {
  16391. {
  16392. detail::UrlComponents uc;
  16393. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  16394. EXPECT_EQ("ws", uc.scheme);
  16395. EXPECT_EQ("echo.example.com", uc.host);
  16396. EXPECT_EQ("8080", uc.port);
  16397. EXPECT_EQ("/ws", uc.path);
  16398. }
  16399. {
  16400. detail::UrlComponents uc;
  16401. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  16402. EXPECT_EQ("wss", uc.scheme);
  16403. EXPECT_EQ("echo.example.com", uc.host);
  16404. EXPECT_TRUE(uc.port.empty());
  16405. EXPECT_EQ("/ws", uc.path);
  16406. }
  16407. }
  16408. TEST(ParseUrlTest, QueryOnly) {
  16409. detail::UrlComponents uc;
  16410. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  16411. EXPECT_TRUE(uc.host.empty());
  16412. EXPECT_TRUE(uc.path.empty());
  16413. EXPECT_EQ("?q=1&r=2", uc.query);
  16414. }
  16415. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  16416. detail::UrlComponents uc;
  16417. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  16418. EXPECT_TRUE(uc.scheme.empty());
  16419. EXPECT_EQ("example.com", uc.host);
  16420. EXPECT_EQ("443", uc.port);
  16421. EXPECT_EQ("/path", uc.path);
  16422. }
  16423. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  16424. // If ipv6 regex working, regex match codepath is taken.
  16425. // else port will default to 80 in Client impl
  16426. int clientImplMagicPort = 80;
  16427. int port = 4321;
  16428. // above ports must be different to avoid false negative
  16429. EXPECT_NE(clientImplMagicPort, port);
  16430. std::string ipV6TestURL = "http://[ff06::c3]";
  16431. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  16432. CLIENT_PRIVATE_KEY_FILE);
  16433. EXPECT_EQ(cli.port(), port);
  16434. }
  16435. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  16436. auto file_path = "./www/dir/index.html";
  16437. auto dir_path = "./www/dir";
  16438. detail::FileStat stat_file(file_path);
  16439. EXPECT_TRUE(stat_file.is_file());
  16440. EXPECT_FALSE(stat_file.is_dir());
  16441. detail::FileStat stat_dir(dir_path);
  16442. EXPECT_FALSE(stat_dir.is_file());
  16443. EXPECT_TRUE(stat_dir.is_dir());
  16444. }
  16445. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  16446. // IPv4 with default HTTP port (80)
  16447. EXPECT_EQ("example.com",
  16448. detail::make_host_and_port_string("example.com", 80, false));
  16449. // IPv4 with default HTTPS port (443)
  16450. EXPECT_EQ("example.com",
  16451. detail::make_host_and_port_string("example.com", 443, true));
  16452. // IPv4 with non-default HTTP port
  16453. EXPECT_EQ("example.com:8080",
  16454. detail::make_host_and_port_string("example.com", 8080, false));
  16455. // IPv4 with non-default HTTPS port
  16456. EXPECT_EQ("example.com:8443",
  16457. detail::make_host_and_port_string("example.com", 8443, true));
  16458. // IPv6 with default HTTP port (80)
  16459. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  16460. // IPv6 with default HTTPS port (443)
  16461. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  16462. // IPv6 with non-default HTTP port
  16463. EXPECT_EQ("[::1]:8080",
  16464. detail::make_host_and_port_string("::1", 8080, false));
  16465. // IPv6 with non-default HTTPS port
  16466. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  16467. // IPv6 full address with default port
  16468. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  16469. detail::make_host_and_port_string(
  16470. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  16471. // IPv6 full address with non-default port
  16472. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  16473. detail::make_host_and_port_string(
  16474. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  16475. // IPv6 localhost with non-default port
  16476. EXPECT_EQ("[::1]:3000",
  16477. detail::make_host_and_port_string("::1", 3000, false));
  16478. // IPv6 with zone ID (link-local address) with default port
  16479. EXPECT_EQ("[fe80::1%eth0]",
  16480. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  16481. // IPv6 with zone ID (link-local address) with non-default port
  16482. EXPECT_EQ("[fe80::1%eth0]:8080",
  16483. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  16484. // Edge case: Port 443 with is_ssl=false (should add port)
  16485. EXPECT_EQ("example.com:443",
  16486. detail::make_host_and_port_string("example.com", 443, false));
  16487. // Edge case: Port 80 with is_ssl=true (should add port)
  16488. EXPECT_EQ("example.com:80",
  16489. detail::make_host_and_port_string("example.com", 80, true));
  16490. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  16491. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  16492. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  16493. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  16494. // Security fix: Already bracketed IPv6 should not get double brackets
  16495. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  16496. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  16497. EXPECT_EQ("[::1]:8080",
  16498. detail::make_host_and_port_string("[::1]", 8080, false));
  16499. EXPECT_EQ("[2001:db8::1]:8080",
  16500. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  16501. EXPECT_EQ("[fe80::1%eth0]",
  16502. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  16503. EXPECT_EQ("[fe80::1%eth0]:8080",
  16504. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  16505. // Edge case: Empty host (should return as-is)
  16506. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  16507. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  16508. // This is a known limitation but shouldn't crash
  16509. EXPECT_EQ("[host:name]",
  16510. detail::make_host_and_port_string("host:name", 80, false));
  16511. // Port number edge cases (no validation, but should not crash)
  16512. EXPECT_EQ("example.com:0",
  16513. detail::make_host_and_port_string("example.com", 0, false));
  16514. EXPECT_EQ("example.com:-1",
  16515. detail::make_host_and_port_string("example.com", -1, false));
  16516. EXPECT_EQ("example.com:65535",
  16517. detail::make_host_and_port_string("example.com", 65535, false));
  16518. EXPECT_EQ("example.com:65536",
  16519. detail::make_host_and_port_string("example.com", 65536, false));
  16520. }
  16521. #ifdef CPPHTTPLIB_SSL_ENABLED
  16522. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  16523. httplib::SSLClient cli("roblox.com", 443);
  16524. cli.set_follow_location(true);
  16525. auto res = cli.Get("/");
  16526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16527. EXPECT_EQ(StatusCode::OK_200, res->status);
  16528. }
  16529. #endif
  16530. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  16531. Server svr;
  16532. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  16533. EXPECT_EQ(res.status, 400);
  16534. });
  16535. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16536. auto se = detail::scope_exit([&] {
  16537. svr.stop();
  16538. thread.join();
  16539. ASSERT_FALSE(svr.is_running());
  16540. });
  16541. svr.wait_until_ready();
  16542. Client cli(HOST, PORT);
  16543. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  16544. }
  16545. TEST(InvalidHeaderCharsTest, is_field_name) {
  16546. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  16547. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  16548. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  16549. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  16550. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  16551. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  16552. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  16553. EXPECT_FALSE(detail::fields::is_field_name(""));
  16554. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  16555. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  16556. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  16557. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  16558. }
  16559. TEST(InvalidHeaderCharsTest, is_field_value) {
  16560. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  16561. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  16562. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  16563. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  16564. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  16565. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  16566. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  16567. EXPECT_TRUE(detail::fields::is_field_value(""));
  16568. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  16569. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  16570. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  16571. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  16572. EXPECT_TRUE(detail::fields::is_field_value("0"));
  16573. }
  16574. TEST(InvalidHeaderCharsTest, OnServer) {
  16575. Server svr;
  16576. svr.Get("/test_name", [&](const Request &req, Response &res) {
  16577. std::string header = "Not Set";
  16578. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16579. res.set_header(header, "value");
  16580. res.set_content("Page Content Page Content", "text/plain");
  16581. });
  16582. svr.Get("/test_value", [&](const Request &req, Response &res) {
  16583. std::string header = "Not Set";
  16584. if (req.has_param("header")) { header = req.get_param_value("header"); }
  16585. res.set_header("X-Test", header);
  16586. res.set_content("Page Content Page Content", "text/plain");
  16587. });
  16588. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16589. auto se = detail::scope_exit([&] {
  16590. svr.stop();
  16591. thread.join();
  16592. ASSERT_FALSE(svr.is_running());
  16593. });
  16594. svr.wait_until_ready();
  16595. Client cli(HOST, PORT);
  16596. {
  16597. auto res = cli.Get(
  16598. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16600. EXPECT_EQ("Page Content Page Content", res->body);
  16601. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16602. }
  16603. {
  16604. auto res = cli.Get(
  16605. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  16606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16607. EXPECT_EQ("Page Content Page Content", res->body);
  16608. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  16609. }
  16610. }
  16611. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  16612. auto handled = false;
  16613. Server svr;
  16614. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  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. ASSERT_FALSE(handled);
  16621. });
  16622. svr.wait_until_ready();
  16623. auto req = "POST /test HTTP/1.1\r\n"
  16624. "Content-Length: x\r\n"
  16625. "\r\n";
  16626. std::string response;
  16627. ASSERT_TRUE(send_request(1, req, &response));
  16628. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  16629. response.substr(0, response.find("\r\n")));
  16630. }
  16631. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  16632. // case-insensitive, and a server that receives a 100-continue expectation in
  16633. // an HTTP/1.0 request MUST ignore it.
  16634. static void probe_expect(int port, const std::string &req, bool *got_100) {
  16635. std::string response;
  16636. ASSERT_TRUE(send_request(1, req, &response, port));
  16637. *got_100 = response.find("100 Continue") != std::string::npos;
  16638. }
  16639. class ExpectTokenTest : public ::testing::Test {
  16640. protected:
  16641. void SetUp() override {
  16642. svr_.Post("/p", [](const Request &, Response &res) {
  16643. res.set_content("ok", "text/plain");
  16644. });
  16645. port_ = svr_.bind_to_any_port(HOST);
  16646. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16647. svr_.wait_until_ready();
  16648. }
  16649. void TearDown() override {
  16650. svr_.stop();
  16651. if (thread_.joinable()) { thread_.join(); }
  16652. }
  16653. std::string request(const char *version, const char *expect_value) const {
  16654. return std::string("POST /p ") + version +
  16655. "\r\n"
  16656. "Host: localhost\r\n"
  16657. "Content-Length: 2\r\n"
  16658. "Connection: close\r\n"
  16659. "Expect: " +
  16660. expect_value +
  16661. "\r\n"
  16662. "\r\n"
  16663. "hi";
  16664. }
  16665. Server svr_;
  16666. int port_ = 0;
  16667. thread thread_;
  16668. };
  16669. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  16670. bool got_100 = false;
  16671. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  16672. EXPECT_TRUE(got_100);
  16673. }
  16674. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  16675. bool got_100 = true;
  16676. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  16677. EXPECT_FALSE(got_100);
  16678. }
  16679. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  16680. bool got_100 = false;
  16681. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  16682. EXPECT_TRUE(got_100);
  16683. }
  16684. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  16685. bool got_100 = false;
  16686. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  16687. EXPECT_TRUE(got_100);
  16688. }
  16689. // `100 Continue` is sent only when the server starts reading the body, so a
  16690. // request rejected before that never invites the client to send it. The
  16691. // requests below carry the expectation but withhold the body, as a client
  16692. // waiting for `100 Continue` would.
  16693. // A POST that expects `100 Continue` and withholds its two-byte body.
  16694. static std::string expect_headers_only(const std::string &path) {
  16695. return "POST " + path +
  16696. " HTTP/1.1\r\n"
  16697. "Host: localhost\r\n"
  16698. "Content-Length: 2\r\n"
  16699. "Expect: 100-continue\r\n"
  16700. "\r\n";
  16701. }
  16702. class ExpectLazyContinueTest : public ::testing::Test {
  16703. protected:
  16704. void SetUp() override {
  16705. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  16706. if (req.path == "/pre-routing") {
  16707. res.status = StatusCode::Unauthorized_401;
  16708. return Server::HandlerResponse::Handled;
  16709. }
  16710. return Server::HandlerResponse::Unhandled;
  16711. });
  16712. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  16713. if (req.matched_route == "/pre-request") {
  16714. res.status = StatusCode::Forbidden_403;
  16715. return Server::HandlerResponse::Handled;
  16716. }
  16717. return Server::HandlerResponse::Unhandled;
  16718. });
  16719. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  16720. res.set_content("ok", "text/plain");
  16721. });
  16722. svr_.Post("/pre-request", [](const Request &, Response &res) {
  16723. res.set_content("ok", "text/plain");
  16724. });
  16725. svr_.Post("/reader-used", [](const Request &, Response &res,
  16726. const ContentReader &content_reader) {
  16727. std::string body;
  16728. content_reader([&](const char *data, size_t len) {
  16729. body.append(data, len);
  16730. return true;
  16731. });
  16732. res.set_content(body, "text/plain");
  16733. });
  16734. svr_.Post("/reader-unused",
  16735. [](const Request &, Response &res, const ContentReader &) {
  16736. res.set_content("ignored", "text/plain");
  16737. });
  16738. port_ = svr_.bind_to_any_port(HOST);
  16739. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16740. svr_.wait_until_ready();
  16741. }
  16742. void TearDown() override {
  16743. svr_.stop();
  16744. if (thread_.joinable()) { thread_.join(); }
  16745. }
  16746. // Sends `req` and reads until the server closes the connection. Returns
  16747. // false if the read had to wait for the client-side timeout instead.
  16748. bool send_until_closed(const std::string &req, std::string *resp) const {
  16749. auto start = std::chrono::steady_clock::now();
  16750. if (!send_request(3, req, resp, port_)) { return false; }
  16751. auto elapsed = std::chrono::steady_clock::now() - start;
  16752. return elapsed < std::chrono::seconds(2);
  16753. }
  16754. // The final response comes without `100 Continue`, and the server closes
  16755. // the connection since the body may or may not follow.
  16756. void expect_final_without_interim(const std::string &path,
  16757. const char *status_line) const {
  16758. std::string resp;
  16759. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  16760. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  16761. EXPECT_EQ(0u, resp.find(status_line));
  16762. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16763. }
  16764. Server svr_;
  16765. int port_ = 0;
  16766. thread thread_;
  16767. };
  16768. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  16769. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  16770. }
  16771. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  16772. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  16773. }
  16774. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  16775. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  16776. }
  16777. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  16778. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  16779. }
  16780. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  16781. // The body follows once `100 Continue` has had time to arrive.
  16782. auto req = expect_headers_only("/reader-used");
  16783. req.insert(req.size() - 2, "Connection: close\r\n");
  16784. std::string resp;
  16785. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  16786. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  16787. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  16788. EXPECT_NE(std::string::npos, resp.find("hi"));
  16789. }
  16790. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  16791. // Large enough for the client to add `Expect: 100-continue` itself.
  16792. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  16793. std::atomic<bool> body_sent{false};
  16794. Client cli(HOST, port_);
  16795. auto res = cli.Post(
  16796. "/pre-request", length,
  16797. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  16798. body_sent = true;
  16799. std::string chunk(len, 'x');
  16800. sink.write(chunk.data(), chunk.size());
  16801. return true;
  16802. },
  16803. "application/octet-stream");
  16804. ASSERT_TRUE(res);
  16805. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  16806. EXPECT_FALSE(body_sent);
  16807. }
  16808. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  16809. Server svr;
  16810. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  16811. return StatusCode::ExpectationFailed_417;
  16812. });
  16813. svr.Post("/p", [](const Request &, Response &res) {
  16814. res.set_content("ok", "text/plain");
  16815. });
  16816. auto port = svr.bind_to_any_port(HOST);
  16817. thread t = thread([&] { svr.listen_after_bind(); });
  16818. auto se = detail::scope_exit([&] {
  16819. svr.stop();
  16820. t.join();
  16821. });
  16822. svr.wait_until_ready();
  16823. std::string resp;
  16824. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  16825. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  16826. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  16827. // Exactly one response: the route handler must not run after the 417.
  16828. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  16829. }
  16830. #ifndef _WIN32
  16831. TEST(Expect100ContinueTest, ServerClosesConnection) {
  16832. static constexpr char reject[] = "Unauthorized";
  16833. static constexpr char accept[] = "Upload accepted";
  16834. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  16835. Server svr;
  16836. svr.set_expect_100_continue_handler(
  16837. [](const Request & /*req*/, Response &res) {
  16838. res.status = StatusCode::Unauthorized_401;
  16839. res.set_content(reject, "text/plain");
  16840. return res.status;
  16841. });
  16842. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  16843. res.set_content(accept, "text/plain");
  16844. });
  16845. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  16846. auto se = detail::scope_exit([&] {
  16847. svr.stop();
  16848. thread.join();
  16849. ASSERT_FALSE(svr.is_running());
  16850. });
  16851. svr.wait_until_ready();
  16852. {
  16853. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  16854. curl_easy_init(), &curl_easy_cleanup};
  16855. ASSERT_NE(curl, nullptr);
  16856. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  16857. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  16858. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  16859. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  16860. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  16861. &curl_slist_free_all};
  16862. ASSERT_NE(list, nullptr);
  16863. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  16864. struct read_data {
  16865. size_t read_size;
  16866. size_t total_size;
  16867. } data = {0, total_size};
  16868. using read_callback_t =
  16869. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16870. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  16871. void *userdata) -> size_t {
  16872. read_data *d = (read_data *)userdata;
  16873. if (!userdata || d->read_size >= d->total_size) { return 0; }
  16874. std::fill_n(ptr, size * nmemb, 'A');
  16875. d->read_size += size * nmemb;
  16876. return size * nmemb;
  16877. };
  16878. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  16879. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  16880. std::vector<char> buffer;
  16881. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  16882. using write_callback_t =
  16883. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  16884. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  16885. void *userdata) -> size_t {
  16886. std::vector<char> *buf = (std::vector<char> *)userdata;
  16887. buf->reserve(buf->size() + size * nmemb + 1);
  16888. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  16889. return size * nmemb;
  16890. };
  16891. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  16892. {
  16893. const auto res = curl_easy_perform(curl.get());
  16894. ASSERT_EQ(res, CURLE_OK);
  16895. }
  16896. {
  16897. auto response_code = long{};
  16898. const auto res =
  16899. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  16900. ASSERT_EQ(res, CURLE_OK);
  16901. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  16902. }
  16903. {
  16904. auto dl = curl_off_t{};
  16905. const auto res =
  16906. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  16907. ASSERT_EQ(res, CURLE_OK);
  16908. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  16909. }
  16910. {
  16911. buffer.push_back('\0');
  16912. ASSERT_STRCASEEQ(buffer.data(), reject);
  16913. }
  16914. }
  16915. }
  16916. #endif
  16917. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  16918. // Regression test for #2458.
  16919. //
  16920. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  16921. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  16922. // ticket can make the client socket spuriously readable during the
  16923. // 100-continue wait. If the readiness is mistaken for an incoming response,
  16924. // the client withholds the body and then blocks reading a response that never
  16925. // comes, failing with `Failed to read connection`.
  16926. //
  16927. // A correct client (like curl) sends the body once no `100 Continue` arrives
  16928. // within the timeout. This raw OpenSSL server deliberately never sends
  16929. // `100 Continue`; the client must still deliver the body and receive 200.
  16930. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  16931. signal(SIGPIPE, SIG_IGN);
  16932. const auto port = PORT + 4;
  16933. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  16934. ASSERT_NE(srv, INVALID_SOCKET);
  16935. int opt = 1;
  16936. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  16937. sockaddr_in addr{};
  16938. addr.sin_family = AF_INET;
  16939. addr.sin_port = htons(static_cast<uint16_t>(port));
  16940. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  16941. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  16942. ASSERT_EQ(0, ::listen(srv, 1));
  16943. std::atomic<size_t> server_body_bytes{0};
  16944. auto server_thread = std::thread([&] {
  16945. sockaddr_in cli_addr{};
  16946. socklen_t cli_len = sizeof(cli_addr);
  16947. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  16948. if (cli == INVALID_SOCKET) { return; }
  16949. // Bound the lifetime of the server side so a buggy client (which never
  16950. // sends the body) cannot make this thread block forever on join.
  16951. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  16952. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  16953. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  16954. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  16955. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  16956. SSL *ssl = SSL_new(ctx);
  16957. SSL_set_fd(ssl, static_cast<int>(cli));
  16958. if (SSL_accept(ssl) > 0) {
  16959. // Read the request headers. Reading here also flushes the TLS 1.3
  16960. // session tickets to the client. Deliberately do NOT send
  16961. // `100 Continue`.
  16962. std::string buf;
  16963. char tmp[1024];
  16964. while (buf.find("\r\n\r\n") == std::string::npos) {
  16965. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16966. if (n <= 0) { break; }
  16967. buf.append(tmp, static_cast<size_t>(n));
  16968. }
  16969. // A correct client sends the body now; count what arrives.
  16970. auto pos = buf.find("\r\n\r\n");
  16971. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  16972. while (body < 4096) {
  16973. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  16974. if (n <= 0) { break; }
  16975. body += static_cast<size_t>(n);
  16976. }
  16977. server_body_bytes = body;
  16978. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  16979. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  16980. SSL_shutdown(ssl);
  16981. }
  16982. SSL_free(ssl);
  16983. detail::close_socket(cli);
  16984. SSL_CTX_free(ctx);
  16985. });
  16986. auto se = detail::scope_exit([&] {
  16987. server_thread.join();
  16988. detail::close_socket(srv);
  16989. });
  16990. SSLClient cli("127.0.0.1", port);
  16991. cli.enable_server_certificate_verification(false);
  16992. cli.set_connection_timeout(5, 0);
  16993. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  16994. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  16995. std::string body(4096, 'A');
  16996. auto res = cli.Put("/api/test", body, "application/json");
  16997. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  16998. EXPECT_EQ(StatusCode::OK_200, res->status);
  16999. EXPECT_EQ(body.size(), server_body_bytes.load());
  17000. }
  17001. #endif
  17002. template <typename S, typename C>
  17003. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  17004. svr.Get("/stream", [&](const Request &, Response &res) {
  17005. auto data = new std::string("01234567890123456789");
  17006. res.set_content_provider(
  17007. data->size(), "text/plain",
  17008. [&, data](size_t offset, size_t length, DataSink &sink) {
  17009. const size_t DATA_CHUNK_SIZE = 4;
  17010. const auto &d = *data;
  17011. std::this_thread::sleep_for(std::chrono::seconds(1));
  17012. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  17013. return true;
  17014. },
  17015. [data](bool success) {
  17016. EXPECT_FALSE(success);
  17017. delete data;
  17018. });
  17019. });
  17020. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  17021. auto i = new size_t(0);
  17022. res.set_content_provider(
  17023. "text/plain",
  17024. [i](size_t, DataSink &sink) {
  17025. if (*i < 5) {
  17026. std::this_thread::sleep_for(std::chrono::seconds(1));
  17027. sink.write("abcd", 4);
  17028. (*i)++;
  17029. } else {
  17030. sink.done();
  17031. }
  17032. return true;
  17033. },
  17034. [i](bool success) {
  17035. EXPECT_FALSE(success);
  17036. delete i;
  17037. });
  17038. });
  17039. svr.Get("/chunked", [&](const Request &, Response &res) {
  17040. auto i = new size_t(0);
  17041. res.set_chunked_content_provider(
  17042. "text/plain",
  17043. [i](size_t, DataSink &sink) {
  17044. if (*i < 5) {
  17045. std::this_thread::sleep_for(std::chrono::seconds(1));
  17046. sink.os << "abcd";
  17047. (*i)++;
  17048. } else {
  17049. sink.done();
  17050. }
  17051. return true;
  17052. },
  17053. [i](bool success) {
  17054. EXPECT_FALSE(success);
  17055. delete i;
  17056. });
  17057. });
  17058. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  17059. auto se = detail::scope_exit([&] {
  17060. svr.stop();
  17061. listen_thread.join();
  17062. ASSERT_FALSE(svr.is_running());
  17063. });
  17064. svr.wait_until_ready();
  17065. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  17066. {
  17067. auto start = std::chrono::steady_clock::now();
  17068. auto res = cli.Get("/stream");
  17069. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17070. std::chrono::steady_clock::now() - start)
  17071. .count();
  17072. ASSERT_FALSE(res);
  17073. EXPECT_EQ(Error::Read, res.error());
  17074. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17075. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17076. }
  17077. {
  17078. auto start = std::chrono::steady_clock::now();
  17079. auto res = cli.Get("/stream_without_length");
  17080. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17081. std::chrono::steady_clock::now() - start)
  17082. .count();
  17083. ASSERT_FALSE(res);
  17084. EXPECT_EQ(Error::Read, res.error());
  17085. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17086. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17087. }
  17088. {
  17089. auto start = std::chrono::steady_clock::now();
  17090. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  17091. EXPECT_EQ("abcd", string(data, data_length));
  17092. return true;
  17093. });
  17094. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  17095. std::chrono::steady_clock::now() - start)
  17096. .count();
  17097. ASSERT_FALSE(res);
  17098. EXPECT_EQ(Error::Read, res.error());
  17099. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  17100. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  17101. }
  17102. }
  17103. TEST(MaxTimeoutTest, ContentStream) {
  17104. time_t timeout = 2000;
  17105. time_t threshold = 200;
  17106. Server svr;
  17107. Client cli("localhost", PORT);
  17108. max_timeout_test(svr, cli, timeout, threshold);
  17109. }
  17110. #ifdef CPPHTTPLIB_SSL_ENABLED
  17111. TEST(MaxTimeoutTest, ContentStreamSSL) {
  17112. time_t timeout = 2000;
  17113. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  17114. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17115. SSLClient cli("localhost", PORT);
  17116. cli.enable_server_certificate_verification(false);
  17117. max_timeout_test(svr, cli, timeout, threshold);
  17118. }
  17119. #endif
  17120. class EventDispatcher {
  17121. public:
  17122. EventDispatcher() {}
  17123. bool wait_event(DataSink *sink) {
  17124. unique_lock<mutex> lk(m_);
  17125. int id = id_;
  17126. // Wait with timeout to prevent hanging if client disconnects
  17127. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  17128. [&] { return cid_ == id; })) {
  17129. return false; // Timeout occurred
  17130. }
  17131. sink->write(message_.data(), message_.size());
  17132. return true;
  17133. }
  17134. void send_event(const string &message) {
  17135. lock_guard<mutex> lk(m_);
  17136. cid_ = id_++;
  17137. message_ = message;
  17138. cv_.notify_all();
  17139. }
  17140. private:
  17141. mutex m_;
  17142. condition_variable cv_;
  17143. atomic_int id_{0};
  17144. atomic_int cid_{-1};
  17145. string message_;
  17146. };
  17147. TEST(ClientInThreadTest, Issue2068) {
  17148. EventDispatcher ed;
  17149. Server svr;
  17150. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  17151. res.set_chunked_content_provider("text/event-stream",
  17152. [&](size_t /*offset*/, DataSink &sink) {
  17153. return ed.wait_event(&sink);
  17154. });
  17155. });
  17156. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  17157. svr.wait_until_ready();
  17158. thread event_thread([&] {
  17159. int id = 0;
  17160. while (svr.is_running()) {
  17161. this_thread::sleep_for(chrono::milliseconds(500));
  17162. std::stringstream ss;
  17163. ss << "data: " << id << "\n\n";
  17164. ed.send_event(ss.str());
  17165. id++;
  17166. }
  17167. });
  17168. auto se = detail::scope_exit([&] {
  17169. svr.stop();
  17170. listen_thread.join();
  17171. event_thread.join();
  17172. ASSERT_FALSE(svr.is_running());
  17173. });
  17174. {
  17175. auto client = detail::make_unique<Client>(HOST, PORT);
  17176. client->set_read_timeout(std::chrono::minutes(10));
  17177. std::atomic<bool> stop{false};
  17178. std::thread t([&] {
  17179. client->Get("/event1",
  17180. [&](const char *, size_t) -> bool { return !stop; });
  17181. });
  17182. std::this_thread::sleep_for(std::chrono::seconds(2));
  17183. stop = true;
  17184. client->stop();
  17185. t.join();
  17186. // Reset client after thread has finished
  17187. client.reset();
  17188. }
  17189. }
  17190. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  17191. auto handled = false;
  17192. Server svr;
  17193. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17194. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17195. auto se = detail::scope_exit([&] {
  17196. svr.stop();
  17197. t.join();
  17198. ASSERT_FALSE(svr.is_running());
  17199. ASSERT_FALSE(handled);
  17200. });
  17201. svr.wait_until_ready();
  17202. // Two Content-Length headers with different values — must be rejected
  17203. auto req = "POST /test HTTP/1.1\r\n"
  17204. "Content-Length: 5\r\n"
  17205. "Content-Length: 10\r\n"
  17206. "\r\n"
  17207. "hello";
  17208. std::string response;
  17209. ASSERT_TRUE(send_request(1, req, &response));
  17210. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17211. response.substr(0, response.find("\r\n")));
  17212. }
  17213. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  17214. auto handled = false;
  17215. Server svr;
  17216. svr.Post("/test", [&](const Request &, Response &res) {
  17217. handled = true;
  17218. res.set_content("ok", "text/plain");
  17219. });
  17220. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17221. auto se = detail::scope_exit([&] {
  17222. svr.stop();
  17223. t.join();
  17224. ASSERT_FALSE(svr.is_running());
  17225. ASSERT_TRUE(handled);
  17226. });
  17227. svr.wait_until_ready();
  17228. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  17229. auto req = "POST /test HTTP/1.1\r\n"
  17230. "Host: localhost\r\n"
  17231. "Content-Length: 5\r\n"
  17232. "Content-Length: 5\r\n"
  17233. "\r\n"
  17234. "hello";
  17235. std::string response;
  17236. ASSERT_TRUE(send_request(1, req, &response));
  17237. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  17238. }
  17239. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  17240. Server svr;
  17241. svr.Get("/test", [](const Request &, Response &res) {
  17242. res.set_content("ok", "text/plain");
  17243. });
  17244. auto port = svr.bind_to_any_port(HOST);
  17245. thread t = thread([&] { svr.listen_after_bind(); });
  17246. auto se = detail::scope_exit([&] {
  17247. svr.stop();
  17248. t.join();
  17249. ASSERT_FALSE(svr.is_running());
  17250. });
  17251. svr.wait_until_ready();
  17252. auto status_line = [&](const std::string &host_lines) {
  17253. std::string res;
  17254. send_request(
  17255. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  17256. &res, port);
  17257. return res.substr(0, res.find("\r\n"));
  17258. };
  17259. const char *accepted[] = {
  17260. "Host: localhost\r\n",
  17261. "Host: a.example:8080\r\n",
  17262. "Host: my_service\r\n",
  17263. "Host: [::1]:8080\r\n",
  17264. "Host: [fe80::1%25eth0]\r\n",
  17265. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  17266. };
  17267. for (auto host_lines : accepted) {
  17268. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  17269. }
  17270. const char *rejected[] = {
  17271. "Host: a.example\r\nHost: b.example\r\n",
  17272. "Host: a.example\r\nHost: a.example\r\n",
  17273. "Host: a@b.example\r\n",
  17274. "Host: a.example/b\r\n",
  17275. "Host: a.example\\b\r\n",
  17276. "Host: a.example?b\r\n",
  17277. "Host: a.example#b\r\n",
  17278. "Host: a.example b.example\r\n",
  17279. };
  17280. for (auto host_lines : rejected) {
  17281. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  17282. << host_lines;
  17283. }
  17284. }
  17285. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  17286. Server svr;
  17287. svr.Get("/", [](const Request &req, Response &res) {
  17288. EXPECT_EQ(2U, req.trailers.size());
  17289. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  17290. // Denied
  17291. EXPECT_FALSE(req.has_trailer("Content-Length"));
  17292. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  17293. // Accepted
  17294. EXPECT_TRUE(req.has_trailer("X-Hello"));
  17295. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  17296. EXPECT_TRUE(req.has_trailer("X-World"));
  17297. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  17298. res.set_content("ok", "text/plain");
  17299. });
  17300. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17301. auto se = detail::scope_exit([&] {
  17302. svr.stop();
  17303. t.join();
  17304. ASSERT_FALSE(svr.is_running());
  17305. });
  17306. svr.wait_until_ready();
  17307. const std::string req = "GET / HTTP/1.1\r\n"
  17308. "Transfer-Encoding: chunked\r\n"
  17309. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  17310. "\r\n"
  17311. "0\r\n"
  17312. "Content-Length: 10\r\n"
  17313. "Host: internal.local\r\n"
  17314. "Content-Type: malicious/content\r\n"
  17315. "Cookie: any\r\n"
  17316. "Set-Cookie: any\r\n"
  17317. "X-Forwarded-For: attacker.com\r\n"
  17318. "X-Real-Ip: 1.1.1.1\r\n"
  17319. "X-Hello: hello\r\n"
  17320. "X-World: world\r\n"
  17321. "\r\n";
  17322. std::string res;
  17323. ASSERT_TRUE(send_request(1, req, &res));
  17324. }
  17325. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  17326. // several field lines, and the combined value is what has to be parsed. A
  17327. // Trailer field split across lines therefore declares every name it lists;
  17328. // reading only the first line silently drops the trailers the later lines
  17329. // declare. The prohibited-trailer filter still applies to every line.
  17330. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  17331. Server svr;
  17332. size_t observed_trailer_count = 0;
  17333. std::string observed_hello;
  17334. std::string observed_world;
  17335. bool observed_content_length = true;
  17336. svr.Get("/", [&](const Request &req, Response &res) {
  17337. observed_trailer_count = req.trailers.size();
  17338. observed_hello = req.get_trailer_value("X-Hello");
  17339. observed_world = req.get_trailer_value("X-World");
  17340. observed_content_length = req.has_trailer("Content-Length");
  17341. res.set_content("ok", "text/plain");
  17342. });
  17343. auto port = svr.bind_to_any_port(HOST);
  17344. thread t = thread([&]() { svr.listen_after_bind(); });
  17345. auto se = detail::scope_exit([&] {
  17346. svr.stop();
  17347. t.join();
  17348. ASSERT_FALSE(svr.is_running());
  17349. });
  17350. svr.wait_until_ready();
  17351. const std::string req = "GET / HTTP/1.1\r\n"
  17352. "Host: localhost\r\n"
  17353. "Transfer-Encoding: chunked\r\n"
  17354. "Trailer: X-Hello\r\n"
  17355. "Trailer: X-World, Content-Length\r\n"
  17356. "\r\n"
  17357. "0\r\n"
  17358. "X-Hello: hello\r\n"
  17359. "X-World: world\r\n"
  17360. "Content-Length: 10\r\n"
  17361. "\r\n";
  17362. std::string res;
  17363. ASSERT_TRUE(send_request(1, req, &res, port));
  17364. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  17365. // Accepted: both field lines contribute to the declared set
  17366. EXPECT_EQ(2U, observed_trailer_count);
  17367. EXPECT_EQ(observed_hello, "hello");
  17368. EXPECT_EQ(observed_world, "world");
  17369. // Denied: a prohibited name stays prohibited on a later field line
  17370. EXPECT_FALSE(observed_content_length);
  17371. }
  17372. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  17373. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  17374. // unbounded run of fields that are never declared, because the counter would
  17375. // only advance for declared fields.
  17376. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  17377. Server svr;
  17378. bool handler_called = false;
  17379. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  17380. handler_called = true;
  17381. res.set_content("ok", "text/plain");
  17382. });
  17383. auto port = svr.bind_to_any_port(HOST);
  17384. thread t = thread([&]() { svr.listen_after_bind(); });
  17385. auto se = detail::scope_exit([&] {
  17386. svr.stop();
  17387. t.join();
  17388. ASSERT_FALSE(svr.is_running());
  17389. });
  17390. svr.wait_until_ready();
  17391. // Declare nothing, then send far more undeclared trailer fields than the
  17392. // header-count limit. Parsing must stop and reject the request rather than
  17393. // read every line.
  17394. std::string req = "GET / HTTP/1.1\r\n"
  17395. "Transfer-Encoding: chunked\r\n"
  17396. "\r\n"
  17397. "0\r\n";
  17398. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  17399. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  17400. }
  17401. req += "\r\n";
  17402. std::string res;
  17403. ASSERT_TRUE(send_request(1, req, &res, port));
  17404. // The request is rejected before the handler runs.
  17405. EXPECT_FALSE(handler_called);
  17406. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  17407. }
  17408. // The set of declared trailer names is capped so a peer cannot grow it without
  17409. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  17410. // declared past the cap is not honored, even if the field is actually sent.
  17411. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  17412. Server svr;
  17413. // One name inside the cap and one past it, so the test tracks the cap rather
  17414. // than a fixed count.
  17415. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  17416. const std::string within_cap_name = "X-T-0";
  17417. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  17418. bool observed_within_cap = false;
  17419. bool observed_past_cap = false;
  17420. svr.Get("/", [&](const Request &req, Response &res) {
  17421. observed_within_cap = req.has_trailer(within_cap_name);
  17422. observed_past_cap = req.has_trailer(past_cap_name);
  17423. res.set_content("ok", "text/plain");
  17424. });
  17425. auto port = svr.bind_to_any_port(HOST);
  17426. thread t = thread([&]() { svr.listen_after_bind(); });
  17427. auto se = detail::scope_exit([&] {
  17428. svr.stop();
  17429. t.join();
  17430. ASSERT_FALSE(svr.is_running());
  17431. });
  17432. svr.wait_until_ready();
  17433. // Declare more trailer names than the cap in a single Trailer field, then
  17434. // actually send the first (within the cap) and the last (past it).
  17435. std::string trailer_decl = "Trailer: ";
  17436. for (int i = 0; i < declared_count; i++) {
  17437. if (i != 0) { trailer_decl += ", "; }
  17438. trailer_decl += "X-T-" + std::to_string(i);
  17439. }
  17440. trailer_decl += "\r\n";
  17441. const std::string req = "GET / HTTP/1.1\r\n"
  17442. "Host: localhost\r\n"
  17443. "Transfer-Encoding: chunked\r\n" +
  17444. trailer_decl +
  17445. "\r\n"
  17446. "0\r\n" +
  17447. within_cap_name + ": a\r\n" + past_cap_name +
  17448. ": b\r\n"
  17449. "\r\n";
  17450. std::string res;
  17451. ASSERT_TRUE(send_request(1, req, &res, port));
  17452. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  17453. // A name within the cap is honored; one declared past the cap is dropped.
  17454. EXPECT_TRUE(observed_within_cap);
  17455. EXPECT_FALSE(observed_past_cap);
  17456. }
  17457. // A direct client that is not listed in trusted_proxies must not be able to
  17458. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  17459. // the peer address on the actual TCP connection determines whether the
  17460. // header is honored.
  17461. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  17462. Server svr;
  17463. // Deliberately does NOT include the loopback address the test client
  17464. // actually connects from, so the direct connection is not a trusted proxy.
  17465. svr.set_trusted_proxies({"203.0.113.66"});
  17466. std::string observed_remote_addr;
  17467. svr.Get("/ip", [&](const Request &req, Response &res) {
  17468. observed_remote_addr = req.remote_addr;
  17469. res.set_content("ok", "text/plain");
  17470. });
  17471. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17472. auto se = detail::scope_exit([&] {
  17473. svr.stop();
  17474. t.join();
  17475. ASSERT_FALSE(svr.is_running());
  17476. });
  17477. svr.wait_until_ready();
  17478. Client cli(HOST, PORT);
  17479. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  17480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17481. EXPECT_EQ(StatusCode::OK_200, res->status);
  17482. // The connecting peer is not a trusted proxy, so the spoofed header must be
  17483. // ignored entirely and the real connection-level address retained.
  17484. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17485. observed_remote_addr == "127.0.0.1");
  17486. }
  17487. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  17488. Server svr;
  17489. std::string observed_remote_addr;
  17490. std::string observed_xff;
  17491. svr.Get("/ip", [&](const Request &req, Response &res) {
  17492. observed_remote_addr = req.remote_addr;
  17493. observed_xff = req.get_header_value("X-Forwarded-For");
  17494. res.set_content("ok", "text/plain");
  17495. });
  17496. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17497. auto se = detail::scope_exit([&] {
  17498. svr.stop();
  17499. t.join();
  17500. ASSERT_FALSE(svr.is_running());
  17501. });
  17502. svr.wait_until_ready();
  17503. Client cli(HOST, PORT);
  17504. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  17505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17506. EXPECT_EQ(StatusCode::OK_200, res->status);
  17507. EXPECT_EQ(observed_xff, "203.0.113.66");
  17508. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17509. observed_remote_addr == "127.0.0.1");
  17510. }
  17511. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  17512. Server svr;
  17513. svr.set_trusted_proxies({"203.0.113.66"});
  17514. std::string observed_remote_addr;
  17515. std::string observed_xff;
  17516. svr.Get("/ip", [&](const Request &req, Response &res) {
  17517. observed_remote_addr = req.remote_addr;
  17518. observed_xff = req.get_header_value("X-Forwarded-For");
  17519. res.set_content("ok", "text/plain");
  17520. });
  17521. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17522. auto se = detail::scope_exit([&] {
  17523. svr.stop();
  17524. t.join();
  17525. ASSERT_FALSE(svr.is_running());
  17526. });
  17527. svr.wait_until_ready();
  17528. Client cli(HOST, PORT);
  17529. auto res = cli.Get("/ip");
  17530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17531. EXPECT_EQ(StatusCode::OK_200, res->status);
  17532. EXPECT_EQ(observed_xff, "");
  17533. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17534. observed_remote_addr == "127.0.0.1");
  17535. }
  17536. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  17537. Server svr;
  17538. // Include the loopback address the test client actually connects from, so
  17539. // the direct connection itself is recognized as the trusted proxy hop.
  17540. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  17541. std::string observed_remote_addr;
  17542. std::string observed_xff;
  17543. svr.Get("/ip", [&](const Request &req, Response &res) {
  17544. observed_remote_addr = req.remote_addr;
  17545. observed_xff = req.get_header_value("X-Forwarded-For");
  17546. res.set_content("ok", "text/plain");
  17547. });
  17548. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17549. auto se = detail::scope_exit([&] {
  17550. svr.stop();
  17551. t.join();
  17552. ASSERT_FALSE(svr.is_running());
  17553. });
  17554. svr.wait_until_ready();
  17555. Client cli(HOST, PORT);
  17556. auto res = cli.Get(
  17557. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  17558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17559. EXPECT_EQ(StatusCode::OK_200, res->status);
  17560. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  17561. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17562. }
  17563. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  17564. Server svr;
  17565. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  17566. std::string observed_remote_addr;
  17567. std::string observed_xff;
  17568. svr.Get("/ip", [&](const Request &req, Response &res) {
  17569. observed_remote_addr = req.remote_addr;
  17570. observed_xff = req.get_header_value("X-Forwarded-For");
  17571. res.set_content("ok", "text/plain");
  17572. });
  17573. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17574. auto se = detail::scope_exit([&] {
  17575. svr.stop();
  17576. t.join();
  17577. ASSERT_FALSE(svr.is_running());
  17578. });
  17579. svr.wait_until_ready();
  17580. Client cli(HOST, PORT);
  17581. auto res = cli.Get(
  17582. "/ip",
  17583. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17585. EXPECT_EQ(StatusCode::OK_200, res->status);
  17586. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17587. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17588. }
  17589. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  17590. Server svr;
  17591. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17592. std::string observed_remote_addr;
  17593. std::string observed_xff;
  17594. svr.Get("/ip", [&](const Request &req, Response &res) {
  17595. observed_remote_addr = req.remote_addr;
  17596. observed_xff = req.get_header_value("X-Forwarded-For");
  17597. res.set_content("ok", "text/plain");
  17598. });
  17599. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17600. auto se = detail::scope_exit([&] {
  17601. svr.stop();
  17602. t.join();
  17603. ASSERT_FALSE(svr.is_running());
  17604. });
  17605. svr.wait_until_ready();
  17606. Client cli(HOST, PORT);
  17607. auto res = cli.Get(
  17608. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  17609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17610. EXPECT_EQ(StatusCode::OK_200, res->status);
  17611. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  17612. // by the closest hop) is used. The leftmost entry is fully client-controlled
  17613. // and must not be selected.
  17614. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  17615. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  17616. }
  17617. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  17618. Server svr;
  17619. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  17620. std::string observed_remote_addr;
  17621. svr.Get("/ip", [&](const Request &req, Response &res) {
  17622. observed_remote_addr = req.remote_addr;
  17623. res.set_content("ok", "text/plain");
  17624. });
  17625. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17626. auto se = detail::scope_exit([&] {
  17627. svr.stop();
  17628. t.join();
  17629. ASSERT_FALSE(svr.is_running());
  17630. });
  17631. svr.wait_until_ready();
  17632. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  17633. // a forged address and the trusted proxy's own address; the forged value must
  17634. // not win over the address the trusted proxy actually recorded.
  17635. Client cli(HOST, PORT);
  17636. auto res = cli.Get(
  17637. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  17638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17639. EXPECT_EQ(StatusCode::OK_200, res->status);
  17640. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  17641. }
  17642. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  17643. Server svr;
  17644. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17645. std::string observed_remote_addr;
  17646. std::string observed_xff;
  17647. svr.Get("/ip", [&](const Request &req, Response &res) {
  17648. observed_remote_addr = req.remote_addr;
  17649. observed_xff = req.get_header_value("X-Forwarded-For");
  17650. res.set_content("ok", "text/plain");
  17651. });
  17652. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17653. auto se = detail::scope_exit([&] {
  17654. svr.stop();
  17655. t.join();
  17656. ASSERT_FALSE(svr.is_running());
  17657. });
  17658. svr.wait_until_ready();
  17659. Client cli(HOST, PORT);
  17660. auto res = cli.Get(
  17661. "/ip",
  17662. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  17663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17664. EXPECT_EQ(StatusCode::OK_200, res->status);
  17665. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  17666. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17667. }
  17668. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  17669. Server svr;
  17670. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17671. std::string observed_remote_addr;
  17672. std::string observed_xff;
  17673. svr.Get("/ip", [&](const Request &req, Response &res) {
  17674. observed_remote_addr = req.remote_addr;
  17675. observed_xff = req.get_header_value("X-Forwarded-For");
  17676. res.set_content("ok", "text/plain");
  17677. });
  17678. thread t = thread([&]() { svr.listen(HOST, PORT); });
  17679. auto se = detail::scope_exit([&] {
  17680. svr.stop();
  17681. t.join();
  17682. ASSERT_FALSE(svr.is_running());
  17683. });
  17684. svr.wait_until_ready();
  17685. std::string raw_req =
  17686. "GET /ip HTTP/1.1\r\n"
  17687. "Host: localhost\r\n"
  17688. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  17689. "Connection: close\r\n"
  17690. "\r\n";
  17691. std::string out;
  17692. ASSERT_TRUE(send_request(5, raw_req, &out));
  17693. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17694. // Header parser trims surrounding whitespace of the header value
  17695. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  17696. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  17697. }
  17698. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  17699. // one comma-joined value, in the order received. Proxies such as HAProxy append
  17700. // their own X-Forwarded-For as a separate field line rather than extending the
  17701. // one the client sent, so every occurrence has to be taken into account.
  17702. // Reading only the first one hands back the address the client chose.
  17703. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  17704. Server svr;
  17705. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  17706. std::string observed_remote_addr;
  17707. size_t observed_xff_count = 0;
  17708. svr.Get("/ip", [&](const Request &req, Response &res) {
  17709. observed_remote_addr = req.remote_addr;
  17710. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  17711. res.set_content("ok", "text/plain");
  17712. });
  17713. auto port = svr.bind_to_any_port(HOST);
  17714. thread t = thread([&]() { svr.listen_after_bind(); });
  17715. auto se = detail::scope_exit([&] {
  17716. svr.stop();
  17717. t.join();
  17718. ASSERT_FALSE(svr.is_running());
  17719. });
  17720. svr.wait_until_ready();
  17721. // The client supplies the first field line; the trusted proxy appends the
  17722. // address it observed as a second one.
  17723. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  17724. "Host: localhost\r\n"
  17725. "X-Forwarded-For: 1.2.3.4\r\n"
  17726. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  17727. "Connection: close\r\n"
  17728. "\r\n";
  17729. std::string out;
  17730. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17731. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17732. EXPECT_EQ(observed_xff_count, 2U);
  17733. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17734. // The same chain spread over one field line per hop derives the same client
  17735. // address, i.e. the split and the comma-joined representations agree.
  17736. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  17737. "Host: localhost\r\n"
  17738. "X-Forwarded-For: 1.2.3.4\r\n"
  17739. "X-Forwarded-For: 198.51.100.23\r\n"
  17740. "X-Forwarded-For: 192.0.2.45\r\n"
  17741. "Connection: close\r\n"
  17742. "\r\n";
  17743. out.clear();
  17744. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  17745. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17746. EXPECT_EQ(observed_xff_count, 3U);
  17747. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  17748. }
  17749. // An X-Forwarded-For header whose value parses to zero IP segments must not
  17750. // crash the server (it used to call front() on an empty vector inside
  17751. // get_client_ip). The connection-level remote address must be retained instead.
  17752. static void run_malformed_xff_test(const std::string &xff_value) {
  17753. Server svr;
  17754. svr.set_trusted_proxies({"192.0.2.45"});
  17755. std::string observed_remote_addr;
  17756. svr.Get("/ip", [&](const Request &req, Response &res) {
  17757. observed_remote_addr = req.remote_addr;
  17758. res.set_content("ok", "text/plain");
  17759. });
  17760. int port = 0;
  17761. thread t = thread([&]() {
  17762. port = svr.bind_to_any_port(HOST);
  17763. svr.listen_after_bind();
  17764. });
  17765. auto se = detail::scope_exit([&] {
  17766. svr.stop();
  17767. t.join();
  17768. ASSERT_FALSE(svr.is_running());
  17769. });
  17770. svr.wait_until_ready();
  17771. Client cli(HOST, port);
  17772. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  17773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17774. EXPECT_EQ(StatusCode::OK_200, res->status);
  17775. EXPECT_TRUE(observed_remote_addr == "::1" ||
  17776. observed_remote_addr == "127.0.0.1");
  17777. }
  17778. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  17779. run_malformed_xff_test("");
  17780. }
  17781. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  17782. run_malformed_xff_test(",");
  17783. }
  17784. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  17785. run_malformed_xff_test(", , ,");
  17786. }
  17787. // The same rule applies to Accept: a request whose acceptable types are spread
  17788. // over several field lines must be negotiated against all of them.
  17789. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  17790. // case-insensitive connection options. Comparing the whole field value against
  17791. // one option misses a client that sends several of them, and misses every
  17792. // casing but the one written in the comparison.
  17793. //
  17794. // Sends req, reads the response, then reuses the same socket for a second
  17795. // request to find out whether the server kept the connection.
  17796. static void probe_connection_reuse(int port, const std::string &req,
  17797. bool *announced_close, bool *reusable) {
  17798. auto error = Error::Success;
  17799. auto sock = detail::create_client_socket(
  17800. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  17801. /*connection_timeout_sec=*/5, 0,
  17802. /*read_timeout_sec=*/1, 0,
  17803. /*write_timeout_sec=*/5, 0, std::string(), error);
  17804. ASSERT_NE(sock, INVALID_SOCKET);
  17805. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  17806. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  17807. "Host: localhost\r\n"
  17808. "Connection: close\r\n"
  17809. "\r\n";
  17810. std::string first_response;
  17811. std::string second_response;
  17812. detail::process_client_socket(
  17813. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  17814. [&](Stream &strm) {
  17815. if (strm.write(req.data(), req.size()) !=
  17816. static_cast<ssize_t>(req.size())) {
  17817. return false;
  17818. }
  17819. char buf[512];
  17820. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  17821. // Headers plus the two-byte body of the handler below
  17822. while (reader.getline()) {
  17823. first_response += reader.ptr();
  17824. if (first_response.find("ok") != std::string::npos) { break; }
  17825. }
  17826. if (strm.write(second.data(), second.size()) !=
  17827. static_cast<ssize_t>(second.size())) {
  17828. return true;
  17829. }
  17830. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  17831. while (reader2.getline()) {
  17832. second_response += reader2.ptr();
  17833. if (second_response.find("ok") != std::string::npos) { break; }
  17834. }
  17835. return true;
  17836. });
  17837. *announced_close =
  17838. first_response.find("Connection: close") != std::string::npos;
  17839. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  17840. }
  17841. class ConnectionTokenTest : public ::testing::Test {
  17842. protected:
  17843. void SetUp() override {
  17844. svr_.Get("/keepalive", [](const Request &, Response &res) {
  17845. res.set_content("ok", "text/plain");
  17846. });
  17847. port_ = svr_.bind_to_any_port(HOST);
  17848. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17849. svr_.wait_until_ready();
  17850. }
  17851. void TearDown() override {
  17852. svr_.stop();
  17853. if (thread_.joinable()) { thread_.join(); }
  17854. }
  17855. Server svr_;
  17856. int port_ = 0;
  17857. thread thread_;
  17858. };
  17859. // "close" alongside another option still closes the connection, and the
  17860. // response says so rather than leaving the peer to discover it.
  17861. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  17862. bool announced_close = false;
  17863. bool reusable = true;
  17864. probe_connection_reuse(port_,
  17865. "GET /keepalive HTTP/1.1\r\n"
  17866. "Host: localhost\r\n"
  17867. "Connection: keep-alive, close\r\n"
  17868. "\r\n",
  17869. &announced_close, &reusable);
  17870. EXPECT_TRUE(announced_close);
  17871. EXPECT_FALSE(reusable);
  17872. }
  17873. // "close" split over two field lines is the same list, so it is honored too.
  17874. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  17875. bool announced_close = false;
  17876. bool reusable = true;
  17877. probe_connection_reuse(port_,
  17878. "GET /keepalive HTTP/1.1\r\n"
  17879. "Host: localhost\r\n"
  17880. "Connection: keep-alive\r\n"
  17881. "Connection: close\r\n"
  17882. "\r\n",
  17883. &announced_close, &reusable);
  17884. EXPECT_TRUE(announced_close);
  17885. EXPECT_FALSE(reusable);
  17886. }
  17887. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  17888. // keep-alive in the spelling everyone actually sends keeps its connection.
  17889. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  17890. bool announced_close = false;
  17891. bool reusable = false;
  17892. probe_connection_reuse(port_,
  17893. "GET /keepalive HTTP/1.0\r\n"
  17894. "Host: localhost\r\n"
  17895. "Connection: keep-alive\r\n"
  17896. "\r\n",
  17897. &announced_close, &reusable);
  17898. EXPECT_FALSE(announced_close);
  17899. EXPECT_TRUE(reusable);
  17900. }
  17901. // A token the value merely contains is not the token itself.
  17902. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  17903. bool announced_close = false;
  17904. bool reusable = false;
  17905. probe_connection_reuse(port_,
  17906. "GET /keepalive HTTP/1.1\r\n"
  17907. "Host: localhost\r\n"
  17908. "Connection: notclose\r\n"
  17909. "\r\n",
  17910. &announced_close, &reusable);
  17911. EXPECT_FALSE(announced_close);
  17912. EXPECT_TRUE(reusable);
  17913. }
  17914. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  17915. Server svr;
  17916. std::vector<std::string> observed_types;
  17917. svr.Get("/", [&](const Request &req, Response &res) {
  17918. observed_types = req.accept_content_types;
  17919. res.set_content("ok", "text/plain");
  17920. });
  17921. auto port = svr.bind_to_any_port(HOST);
  17922. thread t = thread([&]() { svr.listen_after_bind(); });
  17923. auto se = detail::scope_exit([&] {
  17924. svr.stop();
  17925. t.join();
  17926. ASSERT_FALSE(svr.is_running());
  17927. });
  17928. svr.wait_until_ready();
  17929. Client cli(HOST, port);
  17930. Headers headers;
  17931. headers.emplace("Accept", "text/plain;q=0.5");
  17932. headers.emplace("Accept", "application/json");
  17933. auto res = cli.Get("/", headers);
  17934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17935. EXPECT_EQ(StatusCode::OK_200, res->status);
  17936. // Sorted by q-value, so the second field line's type comes first
  17937. ASSERT_EQ(2U, observed_types.size());
  17938. EXPECT_EQ("application/json", observed_types[0]);
  17939. EXPECT_EQ("text/plain", observed_types[1]);
  17940. }
  17941. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  17942. // empty field line must not contribute a bare comma to the combined value.
  17943. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  17944. Server svr;
  17945. std::vector<std::string> observed_types;
  17946. svr.Get("/", [&](const Request &req, Response &res) {
  17947. observed_types = req.accept_content_types;
  17948. res.set_content("ok", "text/plain");
  17949. });
  17950. auto port = svr.bind_to_any_port(HOST);
  17951. thread t = thread([&]() { svr.listen_after_bind(); });
  17952. auto se = detail::scope_exit([&] {
  17953. svr.stop();
  17954. t.join();
  17955. ASSERT_FALSE(svr.is_running());
  17956. });
  17957. svr.wait_until_ready();
  17958. // Empty first field line, then a real one
  17959. std::string raw_req = "GET / HTTP/1.1\r\n"
  17960. "Host: localhost\r\n"
  17961. "Accept:\r\n"
  17962. "Accept: application/json\r\n"
  17963. "Connection: close\r\n"
  17964. "\r\n";
  17965. std::string out;
  17966. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  17967. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  17968. ASSERT_EQ(1U, observed_types.size());
  17969. EXPECT_EQ("application/json", observed_types[0]);
  17970. }
  17971. // The skip in get_combined_header_value() is what keeps an empty field line
  17972. // from contributing a bare comma. Only a trailing empty field line exercises
  17973. // it: a leading one is already covered by the "combined is still empty" check,
  17974. // and parse_accept_header() now ignores the empty element either way, so the
  17975. // request-level test above can no longer tell the two apart.
  17976. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  17977. Headers headers;
  17978. headers.emplace("Accept", "text/html");
  17979. headers.emplace("Accept", "");
  17980. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  17981. headers.clear();
  17982. headers.emplace("Accept", "");
  17983. headers.emplace("Accept", "application/json");
  17984. EXPECT_EQ("application/json",
  17985. detail::get_combined_header_value(headers, "Accept"));
  17986. }
  17987. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17988. // An encoding offered on a later Accept-Encoding field line is still offered.
  17989. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  17990. Server svr;
  17991. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17992. res.set_content(std::string(1024, 'x'), "text/plain");
  17993. });
  17994. auto port = svr.bind_to_any_port(HOST);
  17995. thread t = thread([&]() { svr.listen_after_bind(); });
  17996. auto se = detail::scope_exit([&] {
  17997. svr.stop();
  17998. t.join();
  17999. ASSERT_FALSE(svr.is_running());
  18000. });
  18001. svr.wait_until_ready();
  18002. Client cli(HOST, port);
  18003. cli.set_decompress(false);
  18004. Headers headers;
  18005. headers.emplace("Accept-Encoding", "identity");
  18006. headers.emplace("Accept-Encoding", "gzip");
  18007. auto res = cli.Get("/", headers);
  18008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18009. EXPECT_EQ(StatusCode::OK_200, res->status);
  18010. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  18011. }
  18012. #endif
  18013. #ifndef _WIN32
  18014. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  18015. Server svr;
  18016. svr.Post("/post", [&](const Request &req, Response &res) {
  18017. res.set_content(req.body, "text/plain");
  18018. });
  18019. svr.Put("/put", [&](const Request &req, Response &res) {
  18020. res.set_content(req.body, "text/plain");
  18021. });
  18022. svr.Patch("/patch", [&](const Request &req, Response &res) {
  18023. res.set_content(req.body, "text/plain");
  18024. });
  18025. svr.Delete("/delete", [&](const Request &req, Response &res) {
  18026. res.set_content(req.body, "text/plain");
  18027. });
  18028. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18029. auto se = detail::scope_exit([&] {
  18030. svr.stop();
  18031. t.join();
  18032. ASSERT_FALSE(svr.is_running());
  18033. });
  18034. svr.wait_until_ready();
  18035. std::string resp;
  18036. // POST without Content-Length
  18037. ASSERT_TRUE(send_request(5,
  18038. "POST /post HTTP/1.1\r\n"
  18039. "Host: localhost\r\n"
  18040. "Connection: close\r\n"
  18041. "\r\n",
  18042. &resp));
  18043. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18044. // PUT without Content-Length
  18045. resp.clear();
  18046. ASSERT_TRUE(send_request(5,
  18047. "PUT /put HTTP/1.1\r\n"
  18048. "Host: localhost\r\n"
  18049. "Connection: close\r\n"
  18050. "\r\n",
  18051. &resp));
  18052. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18053. // PATCH without Content-Length
  18054. resp.clear();
  18055. ASSERT_TRUE(send_request(5,
  18056. "PATCH /patch HTTP/1.1\r\n"
  18057. "Host: localhost\r\n"
  18058. "Connection: close\r\n"
  18059. "\r\n",
  18060. &resp));
  18061. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18062. // DELETE without Content-Length
  18063. resp.clear();
  18064. ASSERT_TRUE(send_request(5,
  18065. "DELETE /delete HTTP/1.1\r\n"
  18066. "Host: localhost\r\n"
  18067. "Connection: close\r\n"
  18068. "\r\n",
  18069. &resp));
  18070. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  18071. }
  18072. #endif
  18073. //==============================================================================
  18074. // open_stream() Tests
  18075. //==============================================================================
  18076. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  18077. std::string result;
  18078. char buf[8192];
  18079. ssize_t n;
  18080. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  18081. result.append(buf, static_cast<size_t>(n));
  18082. }
  18083. return result;
  18084. }
  18085. // Mock stream for unit tests
  18086. class MockStream : public Stream {
  18087. public:
  18088. std::string data;
  18089. size_t pos = 0;
  18090. ssize_t error_after = -1; // -1 = no error
  18091. explicit MockStream(const std::string &d, ssize_t err = -1)
  18092. : data(d), error_after(err) {}
  18093. bool is_readable() const override { return true; }
  18094. bool wait_readable() const override { return true; }
  18095. bool wait_writable() const override { return true; }
  18096. ssize_t read(char *ptr, size_t size) override {
  18097. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  18098. if (pos >= data.size()) return 0;
  18099. size_t limit =
  18100. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  18101. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  18102. std::memcpy(ptr, data.data() + pos, to_read);
  18103. pos += to_read;
  18104. return static_cast<ssize_t>(to_read);
  18105. }
  18106. ssize_t write(const char *, size_t) override { return -1; }
  18107. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  18108. ip = "127.0.0.1";
  18109. port = 0;
  18110. }
  18111. void get_local_ip_and_port(std::string &ip, int &port) const override {
  18112. ip = "127.0.0.1";
  18113. port = 0;
  18114. }
  18115. socket_t socket() const override { return INVALID_SOCKET; }
  18116. time_t duration() const override { return 0; }
  18117. };
  18118. TEST(StreamHandleTest, Basic) {
  18119. ClientImpl::StreamHandle handle;
  18120. EXPECT_FALSE(handle.is_valid());
  18121. handle.response = detail::make_unique<Response>();
  18122. handle.error = Error::Connection;
  18123. EXPECT_FALSE(handle.is_valid());
  18124. handle.error = Error::Success;
  18125. EXPECT_TRUE(handle.is_valid());
  18126. }
  18127. TEST(BodyReaderTest, Basic) {
  18128. MockStream stream("Hello, World!");
  18129. detail::BodyReader reader;
  18130. reader.stream = &stream;
  18131. reader.content_length = 13;
  18132. char buf[32];
  18133. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  18134. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  18135. EXPECT_TRUE(reader.eof);
  18136. }
  18137. TEST(BodyReaderTest, NoStream) {
  18138. detail::BodyReader reader;
  18139. char buf[32];
  18140. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18141. EXPECT_EQ(Error::Connection, reader.last_error);
  18142. }
  18143. TEST(BodyReaderTest, Error) {
  18144. MockStream stream("Hello, World!", 5);
  18145. detail::BodyReader reader;
  18146. reader.stream = &stream;
  18147. reader.content_length = 13;
  18148. char buf[32];
  18149. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  18150. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  18151. EXPECT_EQ(Error::Read, reader.last_error);
  18152. }
  18153. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  18154. // Mock-based StreamHandle tests relying on private internals are removed.
  18155. class OpenStreamTest : public ::testing::Test {
  18156. protected:
  18157. void SetUp() override {
  18158. svr_.Get("/hello", [](const Request &, Response &res) {
  18159. res.set_content("Hello World!", "text/plain");
  18160. });
  18161. svr_.Get("/large", [](const Request &, Response &res) {
  18162. res.set_content(std::string(10000, 'X'), "text/plain");
  18163. });
  18164. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  18165. res.set_content("Hello World!", "image/jpeg");
  18166. res.set_header("Content-Encoding", "UTF-8");
  18167. });
  18168. svr_.Get("/chunked", [](const Request &, Response &res) {
  18169. res.set_chunked_content_provider("text/plain",
  18170. [](size_t offset, DataSink &sink) {
  18171. if (offset < 15) {
  18172. sink.write("chunk", 5);
  18173. return true;
  18174. }
  18175. sink.done();
  18176. return true;
  18177. });
  18178. });
  18179. svr_.Get("/compressible", [](const Request &, Response &res) {
  18180. res.set_chunked_content_provider("text/plain", [](size_t offset,
  18181. DataSink &sink) {
  18182. if (offset < 100 * 1024) {
  18183. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  18184. sink.write(chunk.data(), chunk.size());
  18185. return true;
  18186. }
  18187. sink.done();
  18188. return true;
  18189. });
  18190. });
  18191. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  18192. [](const Request & /*req*/, Response &res) {
  18193. auto i = new int(0);
  18194. res.set_header("Trailer", "Content-Length, X-Allowed");
  18195. res.set_chunked_content_provider(
  18196. "text/plain",
  18197. [i](size_t /*offset*/, DataSink &sink) {
  18198. switch (*i) {
  18199. case 0: sink.os << "123"; break;
  18200. case 1: sink.os << "456"; break;
  18201. case 2: sink.os << "789"; break;
  18202. case 3: {
  18203. sink.done_with_trailer(
  18204. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  18205. } break;
  18206. }
  18207. (*i)++;
  18208. return true;
  18209. },
  18210. [i](bool success) {
  18211. EXPECT_TRUE(success);
  18212. delete i;
  18213. });
  18214. });
  18215. // Echo headers endpoint for header-related tests
  18216. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  18217. std::string body;
  18218. for (const auto &h : req.headers) {
  18219. body.append(h.first);
  18220. body.push_back(':');
  18221. body.append(h.second);
  18222. body.push_back('\n');
  18223. }
  18224. res.set_content(body, "text/plain");
  18225. });
  18226. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  18227. std::string body;
  18228. for (const auto &h : req.headers) {
  18229. body.append(h.first);
  18230. body.push_back(':');
  18231. body.append(h.second);
  18232. body.push_back('\n');
  18233. }
  18234. res.set_content(body, "text/plain");
  18235. });
  18236. port_ = svr_.bind_to_any_port("127.0.0.1");
  18237. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18238. svr_.wait_until_ready();
  18239. }
  18240. void TearDown() override {
  18241. svr_.stop();
  18242. if (thread_.joinable()) thread_.join();
  18243. }
  18244. Server svr_;
  18245. std::thread thread_;
  18246. int port_ = 0;
  18247. };
  18248. TEST_F(OpenStreamTest, Basic) {
  18249. Client cli("127.0.0.1", port_);
  18250. auto handle = cli.open_stream("GET", "/hello");
  18251. EXPECT_TRUE(handle.is_valid());
  18252. EXPECT_EQ("Hello World!", read_all(handle));
  18253. }
  18254. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  18255. Client cli("127.0.0.1", port_);
  18256. auto handle = cli.open_stream("GET", "/unknown-encoding");
  18257. ASSERT_TRUE(handle.is_valid());
  18258. EXPECT_EQ("Hello World!", read_all(handle));
  18259. }
  18260. TEST_F(OpenStreamTest, SmallBuffer) {
  18261. Client cli("127.0.0.1", port_);
  18262. auto handle = cli.open_stream("GET", "/hello");
  18263. std::string result;
  18264. char buf[4];
  18265. ssize_t n;
  18266. while ((n = handle.read(buf, sizeof(buf))) > 0)
  18267. result.append(buf, static_cast<size_t>(n));
  18268. EXPECT_EQ("Hello World!", result);
  18269. }
  18270. TEST_F(OpenStreamTest, DefaultHeaders) {
  18271. Client cli("127.0.0.1", port_);
  18272. // open_stream GET should include Host, User-Agent and Accept-Encoding
  18273. {
  18274. auto handle = cli.open_stream("GET", "/echo-headers");
  18275. ASSERT_TRUE(handle.is_valid());
  18276. auto body = read_all(handle);
  18277. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  18278. std::string::npos);
  18279. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  18280. std::string::npos);
  18281. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  18282. }
  18283. // open_stream POST with body and no explicit content_type should NOT add
  18284. // text/plain Content-Type (behavior differs from non-streaming path), but
  18285. // should include Content-Length
  18286. {
  18287. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  18288. ASSERT_TRUE(handle.is_valid());
  18289. auto body = read_all(handle);
  18290. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  18291. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  18292. }
  18293. // open_stream POST with explicit Content-Type should preserve it
  18294. {
  18295. auto handle = cli.open_stream("POST", "/echo-headers", {},
  18296. {{"Content-Type", "application/custom"}},
  18297. "{}", "application/custom");
  18298. ASSERT_TRUE(handle.is_valid());
  18299. auto body = read_all(handle);
  18300. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  18301. }
  18302. // User-specified User-Agent must not be overwritten for stream API
  18303. {
  18304. auto handle = cli.open_stream("GET", "/echo-headers", {},
  18305. {{"User-Agent", "MyAgent/1.2"}});
  18306. ASSERT_TRUE(handle.is_valid());
  18307. auto body = read_all(handle);
  18308. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  18309. }
  18310. }
  18311. TEST_F(OpenStreamTest, Large) {
  18312. Client cli("127.0.0.1", port_);
  18313. auto handle = cli.open_stream("GET", "/large");
  18314. EXPECT_EQ(10000u, read_all(handle).size());
  18315. }
  18316. TEST_F(OpenStreamTest, ConnectionError) {
  18317. Client cli("127.0.0.1", 9999);
  18318. auto handle = cli.open_stream("GET", "/hello");
  18319. EXPECT_FALSE(handle.is_valid());
  18320. }
  18321. TEST_F(OpenStreamTest, Chunked) {
  18322. Client cli("127.0.0.1", port_);
  18323. auto handle = cli.open_stream("GET", "/chunked");
  18324. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18325. "Transfer-Encoding") == "chunked");
  18326. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  18327. }
  18328. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  18329. Client cli("127.0.0.1", port_);
  18330. auto handle =
  18331. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  18332. ASSERT_TRUE(handle.is_valid());
  18333. // Consume body to allow trailers to be received/parsed
  18334. auto body = read_all(handle);
  18335. // Explicitly parse trailers (ensure trailers are available for assertion)
  18336. handle.parse_trailers_if_needed();
  18337. EXPECT_EQ(std::string("123456789"), body);
  18338. // The response should include a Trailer header declaring both names
  18339. ASSERT_TRUE(handle.response);
  18340. EXPECT_TRUE(handle.response->has_header("Trailer"));
  18341. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  18342. handle.response->get_header_value("Trailer"));
  18343. // Prohibited trailer must not be present
  18344. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  18345. // Allowed trailer should be present
  18346. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  18347. EXPECT_EQ(std::string("yes"),
  18348. handle.response->get_trailer_value("X-Allowed"));
  18349. // Verify trailers are NOT present as regular headers
  18350. EXPECT_EQ(std::string(""),
  18351. handle.response->get_header_value("Content-Length"));
  18352. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  18353. }
  18354. static std::thread serve_single_response(std::promise<int> &port_promise,
  18355. const std::string &response) {
  18356. return std::thread([&port_promise, response] {
  18357. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18358. default_socket_options(srv);
  18359. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  18360. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  18361. sockaddr_in addr{};
  18362. addr.sin_family = AF_INET;
  18363. addr.sin_port = htons(0); // Let OS assign a free port
  18364. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18365. int opt = 1;
  18366. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  18367. #ifdef _WIN32
  18368. reinterpret_cast<const char *>(&opt),
  18369. #else
  18370. &opt,
  18371. #endif
  18372. sizeof(opt));
  18373. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  18374. ::listen(srv, 1) != 0) {
  18375. port_promise.set_value(-1);
  18376. detail::close_socket(srv);
  18377. return;
  18378. }
  18379. socklen_t addr_len = sizeof(addr);
  18380. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  18381. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  18382. sockaddr_in cli_addr{};
  18383. socklen_t cli_len = sizeof(cli_addr);
  18384. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18385. if (cli != INVALID_SOCKET) {
  18386. // Read the complete HTTP request (until the blank line that terminates
  18387. // headers) before sending the response. If the server closes the socket
  18388. // while the client's request data is still unread in the kernel receive
  18389. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  18390. // connection on both sides: it discards the client's receive buffer
  18391. // (which already holds our response) and causes any in-progress write on
  18392. // the client to fail with ECONNRESET. Reading all request data first
  18393. // ensures close() emits a graceful FIN.
  18394. {
  18395. char rbuf[256];
  18396. std::string req;
  18397. while (req.find("\r\n\r\n") == std::string::npos) {
  18398. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  18399. if (n <= 0) { break; }
  18400. req.append(rbuf, static_cast<size_t>(n));
  18401. }
  18402. }
  18403. ::send(cli,
  18404. #ifdef _WIN32
  18405. static_cast<const char *>(response.c_str()),
  18406. static_cast<int>(response.size()),
  18407. #else
  18408. response.c_str(), response.size(),
  18409. #endif
  18410. 0);
  18411. detail::close_socket(cli);
  18412. }
  18413. detail::close_socket(srv);
  18414. });
  18415. }
  18416. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  18417. #ifndef _WIN32
  18418. signal(SIGPIPE, SIG_IGN);
  18419. #endif
  18420. std::promise<int> port_promise;
  18421. auto port_future = port_promise.get_future();
  18422. auto server_thread =
  18423. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  18424. "Content-Type: text/plain\r\n"
  18425. "Content-Length: not-a-number\r\n"
  18426. "Connection: close\r\n"
  18427. "\r\n"
  18428. "hello");
  18429. auto port = port_future.get();
  18430. ASSERT_GT(port, 0);
  18431. Client cli("127.0.0.1", port);
  18432. auto handle = cli.open_stream("GET", "/");
  18433. EXPECT_FALSE(handle.is_valid());
  18434. server_thread.join();
  18435. }
  18436. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  18437. #ifndef _WIN32
  18438. signal(SIGPIPE, SIG_IGN);
  18439. #endif
  18440. std::promise<int> port_promise;
  18441. auto port_future = port_promise.get_future();
  18442. auto server_thread = serve_single_response(
  18443. port_promise, "HTTP/1.1 200 OK\r\n"
  18444. "Content-Type: text/plain\r\n"
  18445. "Content-Length: 99999999999999999999999999\r\n"
  18446. "Connection: close\r\n"
  18447. "\r\n"
  18448. "hello");
  18449. auto port = port_future.get();
  18450. ASSERT_GT(port, 0);
  18451. // Historically std::stoull would throw std::out_of_range here and crash
  18452. // the process, then parsing silently clamped to a bogus framing length and
  18453. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  18454. // so the stream fails to open, matching the not-a-number case above. The
  18455. // process still must NOT terminate.
  18456. Client cli("127.0.0.1", port);
  18457. auto handle = cli.open_stream("GET", "/");
  18458. EXPECT_FALSE(handle.is_valid());
  18459. server_thread.join();
  18460. }
  18461. // Serves `response` to the single request `fn` makes with a fresh client.
  18462. template <typename Fn>
  18463. static void with_single_response(const std::string &response, Fn fn) {
  18464. #ifndef _WIN32
  18465. signal(SIGPIPE, SIG_IGN);
  18466. #endif
  18467. std::promise<int> port_promise;
  18468. auto port_future = port_promise.get_future();
  18469. auto server_thread = serve_single_response(port_promise, response);
  18470. auto se = detail::scope_exit([&] { server_thread.join(); });
  18471. auto port = port_future.get();
  18472. ASSERT_GT(port, 0);
  18473. Client cli("127.0.0.1", port);
  18474. fn(cli);
  18475. }
  18476. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  18477. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  18478. // the chunked coding and drop Content-Length, so a front-end that trusts
  18479. // Content-Length would disagree about where the body ends (response
  18480. // smuggling). The client must reject such a response.
  18481. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  18482. for (const char *te : {"chunked", "gzip, chunked"}) {
  18483. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  18484. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  18485. "\r\n" + "Connection: close\r\n" + "\r\n" +
  18486. "5\r\nhello\r\n0\r\n\r\n";
  18487. with_single_response(response, [&](Client &cli) {
  18488. auto res = cli.Get("/");
  18489. EXPECT_FALSE(static_cast<bool>(res)) << te;
  18490. EXPECT_EQ(Error::Read, res.error()) << te;
  18491. });
  18492. with_single_response(response, [&](Client &cli) {
  18493. auto handle = cli.open_stream("GET", "/");
  18494. EXPECT_FALSE(handle.is_valid()) << te;
  18495. EXPECT_EQ(Error::Read, handle.error) << te;
  18496. });
  18497. }
  18498. }
  18499. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  18500. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  18501. // closing the connection (unlike a request, which must be rejected).
  18502. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  18503. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18504. "Transfer-Encoding: chunked\r\n"
  18505. "Connection: close\r\n"
  18506. "\r\n"
  18507. "5\r\nhello\r\n0\r\n\r\n",
  18508. "HTTP/1.1 200 OK\r\n"
  18509. "Transfer-Encoding: gzip\r\n"
  18510. "Connection: close\r\n"
  18511. "\r\n"
  18512. "hello"}) {
  18513. with_single_response(response, [&](Client &cli) {
  18514. auto res = cli.Get("/");
  18515. ASSERT_TRUE(static_cast<bool>(res)) << response;
  18516. EXPECT_EQ("hello", res->body);
  18517. });
  18518. with_single_response(response, [&](Client &cli) {
  18519. auto handle = cli.open_stream("GET", "/");
  18520. ASSERT_TRUE(handle.is_valid()) << response;
  18521. EXPECT_EQ("hello", read_all(handle));
  18522. });
  18523. }
  18524. }
  18525. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  18526. // framing headers describe nothing to read and must not be rejected.
  18527. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  18528. const std::string framing = "Content-Length: 5\r\n"
  18529. "Transfer-Encoding: chunked\r\n"
  18530. "Connection: close\r\n"
  18531. "\r\n";
  18532. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18533. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  18534. });
  18535. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  18536. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  18537. });
  18538. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  18539. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  18540. with_single_response(response, [&](Client &cli) {
  18541. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  18542. });
  18543. with_single_response(response, [&](Client &cli) {
  18544. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  18545. });
  18546. }
  18547. }
  18548. // A payload max length of 0 means no limit, however the body is framed.
  18549. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  18550. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  18551. "Transfer-Encoding: chunked\r\n"
  18552. "\r\n"
  18553. "5\r\nhello\r\n0\r\n\r\n",
  18554. "HTTP/1.1 200 OK\r\n"
  18555. "Connection: close\r\n"
  18556. "\r\n"
  18557. "hello"}) {
  18558. with_single_response(response, [&](Client &cli) {
  18559. cli.set_payload_max_length(0);
  18560. auto res = cli.Get("/");
  18561. ASSERT_TRUE(res) << response;
  18562. EXPECT_EQ("hello", res->body) << response;
  18563. });
  18564. }
  18565. }
  18566. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  18567. Server svr;
  18568. svr.set_payload_max_length(0);
  18569. svr.Post("/echo", [](const Request &req, Response &res) {
  18570. res.set_content(req.body, "text/plain");
  18571. });
  18572. auto port = svr.bind_to_any_port(HOST);
  18573. thread t = thread([&] { svr.listen_after_bind(); });
  18574. auto se = detail::scope_exit([&] {
  18575. svr.stop();
  18576. t.join();
  18577. ASSERT_FALSE(svr.is_running());
  18578. });
  18579. svr.wait_until_ready();
  18580. Client cli(HOST, port);
  18581. auto res = cli.Post(
  18582. "/echo",
  18583. [](size_t /*offset*/, DataSink &sink) {
  18584. sink.write("hello", 5);
  18585. sink.done();
  18586. return true;
  18587. },
  18588. "text/plain");
  18589. ASSERT_TRUE(res);
  18590. EXPECT_EQ(StatusCode::OK_200, res->status);
  18591. EXPECT_EQ("hello", res->body);
  18592. }
  18593. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18594. TEST_F(OpenStreamTest, Gzip) {
  18595. Client cli("127.0.0.1", port_);
  18596. auto handle = cli.open_stream("GET", "/compressible", {},
  18597. {{"Accept-Encoding", "gzip"}});
  18598. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  18599. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18600. }
  18601. #endif
  18602. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18603. TEST_F(OpenStreamTest, Brotli) {
  18604. Client cli("127.0.0.1", port_);
  18605. auto handle =
  18606. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  18607. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  18608. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18609. }
  18610. #endif
  18611. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18612. TEST_F(OpenStreamTest, Zstd) {
  18613. Client cli("127.0.0.1", port_);
  18614. auto handle = cli.open_stream("GET", "/compressible", {},
  18615. {{"Accept-Encoding", "zstd"}});
  18616. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  18617. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  18618. }
  18619. #endif
  18620. #ifdef CPPHTTPLIB_SSL_ENABLED
  18621. class SSLOpenStreamTest : public ::testing::Test {
  18622. protected:
  18623. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  18624. void SetUp() override {
  18625. svr_.Get("/hello", [](const Request &, Response &res) {
  18626. res.set_content("Hello SSL World!", "text/plain");
  18627. });
  18628. svr_.Get("/chunked", [](const Request &, Response &res) {
  18629. res.set_chunked_content_provider("text/plain",
  18630. [](size_t offset, DataSink &sink) {
  18631. if (offset < 15) {
  18632. sink.write("chunk", 5);
  18633. return true;
  18634. }
  18635. sink.done();
  18636. return true;
  18637. });
  18638. });
  18639. svr_.Post("/echo", [](const Request &req, Response &res) {
  18640. res.set_content(req.body, req.get_header_value("Content-Type"));
  18641. });
  18642. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  18643. std::string body = req.body;
  18644. res.set_chunked_content_provider(
  18645. "text/plain", [body](size_t offset, DataSink &sink) {
  18646. if (offset < body.size()) {
  18647. sink.write(body.data() + offset, body.size() - offset);
  18648. }
  18649. sink.done();
  18650. return true;
  18651. });
  18652. });
  18653. port_ = svr_.bind_to_any_port("127.0.0.1");
  18654. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  18655. svr_.wait_until_ready();
  18656. }
  18657. void TearDown() override {
  18658. svr_.stop();
  18659. if (thread_.joinable()) thread_.join();
  18660. }
  18661. SSLServer svr_;
  18662. std::thread thread_;
  18663. int port_ = 0;
  18664. };
  18665. TEST_F(SSLOpenStreamTest, Basic) {
  18666. SSLClient cli("127.0.0.1", port_);
  18667. cli.enable_server_certificate_verification(false);
  18668. auto handle = cli.open_stream("GET", "/hello");
  18669. ASSERT_TRUE(handle.is_valid());
  18670. EXPECT_EQ("Hello SSL World!", read_all(handle));
  18671. }
  18672. TEST_F(SSLOpenStreamTest, Chunked) {
  18673. SSLClient cli("127.0.0.1", port_);
  18674. cli.enable_server_certificate_verification(false);
  18675. auto handle = cli.open_stream("GET", "/chunked");
  18676. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18677. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  18678. "Transfer-Encoding") == "chunked");
  18679. auto body = read_all(handle);
  18680. EXPECT_EQ("chunkchunkchunk", body);
  18681. }
  18682. TEST_F(SSLOpenStreamTest, Post) {
  18683. SSLClient cli("127.0.0.1", port_);
  18684. cli.enable_server_certificate_verification(false);
  18685. auto handle =
  18686. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  18687. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  18688. EXPECT_EQ(200, handle.response->status);
  18689. auto body = read_all(handle);
  18690. EXPECT_EQ("Hello SSL POST", body);
  18691. }
  18692. TEST_F(SSLOpenStreamTest, PostChunked) {
  18693. SSLClient cli("127.0.0.1", port_);
  18694. cli.enable_server_certificate_verification(false);
  18695. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  18696. "Chunked SSL Data", "text/plain");
  18697. ASSERT_TRUE(handle.is_valid());
  18698. EXPECT_EQ(200, handle.response->status);
  18699. auto body = read_all(handle);
  18700. EXPECT_EQ("Chunked SSL Data", body);
  18701. }
  18702. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  18703. // Content-Length is terminated by the server closing the connection. When the
  18704. // SSL peer sends a close_notify after the body, the client must treat it as a
  18705. // clean EOF and return a successful response rather than an error.
  18706. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  18707. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18708. ASSERT_TRUE(svr.is_valid());
  18709. svr.set_keep_alive_max_count(1);
  18710. const std::string expected_body = "Hello from connection-close response!";
  18711. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  18712. res.set_content_provider("text/plain",
  18713. [&](size_t offset, DataSink &sink) -> bool {
  18714. if (offset < expected_body.size()) {
  18715. sink.write(expected_body.data() + offset,
  18716. expected_body.size() - offset);
  18717. }
  18718. sink.done();
  18719. return true;
  18720. });
  18721. });
  18722. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  18723. auto se = detail::scope_exit([&] {
  18724. svr.stop();
  18725. listen_thread.join();
  18726. ASSERT_FALSE(svr.is_running());
  18727. });
  18728. svr.wait_until_ready();
  18729. SSLClient cli(HOST, PORT);
  18730. cli.enable_server_certificate_verification(false);
  18731. auto res = cli.Get("/no-content-length");
  18732. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  18733. EXPECT_EQ(StatusCode::OK_200, res->status);
  18734. EXPECT_EQ(expected_body, res->body);
  18735. }
  18736. #endif // CPPHTTPLIB_SSL_ENABLED
  18737. //==============================================================================
  18738. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  18739. // results for various scenarios.
  18740. //==============================================================================
  18741. TEST(ParityTest, GetVsOpenStream) {
  18742. Server svr;
  18743. const std::string path = "/parity";
  18744. const std::string content = "Parity test content: hello world";
  18745. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18746. res.set_content(content, "text/plain");
  18747. });
  18748. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18749. auto se = detail::scope_exit([&] {
  18750. svr.stop();
  18751. t.join();
  18752. ASSERT_FALSE(svr.is_running());
  18753. });
  18754. svr.wait_until_ready();
  18755. Client cli(HOST, PORT);
  18756. // Non-stream path
  18757. auto r1 = cli.Get(path);
  18758. ASSERT_TRUE(r1);
  18759. EXPECT_EQ(StatusCode::OK_200, r1->status);
  18760. // Stream path
  18761. auto h = cli.open_stream("GET", path);
  18762. ASSERT_TRUE(h.is_valid());
  18763. EXPECT_EQ(r1->body, read_all(h));
  18764. }
  18765. // Helper to compress data with provided compressor type T
  18766. template <typename Compressor>
  18767. static std::string compress_payload_for_parity(const std::string &in) {
  18768. std::string out;
  18769. Compressor compressor;
  18770. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  18771. [&](const char *data, size_t n) {
  18772. out.append(data, n);
  18773. return true;
  18774. });
  18775. EXPECT_TRUE(ok);
  18776. return out;
  18777. }
  18778. // Helper function for compression parity tests
  18779. template <typename Compressor>
  18780. static void test_compression_parity(const std::string &original,
  18781. const std::string &path,
  18782. const std::string &encoding) {
  18783. const std::string compressed =
  18784. compress_payload_for_parity<Compressor>(original);
  18785. Server svr;
  18786. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  18787. res.set_content(compressed, "application/octet-stream");
  18788. res.set_header("Content-Encoding", encoding);
  18789. });
  18790. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  18791. auto se = detail::scope_exit([&] {
  18792. svr.stop();
  18793. t.join();
  18794. ASSERT_FALSE(svr.is_running());
  18795. });
  18796. svr.wait_until_ready();
  18797. Client cli(HOST, PORT);
  18798. // Non-streaming
  18799. {
  18800. auto res = cli.Get(path);
  18801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18802. EXPECT_EQ(StatusCode::OK_200, res->status);
  18803. EXPECT_EQ(original, res->body);
  18804. }
  18805. // Streaming
  18806. {
  18807. auto h = cli.open_stream("GET", path);
  18808. ASSERT_TRUE(h.is_valid());
  18809. EXPECT_EQ(original, read_all(h));
  18810. }
  18811. }
  18812. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18813. TEST(ParityTest, Gzip) {
  18814. test_compression_parity<detail::gzip_compressor>(
  18815. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  18816. }
  18817. #endif
  18818. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  18819. TEST(ParityTest, Brotli) {
  18820. test_compression_parity<detail::brotli_compressor>(
  18821. "Hello, brotli parity test payload", "/parity-br", "br");
  18822. }
  18823. #endif
  18824. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  18825. TEST(ParityTest, Zstd) {
  18826. test_compression_parity<detail::zstd_compressor>(
  18827. "Zstandard parity test payload", "/parity-zstd", "zstd");
  18828. }
  18829. #endif
  18830. //==============================================================================
  18831. // New Stream API Tests
  18832. //==============================================================================
  18833. inline std::string read_body(httplib::stream::Result &result) {
  18834. std::string body;
  18835. while (result.next()) {
  18836. body.append(result.data(), result.size());
  18837. }
  18838. return body;
  18839. }
  18840. TEST(ClientConnectionTest, Basic) {
  18841. httplib::ClientConnection conn;
  18842. EXPECT_FALSE(conn.is_open());
  18843. conn.sock = 1;
  18844. EXPECT_TRUE(conn.is_open());
  18845. httplib::ClientConnection conn2(std::move(conn));
  18846. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  18847. conn2.sock = INVALID_SOCKET;
  18848. }
  18849. // Unified test server for all stream::* tests
  18850. class StreamApiTest : public ::testing::Test {
  18851. protected:
  18852. void SetUp() override {
  18853. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  18854. res.set_content("Hello World!", "text/plain");
  18855. });
  18856. svr_.Get("/echo-params",
  18857. [](const httplib::Request &req, httplib::Response &res) {
  18858. std::string r;
  18859. for (const auto &p : req.params) {
  18860. if (!r.empty()) r += "&";
  18861. r += p.first + "=" + p.second;
  18862. }
  18863. res.set_content(r, "text/plain");
  18864. });
  18865. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18866. res.set_content(req.body, req.get_header_value("Content-Type"));
  18867. });
  18868. svr_.Post("/echo-headers",
  18869. [](const httplib::Request &req, httplib::Response &res) {
  18870. std::string r;
  18871. for (const auto &h : req.headers)
  18872. r += h.first + ": " + h.second + "\n";
  18873. res.set_content(r, "text/plain");
  18874. });
  18875. svr_.Post("/echo-params",
  18876. [](const httplib::Request &req, httplib::Response &res) {
  18877. std::string r = "params:";
  18878. for (const auto &p : req.params)
  18879. r += p.first + "=" + p.second + ";";
  18880. res.set_content(r + " body:" + req.body, "text/plain");
  18881. });
  18882. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  18883. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  18884. });
  18885. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  18886. res.set_content("PUT:" + req.body, "text/plain");
  18887. });
  18888. svr_.Patch("/echo",
  18889. [](const httplib::Request &req, httplib::Response &res) {
  18890. res.set_content("PATCH:" + req.body, "text/plain");
  18891. });
  18892. svr_.Delete(
  18893. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  18894. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  18895. "text/plain");
  18896. });
  18897. svr_.Get("/head-test",
  18898. [](const httplib::Request &, httplib::Response &res) {
  18899. res.set_content("body for HEAD", "text/plain");
  18900. });
  18901. svr_.Options("/options",
  18902. [](const httplib::Request &, httplib::Response &res) {
  18903. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  18904. });
  18905. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  18906. svr_.wait_until_ready();
  18907. }
  18908. void TearDown() override {
  18909. svr_.stop();
  18910. if (thread_.joinable()) thread_.join();
  18911. }
  18912. httplib::Server svr_;
  18913. std::thread thread_;
  18914. };
  18915. // stream::Get tests
  18916. TEST_F(StreamApiTest, GetBasic) {
  18917. httplib::Client cli(HOST, PORT);
  18918. auto result = httplib::stream::Get(cli, "/hello");
  18919. ASSERT_TRUE(result.is_valid());
  18920. EXPECT_EQ(200, result.status());
  18921. EXPECT_EQ("Hello World!", read_body(result));
  18922. }
  18923. TEST_F(StreamApiTest, GetWithParams) {
  18924. httplib::Client cli(HOST, PORT);
  18925. httplib::Params params{{"foo", "bar"}};
  18926. auto result = httplib::stream::Get(cli, "/echo-params", params);
  18927. ASSERT_TRUE(result.is_valid());
  18928. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  18929. }
  18930. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  18931. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  18932. httplib::Client cli(HOST, PORT);
  18933. cli.set_payload_max_length(0);
  18934. auto result = httplib::stream::Get(cli, "/hello");
  18935. ASSERT_TRUE(result.is_valid());
  18936. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  18937. EXPECT_EQ("Hello World!", read_body(result));
  18938. }
  18939. #endif
  18940. TEST_F(StreamApiTest, GetConnectionError) {
  18941. httplib::Client cli(HOST, 9999);
  18942. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  18943. }
  18944. TEST_F(StreamApiTest, Get404) {
  18945. httplib::Client cli(HOST, PORT);
  18946. auto result = httplib::stream::Get(cli, "/nonexistent");
  18947. EXPECT_TRUE(result.is_valid());
  18948. EXPECT_EQ(404, result.status());
  18949. }
  18950. // stream::Post tests
  18951. TEST_F(StreamApiTest, PostBasic) {
  18952. httplib::Client cli(HOST, PORT);
  18953. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  18954. "application/json");
  18955. ASSERT_TRUE(result.is_valid());
  18956. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  18957. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  18958. }
  18959. TEST_F(StreamApiTest, PostWithHeaders) {
  18960. httplib::Client cli(HOST, PORT);
  18961. httplib::Headers headers{{"X-Custom", "value"}};
  18962. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  18963. "text/plain");
  18964. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  18965. }
  18966. TEST_F(StreamApiTest, PostWithParams) {
  18967. httplib::Client cli(HOST, PORT);
  18968. httplib::Params params{{"k", "v"}};
  18969. auto result =
  18970. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  18971. auto body = read_body(result);
  18972. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  18973. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  18974. }
  18975. TEST_F(StreamApiTest, PostLarge) {
  18976. httplib::Client cli(HOST, PORT);
  18977. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  18978. size_t total = 0;
  18979. while (result.next()) {
  18980. total += result.size();
  18981. }
  18982. EXPECT_EQ(100u * 1024u, total);
  18983. }
  18984. // stream::Put/Patch tests
  18985. TEST_F(StreamApiTest, PutAndPatch) {
  18986. httplib::Client cli(HOST, PORT);
  18987. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  18988. EXPECT_EQ("PUT:test", read_body(put));
  18989. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  18990. EXPECT_EQ("PATCH:test", read_body(patch));
  18991. }
  18992. // stream::Delete tests
  18993. TEST_F(StreamApiTest, Delete) {
  18994. httplib::Client cli(HOST, PORT);
  18995. auto del1 = httplib::stream::Delete(cli, "/resource");
  18996. EXPECT_EQ("Deleted", read_body(del1));
  18997. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  18998. EXPECT_EQ("Deleted:data", read_body(del2));
  18999. }
  19000. // stream::Head/Options tests
  19001. TEST_F(StreamApiTest, HeadAndOptions) {
  19002. httplib::Client cli(HOST, PORT);
  19003. auto head = httplib::stream::Head(cli, "/head-test");
  19004. EXPECT_TRUE(head.is_valid());
  19005. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  19006. auto opts = httplib::stream::Options(cli, "/options");
  19007. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  19008. }
  19009. // SSL stream::* tests
  19010. #ifdef CPPHTTPLIB_SSL_ENABLED
  19011. class SSLStreamApiTest : public ::testing::Test {
  19012. protected:
  19013. void SetUp() override {
  19014. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  19015. res.set_content("Hello SSL!", "text/plain");
  19016. });
  19017. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  19018. res.set_content(req.body, "text/plain");
  19019. });
  19020. port_ = svr_.bind_to_any_port("127.0.0.1");
  19021. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19022. svr_.wait_until_ready();
  19023. }
  19024. void TearDown() override {
  19025. svr_.stop();
  19026. if (thread_.joinable()) thread_.join();
  19027. }
  19028. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  19029. std::thread thread_;
  19030. int port_ = 0;
  19031. };
  19032. TEST_F(SSLStreamApiTest, GetAndPost) {
  19033. httplib::SSLClient cli("127.0.0.1", port_);
  19034. cli.enable_server_certificate_verification(false);
  19035. auto get = httplib::stream::Get(cli, "/hello");
  19036. EXPECT_EQ("Hello SSL!", read_body(get));
  19037. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  19038. EXPECT_EQ("test", read_body(post));
  19039. }
  19040. #endif
  19041. // Tests for Error::Timeout and Error::ConnectionClosed error types
  19042. // These errors are set in SocketStream/SSLSocketStream and propagated through
  19043. // BodyReader
  19044. TEST(ErrorHandlingTest, StreamReadTimeout) {
  19045. // Test that read timeout during streaming is detected
  19046. // Use a large content-length response where server delays mid-stream
  19047. Server svr;
  19048. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19049. // Send a large response with delay in the middle
  19050. res.set_content_provider(
  19051. 1000, // content_length
  19052. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  19053. if (offset < 100) {
  19054. // Send first 100 bytes immediately
  19055. std::string data(100, 'A');
  19056. sink.write(data.c_str(), data.size());
  19057. return true;
  19058. }
  19059. // Then delay longer than client timeout
  19060. std::this_thread::sleep_for(std::chrono::seconds(3));
  19061. std::string data(900, 'B');
  19062. sink.write(data.c_str(), data.size());
  19063. return true;
  19064. });
  19065. });
  19066. auto port = 8091;
  19067. std::thread t([&]() { svr.listen("localhost", port); });
  19068. svr.wait_until_ready();
  19069. Client cli("localhost", port);
  19070. cli.set_read_timeout(1, 0); // 1 second timeout
  19071. auto handle = cli.open_stream("GET", "/slow-stream");
  19072. ASSERT_TRUE(handle.is_valid());
  19073. char buf[256];
  19074. ssize_t total = 0;
  19075. ssize_t n;
  19076. bool got_error = false;
  19077. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19078. total += n;
  19079. }
  19080. if (n < 0) {
  19081. got_error = true;
  19082. // Should be timeout or read error
  19083. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19084. handle.get_read_error() == Error::Read)
  19085. << "Actual error: " << to_string(handle.get_read_error());
  19086. }
  19087. // Either we got an error, or we got less data than expected
  19088. EXPECT_TRUE(got_error || total < 1000)
  19089. << "Expected timeout but got all " << total << " bytes";
  19090. svr.stop();
  19091. t.join();
  19092. }
  19093. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  19094. // Test connection closed detection via BodyReader
  19095. Server svr;
  19096. std::atomic<bool> close_now{false};
  19097. svr.Get("/will-close", [&](const Request &, Response &res) {
  19098. res.set_content_provider(
  19099. 10000, // Large content_length that we won't fully send
  19100. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19101. if (offset < 100) {
  19102. std::string data(100, 'X');
  19103. sink.write(data.c_str(), data.size());
  19104. return true;
  19105. }
  19106. // Wait for signal then abort
  19107. while (!close_now) {
  19108. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19109. }
  19110. return false; // Abort - server will close connection
  19111. });
  19112. });
  19113. auto port = 8092;
  19114. std::thread t([&]() { svr.listen("localhost", port); });
  19115. svr.wait_until_ready();
  19116. Client cli("localhost", port);
  19117. auto handle = cli.open_stream("GET", "/will-close");
  19118. ASSERT_TRUE(handle.is_valid());
  19119. char buf[256];
  19120. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19121. EXPECT_GT(n, 0) << "First read should succeed";
  19122. // Signal server to close
  19123. close_now = true;
  19124. // Keep reading until error or EOF
  19125. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19126. // Keep reading
  19127. }
  19128. // Should get an error since content_length wasn't satisfied
  19129. if (n < 0) {
  19130. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19131. handle.get_read_error() == Error::Read)
  19132. << "Actual error: " << to_string(handle.get_read_error());
  19133. }
  19134. svr.stop();
  19135. t.join();
  19136. }
  19137. #ifdef CPPHTTPLIB_SSL_ENABLED
  19138. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  19139. // Test that read timeout during SSL streaming is detected
  19140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19141. svr.Get("/slow-stream", [](const Request &, Response &res) {
  19142. res.set_content_provider(
  19143. 1000, "text/plain",
  19144. [](size_t offset, size_t /*length*/, DataSink &sink) {
  19145. if (offset < 100) {
  19146. std::string data(100, 'A');
  19147. sink.write(data.c_str(), data.size());
  19148. return true;
  19149. }
  19150. std::this_thread::sleep_for(std::chrono::seconds(3));
  19151. std::string data(900, 'B');
  19152. sink.write(data.c_str(), data.size());
  19153. return true;
  19154. });
  19155. });
  19156. auto port = 8093;
  19157. std::thread t([&]() { svr.listen("localhost", port); });
  19158. svr.wait_until_ready();
  19159. SSLClient cli("localhost", port);
  19160. cli.enable_server_certificate_verification(false);
  19161. cli.set_read_timeout(1, 0); // 1 second timeout
  19162. auto handle = cli.open_stream("GET", "/slow-stream");
  19163. ASSERT_TRUE(handle.is_valid());
  19164. char buf[256];
  19165. ssize_t total = 0;
  19166. ssize_t n;
  19167. bool got_error = false;
  19168. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19169. total += n;
  19170. }
  19171. if (n < 0) {
  19172. got_error = true;
  19173. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  19174. handle.get_read_error() == Error::Read)
  19175. << "Actual error: " << to_string(handle.get_read_error());
  19176. }
  19177. EXPECT_TRUE(got_error || total < 1000)
  19178. << "Expected timeout but got all " << total << " bytes";
  19179. svr.stop();
  19180. t.join();
  19181. }
  19182. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  19183. // Test SSL connection closed detection
  19184. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19185. std::atomic<bool> close_now{false};
  19186. svr.Get("/will-close", [&](const Request &, Response &res) {
  19187. res.set_content_provider(
  19188. 10000, "text/plain",
  19189. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  19190. if (offset < 100) {
  19191. std::string data(100, 'X');
  19192. sink.write(data.c_str(), data.size());
  19193. return true;
  19194. }
  19195. while (!close_now) {
  19196. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19197. }
  19198. return false;
  19199. });
  19200. });
  19201. auto port = 8094;
  19202. std::thread t([&]() { svr.listen("localhost", port); });
  19203. svr.wait_until_ready();
  19204. SSLClient cli("localhost", port);
  19205. cli.enable_server_certificate_verification(false);
  19206. auto handle = cli.open_stream("GET", "/will-close");
  19207. ASSERT_TRUE(handle.is_valid());
  19208. char buf[256];
  19209. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  19210. EXPECT_GT(n, 0);
  19211. // Signal server to close
  19212. close_now = true;
  19213. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19214. // Keep reading
  19215. }
  19216. if (n < 0) {
  19217. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  19218. handle.get_read_error() == Error::Read)
  19219. << "Actual error: " << to_string(handle.get_read_error());
  19220. }
  19221. svr.stop();
  19222. t.join();
  19223. }
  19224. #endif
  19225. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  19226. using namespace httplib;
  19227. // Create a test file
  19228. const char *fname = "etag_testfile.txt";
  19229. const char *content = "etag-content";
  19230. {
  19231. std::ofstream ofs(fname);
  19232. ofs << content;
  19233. ASSERT_TRUE(ofs.good());
  19234. }
  19235. Server svr;
  19236. svr.set_mount_point("/static", ".");
  19237. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19238. svr.wait_until_ready();
  19239. Client cli(HOST, PORT);
  19240. // First request: should get 200 with ETag header
  19241. auto res1 = cli.Get("/static/etag_testfile.txt");
  19242. ASSERT_TRUE(res1);
  19243. ASSERT_EQ(200, res1->status);
  19244. ASSERT_TRUE(res1->has_header("ETag"));
  19245. std::string etag = res1->get_header_value("ETag");
  19246. EXPECT_FALSE(etag.empty());
  19247. // Verify ETag format: W/"hex-hex"
  19248. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  19249. EXPECT_EQ('W', etag[0]);
  19250. EXPECT_EQ('/', etag[1]);
  19251. EXPECT_EQ('"', etag[2]);
  19252. EXPECT_EQ('"', etag.back());
  19253. // Exact match: expect 304 Not Modified
  19254. Headers h2 = {{"If-None-Match", etag}};
  19255. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  19256. ASSERT_TRUE(res2);
  19257. EXPECT_EQ(304, res2->status);
  19258. // Wildcard match: expect 304 Not Modified
  19259. Headers h3 = {{"If-None-Match", "*"}};
  19260. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  19261. ASSERT_TRUE(res3);
  19262. EXPECT_EQ(304, res3->status);
  19263. // Non-matching ETag: expect 200
  19264. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  19265. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  19266. ASSERT_TRUE(res4);
  19267. EXPECT_EQ(200, res4->status);
  19268. // Multiple ETags with one matching: expect 304
  19269. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  19270. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  19271. ASSERT_TRUE(res5);
  19272. EXPECT_EQ(304, res5->status);
  19273. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  19274. // that equivalent to the single comma-separated list above, so the match on
  19275. // the second line must still be found.
  19276. Headers h6;
  19277. h6.emplace("If-None-Match", "W/\"other\"");
  19278. h6.emplace("If-None-Match", etag);
  19279. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  19280. ASSERT_TRUE(res6);
  19281. EXPECT_EQ(304, res6->status);
  19282. svr.stop();
  19283. t.join();
  19284. std::remove(fname);
  19285. }
  19286. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  19287. using namespace httplib;
  19288. Server svr;
  19289. svr.set_mount_point("/static", ".");
  19290. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19291. svr.wait_until_ready();
  19292. Client cli(HOST, PORT);
  19293. // Send If-None-Match: * to a non-existent file
  19294. Headers h = {{"If-None-Match", "*"}};
  19295. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  19296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19297. EXPECT_EQ(404, res->status);
  19298. svr.stop();
  19299. t.join();
  19300. }
  19301. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  19302. using namespace httplib;
  19303. // Create a test file
  19304. const char *fname = "etag_boundary_testfile.txt";
  19305. const char *content = "boundary-test";
  19306. {
  19307. std::ofstream ofs(fname);
  19308. ofs << content;
  19309. ASSERT_TRUE(ofs.good());
  19310. }
  19311. Server svr;
  19312. svr.set_mount_point("/static", ".");
  19313. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  19314. svr.wait_until_ready();
  19315. Client cli(HOST, PORT);
  19316. // Get the actual ETag
  19317. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  19318. ASSERT_TRUE(res1);
  19319. ASSERT_EQ(200, res1->status);
  19320. ASSERT_TRUE(res1->has_header("ETag"));
  19321. std::string etag = res1->get_header_value("ETag");
  19322. // Test 1: Very long ETag value (longer than actual ETag)
  19323. // Should NOT match and return 200 (not trigger out-of-bounds read)
  19324. Headers h1 = {{"If-None-Match", "W/"
  19325. "\"very-long-etag-value-that-is-much-longer-"
  19326. "than-the-actual-etag-value\""}};
  19327. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  19328. ASSERT_TRUE(res2);
  19329. EXPECT_EQ(200, res2->status); // Should not match
  19330. // Test 2: Long string followed by wildcard
  19331. // Should match on "*" and return 304 (without out-of-bounds read on the long
  19332. // string)
  19333. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  19334. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  19335. ASSERT_TRUE(res3);
  19336. EXPECT_EQ(304, res3->status); // Should match on "*"
  19337. // Test 3: Wildcard followed by long string
  19338. // Should match on "*" immediately and return 304
  19339. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  19340. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  19341. ASSERT_TRUE(res4);
  19342. EXPECT_EQ(304, res4->status); // Should match on "*"
  19343. // Test 4: Multiple long non-matching values
  19344. // Should NOT match and return 200 (test that all comparisons are safe)
  19345. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  19346. "W/\"second-long-non-matching-value\", "
  19347. "W/\"third-long-non-matching-value\""}};
  19348. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  19349. ASSERT_TRUE(res5);
  19350. EXPECT_EQ(200, res5->status); // Should not match
  19351. // Test 5: Single character that is not "*" (edge case)
  19352. Headers h5 = {{"If-None-Match", "X"}};
  19353. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  19354. ASSERT_TRUE(res6);
  19355. EXPECT_EQ(200, res6->status); // Should not match
  19356. svr.stop();
  19357. t.join();
  19358. std::remove(fname);
  19359. }
  19360. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  19361. using namespace httplib;
  19362. // Create a test file
  19363. const char *fname = "ims_testfile.txt";
  19364. const char *content = "if-modified-since-test";
  19365. {
  19366. std::ofstream ofs(fname);
  19367. ofs << content;
  19368. ASSERT_TRUE(ofs.good());
  19369. }
  19370. Server svr;
  19371. svr.set_mount_point("/static", ".");
  19372. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19373. svr.wait_until_ready();
  19374. Client cli(HOST, PORT);
  19375. // First request: should get 200 with Last-Modified header
  19376. auto res1 = cli.Get("/static/ims_testfile.txt");
  19377. ASSERT_TRUE(res1);
  19378. ASSERT_EQ(200, res1->status);
  19379. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19380. std::string last_modified = res1->get_header_value("Last-Modified");
  19381. EXPECT_FALSE(last_modified.empty());
  19382. // If-Modified-Since with same time: expect 304
  19383. Headers h2 = {{"If-Modified-Since", last_modified}};
  19384. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  19385. ASSERT_TRUE(res2);
  19386. EXPECT_EQ(304, res2->status);
  19387. // If-Modified-Since with future time: expect 304
  19388. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19389. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  19390. ASSERT_TRUE(res3);
  19391. EXPECT_EQ(304, res3->status);
  19392. // If-Modified-Since with past time: expect 200
  19393. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19394. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  19395. ASSERT_TRUE(res4);
  19396. EXPECT_EQ(200, res4->status);
  19397. // If-None-Match takes precedence over If-Modified-Since
  19398. // (send matching ETag with old If-Modified-Since -> should still be 304)
  19399. ASSERT_TRUE(res1->has_header("ETag"));
  19400. std::string etag = res1->get_header_value("ETag");
  19401. Headers h5 = {{"If-None-Match", etag},
  19402. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19403. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  19404. ASSERT_TRUE(res5);
  19405. EXPECT_EQ(304, res5->status);
  19406. svr.stop();
  19407. t.join();
  19408. std::remove(fname);
  19409. }
  19410. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  19411. using namespace httplib;
  19412. Server svr;
  19413. // Endpoint that returns compressible content
  19414. svr.Get("/compressible", [](const Request &, Response &res) {
  19415. // Return a large enough body to trigger compression
  19416. std::string body(1000, 'a');
  19417. res.set_content(body, "text/plain");
  19418. });
  19419. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19420. svr.wait_until_ready();
  19421. Client cli(HOST, PORT);
  19422. // Request with gzip support: should get Vary header when compressed
  19423. cli.set_compress(true);
  19424. auto res1 = cli.Get("/compressible");
  19425. ASSERT_TRUE(res1);
  19426. EXPECT_EQ(200, res1->status);
  19427. // If Content-Encoding is set, Vary should also be set
  19428. if (res1->has_header("Content-Encoding")) {
  19429. EXPECT_TRUE(res1->has_header("Vary"));
  19430. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  19431. }
  19432. // Request without Accept-Encoding header: should not have compression
  19433. Headers h_no_compress;
  19434. auto res2 = cli.Get("/compressible", h_no_compress);
  19435. ASSERT_TRUE(res2);
  19436. EXPECT_EQ(200, res2->status);
  19437. // Verify Vary header is present when compression is applied
  19438. // (the exact behavior depends on server configuration)
  19439. svr.stop();
  19440. t.join();
  19441. }
  19442. TEST(ETagTest, IfRangeWithETag) {
  19443. using namespace httplib;
  19444. // Create a test file with known content
  19445. const char *fname = "if_range_testfile.txt";
  19446. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  19447. {
  19448. std::ofstream ofs(fname);
  19449. ofs << content;
  19450. ASSERT_TRUE(ofs.good());
  19451. }
  19452. Server svr;
  19453. svr.set_mount_point("/static", ".");
  19454. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19455. svr.wait_until_ready();
  19456. Client cli(HOST, PORT);
  19457. // First request: get ETag
  19458. auto res1 = cli.Get("/static/if_range_testfile.txt");
  19459. ASSERT_TRUE(res1);
  19460. ASSERT_EQ(200, res1->status);
  19461. ASSERT_TRUE(res1->has_header("ETag"));
  19462. std::string etag = res1->get_header_value("ETag");
  19463. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  19464. // Since our server generates weak ETags (W/"..."), If-Range with our
  19465. // ETag should NOT result in partial content - it should return full content.
  19466. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  19467. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  19468. ASSERT_TRUE(res2);
  19469. // Weak ETag in If-Range -> full content (200), not partial (206)
  19470. EXPECT_EQ(200, res2->status);
  19471. EXPECT_EQ(content, res2->body);
  19472. EXPECT_FALSE(res2->has_header("Content-Range"));
  19473. // Range request with non-matching If-Range (ETag): should get 200 (full
  19474. // content)
  19475. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  19476. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  19477. ASSERT_TRUE(res3);
  19478. EXPECT_EQ(200, res3->status);
  19479. EXPECT_EQ(content, res3->body);
  19480. EXPECT_FALSE(res3->has_header("Content-Range"));
  19481. // Range request with strong ETag (hypothetical - our server doesn't generate
  19482. // strong ETags, but if client sends a strong ETag that doesn't match, it
  19483. // should return full content)
  19484. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  19485. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  19486. ASSERT_TRUE(res4);
  19487. EXPECT_EQ(200, res4->status);
  19488. EXPECT_EQ(content, res4->body);
  19489. EXPECT_FALSE(res4->has_header("Content-Range"));
  19490. svr.stop();
  19491. t.join();
  19492. std::remove(fname);
  19493. }
  19494. TEST(ETagTest, IfRangeWithDate) {
  19495. using namespace httplib;
  19496. // Create a test file
  19497. const char *fname = "if_range_date_testfile.txt";
  19498. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  19499. {
  19500. std::ofstream ofs(fname);
  19501. ofs << content;
  19502. ASSERT_TRUE(ofs.good());
  19503. }
  19504. Server svr;
  19505. svr.set_mount_point("/static", ".");
  19506. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19507. svr.wait_until_ready();
  19508. Client cli(HOST, PORT);
  19509. // First request: get Last-Modified
  19510. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  19511. ASSERT_TRUE(res1);
  19512. ASSERT_EQ(200, res1->status);
  19513. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19514. std::string last_modified = res1->get_header_value("Last-Modified");
  19515. // Range request with matching If-Range (date): should get 206
  19516. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  19517. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  19518. ASSERT_TRUE(res2);
  19519. EXPECT_EQ(206, res2->status);
  19520. EXPECT_EQ("FGHIJ", res2->body);
  19521. // Range request with old If-Range date: should get 200 (full content)
  19522. Headers h3 = {{"Range", "bytes=5-9"},
  19523. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  19524. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  19525. ASSERT_TRUE(res3);
  19526. EXPECT_EQ(200, res3->status);
  19527. EXPECT_EQ(content, res3->body);
  19528. // Range request with future If-Range date: should get 206
  19529. Headers h4 = {{"Range", "bytes=0-4"},
  19530. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  19531. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  19532. ASSERT_TRUE(res4);
  19533. EXPECT_EQ(206, res4->status);
  19534. EXPECT_EQ("ABCDE", res4->body);
  19535. svr.stop();
  19536. t.join();
  19537. std::remove(fname);
  19538. }
  19539. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  19540. using namespace httplib;
  19541. const char *fname = "etag_malformed.txt";
  19542. const char *content = "malformed-etag";
  19543. {
  19544. std::ofstream ofs(fname);
  19545. ofs << content;
  19546. ASSERT_TRUE(ofs.good());
  19547. }
  19548. Server svr;
  19549. svr.set_mount_point("/static", ".");
  19550. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19551. svr.wait_until_ready();
  19552. Client cli(HOST, PORT);
  19553. // baseline: should get 200 and an ETag
  19554. auto res1 = cli.Get("/static/etag_malformed.txt");
  19555. ASSERT_TRUE(res1);
  19556. ASSERT_EQ(200, res1->status);
  19557. ASSERT_TRUE(res1->has_header("ETag"));
  19558. // Malformed ETag value (missing quotes) should be treated as non-matching
  19559. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  19560. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  19561. ASSERT_TRUE(res_bad);
  19562. EXPECT_EQ(200, res_bad->status);
  19563. // Whitespace-only header value should be considered invalid / non-matching
  19564. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  19565. "Host: localhost\r\n"
  19566. "If-None-Match: \r\n"
  19567. "Connection: close\r\n"
  19568. "\r\n";
  19569. std::string out;
  19570. ASSERT_TRUE(send_request(5, raw_req, &out));
  19571. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19572. svr.stop();
  19573. t.join();
  19574. std::remove(fname);
  19575. }
  19576. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  19577. using namespace httplib;
  19578. const char *fname = "ims_invalid_format.txt";
  19579. const char *content = "ims-bad-format";
  19580. {
  19581. std::ofstream ofs(fname);
  19582. ofs << content;
  19583. ASSERT_TRUE(ofs.good());
  19584. }
  19585. Server svr;
  19586. svr.set_mount_point("/static", ".");
  19587. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19588. svr.wait_until_ready();
  19589. Client cli(HOST, PORT);
  19590. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  19591. ASSERT_TRUE(res1);
  19592. ASSERT_EQ(200, res1->status);
  19593. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19594. // If-Modified-Since with invalid format should not result in 304
  19595. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  19596. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  19597. ASSERT_TRUE(res_bad);
  19598. EXPECT_EQ(200, res_bad->status);
  19599. // If-Range with invalid date format should be treated as mismatch -> full
  19600. // content (200)
  19601. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  19602. {"If-Range", "invalid-date"}};
  19603. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  19604. ASSERT_TRUE(res_ifrange);
  19605. EXPECT_EQ(200, res_ifrange->status);
  19606. svr.stop();
  19607. t.join();
  19608. std::remove(fname);
  19609. }
  19610. TEST(ETagTest, IfRangeWithMalformedETag) {
  19611. using namespace httplib;
  19612. const char *fname = "ifrange_malformed.txt";
  19613. const std::string content = "0123456789";
  19614. {
  19615. std::ofstream ofs(fname);
  19616. ofs << content;
  19617. ASSERT_TRUE(ofs.good());
  19618. }
  19619. Server svr;
  19620. svr.set_mount_point("/static", ".");
  19621. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19622. svr.wait_until_ready();
  19623. Client cli(HOST, PORT);
  19624. // First request: get ETag
  19625. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  19626. ASSERT_TRUE(res1);
  19627. ASSERT_EQ(200, res1->status);
  19628. ASSERT_TRUE(res1->has_header("ETag"));
  19629. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  19630. // full content (200)
  19631. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  19632. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  19633. ASSERT_TRUE(res2);
  19634. EXPECT_EQ(200, res2->status);
  19635. EXPECT_EQ(content, res2->body);
  19636. svr.stop();
  19637. t.join();
  19638. std::remove(fname);
  19639. }
  19640. TEST(ETagTest, ExtremeLargeDateValues) {
  19641. using namespace httplib;
  19642. const char *fname = "ims_extreme_date.txt";
  19643. const char *content = "ims-extreme-date";
  19644. {
  19645. std::ofstream ofs(fname);
  19646. ofs << content;
  19647. ASSERT_TRUE(ofs.good());
  19648. }
  19649. Server svr;
  19650. svr.set_mount_point("/static", ".");
  19651. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19652. svr.wait_until_ready();
  19653. Client cli(HOST, PORT);
  19654. auto res1 = cli.Get(std::string("/static/") + fname);
  19655. ASSERT_TRUE(res1);
  19656. ASSERT_EQ(200, res1->status);
  19657. ASSERT_TRUE(res1->has_header("Last-Modified"));
  19658. // Extremely large year that may overflow date parsing routines.
  19659. Headers h_large_date = {
  19660. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19661. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  19662. ASSERT_TRUE(res_bad);
  19663. // Expect server to treat this as invalid/mismatch and return full content
  19664. EXPECT_EQ(200, res_bad->status);
  19665. // If-Range with extremely large date should be treated as mismatch -> full
  19666. // content (200)
  19667. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  19668. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19669. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  19670. ASSERT_TRUE(res_ifrange);
  19671. EXPECT_EQ(200, res_ifrange->status);
  19672. svr.stop();
  19673. t.join();
  19674. std::remove(fname);
  19675. }
  19676. TEST(ETagTest, NegativeFileModificationTime) {
  19677. using namespace httplib;
  19678. const char *fname = "ims_negative_mtime.txt";
  19679. const std::string content = "negative-mtime";
  19680. {
  19681. std::ofstream ofs(fname);
  19682. ofs << content;
  19683. ASSERT_TRUE(ofs.good());
  19684. }
  19685. // Try to set file mtime to a negative value. This may fail on some
  19686. // platforms/filesystems; if it fails, the test will still verify server
  19687. // behaves safely by performing a regular conditional request.
  19688. #if defined(__APPLE__) || defined(__linux__)
  19689. bool set_negative = false;
  19690. do {
  19691. struct timeval times[2];
  19692. // access time: now
  19693. times[0].tv_sec = time(nullptr);
  19694. times[0].tv_usec = 0;
  19695. // modification time: negative (e.g., -1)
  19696. times[1].tv_sec = -1;
  19697. times[1].tv_usec = 0;
  19698. if (utimes(fname, times) == 0) { set_negative = true; }
  19699. } while (0);
  19700. #else
  19701. bool set_negative = false;
  19702. #endif
  19703. Server svr;
  19704. svr.set_mount_point("/static", ".");
  19705. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  19706. svr.wait_until_ready();
  19707. Client cli(HOST, PORT);
  19708. auto res1 = cli.Get(std::string("/static/") + fname);
  19709. ASSERT_TRUE(res1);
  19710. ASSERT_EQ(200, res1->status);
  19711. bool has_last_modified = res1->has_header("Last-Modified");
  19712. std::string last_modified;
  19713. if (has_last_modified) {
  19714. last_modified = res1->get_header_value("Last-Modified");
  19715. }
  19716. if (set_negative) {
  19717. // If we successfully set a negative mtime, ensure server returns a
  19718. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  19719. // with an old date and ensure server handles it without crash.
  19720. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  19721. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  19722. ASSERT_TRUE(res2);
  19723. // Behavior may vary; at minimum ensure server responds (200 or 304).
  19724. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  19725. } else {
  19726. // Could not set negative mtime on this platform; fall back to verifying
  19727. // that normal invalid/malformed dates are treated safely (non-304).
  19728. Headers h_bad_date = {
  19729. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  19730. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  19731. ASSERT_TRUE(res_bad);
  19732. EXPECT_EQ(200, res_bad->status);
  19733. }
  19734. svr.stop();
  19735. t.join();
  19736. std::remove(fname);
  19737. }
  19738. //==============================================================================
  19739. // Integration Tests with Server
  19740. //==============================================================================
  19741. class SSEIntegrationTest : public ::testing::Test {
  19742. protected:
  19743. void SetUp() override {
  19744. stop_server_.store(false);
  19745. events_.clear();
  19746. server_ = httplib::detail::make_unique<Server>();
  19747. setup_server();
  19748. start_server();
  19749. }
  19750. void TearDown() override {
  19751. stop_server_.store(true);
  19752. event_cv_.notify_all();
  19753. server_->stop();
  19754. if (server_thread_.joinable()) { server_thread_.join(); }
  19755. }
  19756. void setup_server() {
  19757. // Simple SSE endpoint
  19758. server_->Get("/events", [this](const Request &req, Response &res) {
  19759. auto last_id = req.get_header_value("Last-Event-ID");
  19760. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  19761. res.set_chunked_content_provider(
  19762. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  19763. std::unique_lock<std::mutex> lock(event_mutex_);
  19764. if (event_cv_.wait_for(
  19765. lock, std::chrono::milliseconds(200), [this] {
  19766. return !events_.empty() || stop_server_.load();
  19767. })) {
  19768. if (stop_server_.load()) { return false; }
  19769. if (!events_.empty()) {
  19770. std::string event = events_.front();
  19771. events_.erase(events_.begin());
  19772. sink.write(event.data(), event.size());
  19773. return true;
  19774. }
  19775. }
  19776. return !stop_server_.load();
  19777. });
  19778. });
  19779. // Endpoint that returns error
  19780. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  19781. res.status = 500;
  19782. res.set_content("Internal Server Error", "text/plain");
  19783. });
  19784. // Endpoint for custom event types
  19785. server_->Get("/custom-events", [](const Request &, Response &res) {
  19786. res.set_chunked_content_provider(
  19787. "text/event-stream", [](size_t offset, DataSink &sink) {
  19788. if (offset == 0) {
  19789. std::string event = "event: update\ndata: updated\n\n"
  19790. "event: delete\ndata: deleted\n\n";
  19791. sink.write(event.data(), event.size());
  19792. }
  19793. return false; // End stream after sending
  19794. });
  19795. });
  19796. }
  19797. void start_server() {
  19798. port_ = server_->bind_to_any_port(HOST);
  19799. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19800. // Wait for server to start
  19801. while (!server_->is_running()) {
  19802. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  19803. }
  19804. }
  19805. int get_port() const { return port_; }
  19806. void send_event(const std::string &event) {
  19807. std::lock_guard<std::mutex> lock(event_mutex_);
  19808. events_.push_back(event);
  19809. event_cv_.notify_all();
  19810. }
  19811. std::unique_ptr<Server> server_;
  19812. std::thread server_thread_;
  19813. std::mutex event_mutex_;
  19814. std::condition_variable event_cv_;
  19815. std::vector<std::string> events_;
  19816. std::atomic<bool> stop_server_{false};
  19817. std::string last_received_event_id_;
  19818. int port_ = 0;
  19819. };
  19820. //==============================================================================
  19821. // SSE Parsing Tests
  19822. //==============================================================================
  19823. class SSEParsingTest : public SSEIntegrationTest {
  19824. protected:
  19825. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  19826. // A trailing sentinel event tells when the whole stream has been parsed.
  19827. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  19828. auto body = stream + "event: end\ndata: end\n\n";
  19829. server_->Get("/parse", [body](const Request &, Response &res) {
  19830. res.set_content(body, "text/event-stream");
  19831. });
  19832. return collect("/parse");
  19833. }
  19834. // Runs SSEClient against path until an "end" event arrives and returns the
  19835. // messages dispatched before it
  19836. std::vector<sse::SSEMessage> collect(const std::string &path) {
  19837. Client client(HOST, get_port());
  19838. sse::SSEClient sse(client, path);
  19839. std::mutex mutex;
  19840. std::condition_variable cv;
  19841. std::vector<sse::SSEMessage> messages;
  19842. auto done = false;
  19843. sse.on_message([&](const sse::SSEMessage &msg) {
  19844. std::lock_guard<std::mutex> lock(mutex);
  19845. // Ignore a replay from a reconnect that races with stop()
  19846. if (!done) { messages.push_back(msg); }
  19847. });
  19848. sse.on_event("end", [&](const sse::SSEMessage &) {
  19849. std::lock_guard<std::mutex> lock(mutex);
  19850. done = true;
  19851. cv.notify_all();
  19852. });
  19853. sse.set_reconnect_interval(100);
  19854. sse.start_async();
  19855. {
  19856. std::unique_lock<std::mutex> lock(mutex);
  19857. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  19858. }
  19859. sse.stop();
  19860. EXPECT_TRUE(done);
  19861. return messages;
  19862. }
  19863. };
  19864. TEST_F(SSEParsingTest, SingleLineData) {
  19865. auto msgs = parse("data: hello\n\n");
  19866. ASSERT_EQ(msgs.size(), 1u);
  19867. EXPECT_EQ(msgs[0].data, "hello");
  19868. EXPECT_EQ(msgs[0].event, "message");
  19869. }
  19870. TEST_F(SSEParsingTest, MultiLineData) {
  19871. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  19872. ASSERT_EQ(msgs.size(), 1u);
  19873. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  19874. }
  19875. TEST_F(SSEParsingTest, CustomEventType) {
  19876. auto msgs = parse("event: update\ndata: payload\n\n");
  19877. ASSERT_EQ(msgs.size(), 1u);
  19878. EXPECT_EQ(msgs[0].event, "update");
  19879. EXPECT_EQ(msgs[0].data, "payload");
  19880. }
  19881. TEST_F(SSEParsingTest, EventIdHandling) {
  19882. auto msgs = parse("id: 12345\ndata: test\n\n");
  19883. ASSERT_EQ(msgs.size(), 1u);
  19884. EXPECT_EQ(msgs[0].id, "12345");
  19885. }
  19886. TEST_F(SSEParsingTest, EmptyEventId) {
  19887. auto msgs = parse("id:\ndata: test\n\n");
  19888. ASSERT_EQ(msgs.size(), 1u);
  19889. EXPECT_EQ(msgs[0].id, "");
  19890. }
  19891. TEST_F(SSEParsingTest, CommentsIgnored) {
  19892. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  19893. ASSERT_EQ(msgs.size(), 1u);
  19894. EXPECT_EQ(msgs[0].data, "hello");
  19895. EXPECT_EQ(msgs[0].event, "message");
  19896. }
  19897. TEST_F(SSEParsingTest, ColonInValue) {
  19898. auto msgs = parse("data: hello:world:test\n\n");
  19899. ASSERT_EQ(msgs.size(), 1u);
  19900. EXPECT_EQ(msgs[0].data, "hello:world:test");
  19901. }
  19902. TEST_F(SSEParsingTest, FieldNameOnly) {
  19903. // A line without a colon is a field name with an empty value
  19904. auto msgs = parse("data\n\n");
  19905. ASSERT_EQ(msgs.size(), 1u);
  19906. EXPECT_EQ(msgs[0].data, "");
  19907. }
  19908. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  19909. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  19910. ASSERT_EQ(msgs.size(), 1u);
  19911. EXPECT_EQ(msgs[0].event, "update");
  19912. EXPECT_EQ(msgs[0].data, "hello");
  19913. }
  19914. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  19915. auto msgs = parse("data\r\n\r\n");
  19916. ASSERT_EQ(msgs.size(), 1u);
  19917. EXPECT_EQ(msgs[0].data, "");
  19918. }
  19919. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  19920. auto msgs = parse("event: update\rdata: hello\r\r");
  19921. ASSERT_EQ(msgs.size(), 1u);
  19922. EXPECT_EQ(msgs[0].event, "update");
  19923. EXPECT_EQ(msgs[0].data, "hello");
  19924. }
  19925. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  19926. // Chunk boundaries fall inside every \r\n and right before the first one
  19927. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  19928. "\n\r", "\nevent: end\ndata: end\n\n"};
  19929. server_->Get("/split", [chunks](const Request &, Response &res) {
  19930. auto i = std::make_shared<size_t>(0);
  19931. res.set_chunked_content_provider(
  19932. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  19933. if (*i == chunks.size()) {
  19934. sink.done();
  19935. } else {
  19936. sink.write(chunks[*i].data(), chunks[*i].size());
  19937. (*i)++;
  19938. }
  19939. return true;
  19940. });
  19941. });
  19942. auto msgs = collect("/split");
  19943. ASSERT_EQ(msgs.size(), 1u);
  19944. EXPECT_EQ(msgs[0].event, "update");
  19945. EXPECT_EQ(msgs[0].data, "hello");
  19946. }
  19947. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  19948. // Only a BOM at the start of the stream is ignored
  19949. auto msgs = parse("\xEF\xBB\xBF"
  19950. "data: first\n\n"
  19951. "\xEF\xBB\xBF"
  19952. "data: second\n\n");
  19953. ASSERT_EQ(msgs.size(), 1u);
  19954. EXPECT_EQ(msgs[0].data, "first");
  19955. }
  19956. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  19957. auto msgs = parse("unknown: value\ndata: hello\n\n");
  19958. ASSERT_EQ(msgs.size(), 1u);
  19959. EXPECT_EQ(msgs[0].data, "hello");
  19960. EXPECT_EQ(msgs[0].event, "message");
  19961. }
  19962. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  19963. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  19964. ASSERT_EQ(msgs.size(), 2u);
  19965. EXPECT_EQ(msgs[0].data, "hello");
  19966. EXPECT_EQ(msgs[1].data, "hello");
  19967. }
  19968. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  19969. // An event without data is not dispatched, and its type must not leak
  19970. // into the next event
  19971. auto msgs = parse("event: update\n\ndata: hello\n\n");
  19972. ASSERT_EQ(msgs.size(), 1u);
  19973. EXPECT_EQ(msgs[0].event, "message");
  19974. EXPECT_EQ(msgs[0].data, "hello");
  19975. }
  19976. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  19977. // The first connection sends only an id; the second echoes back the
  19978. // Last-Event-ID it was reconnected with
  19979. std::atomic<int> connection_count{0};
  19980. server_->Get("/id-only", [&](const Request &req, Response &res) {
  19981. if (connection_count++ == 0) {
  19982. res.set_content("id: 42\n\n", "text/event-stream");
  19983. } else {
  19984. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  19985. "\n\nevent: end\ndata: end\n\n",
  19986. "text/event-stream");
  19987. }
  19988. });
  19989. auto msgs = collect("/id-only");
  19990. ASSERT_EQ(msgs.size(), 1u);
  19991. EXPECT_EQ(msgs[0].data, "42");
  19992. }
  19993. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  19994. // The first connection sets an id and then clears it with an empty one; the
  19995. // second reports whether it was reconnected with a Last-Event-ID
  19996. std::atomic<int> connection_count{0};
  19997. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  19998. if (connection_count++ == 0) {
  19999. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  20000. "text/event-stream");
  20001. } else {
  20002. res.set_content(
  20003. std::string("data: ") +
  20004. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  20005. "\n\nevent: end\ndata: end\n\n",
  20006. "text/event-stream");
  20007. }
  20008. });
  20009. auto msgs = collect("/id-clear");
  20010. ASSERT_EQ(msgs.size(), 3u);
  20011. EXPECT_EQ(msgs[0].id, "1");
  20012. EXPECT_EQ(msgs[1].id, "");
  20013. EXPECT_EQ(msgs[2].data, "not sent");
  20014. }
  20015. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  20016. // The first connection sets an id and then sends ids that cannot be carried
  20017. // in a header; the second echoes back the Last-Event-ID it was reconnected
  20018. // with
  20019. std::atomic<int> connection_count{0};
  20020. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  20021. if (connection_count++ == 0) {
  20022. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  20023. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  20024. "text/event-stream");
  20025. } else {
  20026. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  20027. "\n\nevent: end\ndata: end\n\n",
  20028. "text/event-stream");
  20029. }
  20030. });
  20031. auto msgs = collect("/id-unsendable");
  20032. ASSERT_EQ(msgs.size(), 1u);
  20033. EXPECT_EQ(msgs[0].data, "42");
  20034. }
  20035. TEST_F(SSEParsingTest, CompleteEventParsing) {
  20036. auto msgs = parse("event: notification\nid: evt-42\n"
  20037. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  20038. ASSERT_EQ(msgs.size(), 1u);
  20039. EXPECT_EQ(msgs[0].event, "notification");
  20040. EXPECT_EQ(msgs[0].id, "evt-42");
  20041. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  20042. }
  20043. TEST(SSEMessageTest, Clear) {
  20044. sse::SSEMessage msg;
  20045. msg.event = "custom";
  20046. msg.data = "some data";
  20047. msg.id = "123";
  20048. msg.clear();
  20049. EXPECT_EQ(msg.event, "message");
  20050. EXPECT_EQ(msg.data, "");
  20051. EXPECT_EQ(msg.id, "");
  20052. }
  20053. //==============================================================================
  20054. // SSE Integration Tests
  20055. //==============================================================================
  20056. // Test: Successful connection and on_open callback
  20057. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  20058. // Add a simple endpoint that sends one event and closes
  20059. server_->Get("/simple-event", [](const Request &, Response &res) {
  20060. res.set_chunked_content_provider(
  20061. "text/event-stream", [](size_t offset, DataSink &sink) {
  20062. if (offset == 0) {
  20063. std::string event = "data: hello\n\n";
  20064. sink.write(event.data(), event.size());
  20065. }
  20066. return false; // Close stream after sending
  20067. });
  20068. });
  20069. Client client("localhost", get_port());
  20070. sse::SSEClient sse(client, "/simple-event");
  20071. std::atomic<bool> open_called{false};
  20072. std::atomic<bool> message_received{false};
  20073. sse.on_open([&open_called]() { open_called.store(true); });
  20074. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  20075. if (msg.data == "hello") { message_received.store(true); }
  20076. });
  20077. sse.set_reconnect_interval(100);
  20078. sse.set_max_reconnect_attempts(1);
  20079. // Start async
  20080. sse.start_async();
  20081. // Wait for message to be processed
  20082. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20083. sse.stop();
  20084. EXPECT_TRUE(open_called.load());
  20085. EXPECT_TRUE(message_received.load());
  20086. }
  20087. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  20088. // A data line that never ends.
  20089. server_->Get("/endless-line", [](const Request &, Response &res) {
  20090. res.set_chunked_content_provider(
  20091. "text/event-stream", [](size_t offset, DataSink &sink) {
  20092. if (offset == 0) { sink.write("data: ", 6); }
  20093. std::string chunk(64 * 1024, 'A');
  20094. return sink.write(chunk.data(), chunk.size());
  20095. });
  20096. });
  20097. Client client("localhost", get_port());
  20098. // A stream that may run forever, so that only the event is bounded.
  20099. client.set_payload_max_length(0);
  20100. sse::SSEClient sse(client, "/endless-line");
  20101. std::atomic<bool> too_long{false};
  20102. sse.on_error([&](Error err) {
  20103. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  20104. });
  20105. sse.set_max_reconnect_attempts(1);
  20106. sse.start_async();
  20107. for (int i = 0; i < 500 && !too_long; i++) {
  20108. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20109. }
  20110. sse.stop();
  20111. EXPECT_TRUE(too_long);
  20112. }
  20113. // Test: on_message callback
  20114. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  20115. // Endpoint that sends multiple events then closes
  20116. server_->Get("/multi-event", [](const Request &, Response &res) {
  20117. res.set_chunked_content_provider(
  20118. "text/event-stream", [](size_t offset, DataSink &sink) {
  20119. if (offset == 0) {
  20120. std::string events = "data: message1\n\ndata: message2\n\n";
  20121. sink.write(events.data(), events.size());
  20122. }
  20123. return false;
  20124. });
  20125. });
  20126. Client client("localhost", get_port());
  20127. sse::SSEClient sse(client, "/multi-event");
  20128. std::vector<std::string> received_messages;
  20129. std::mutex messages_mutex;
  20130. sse.on_message([&](const sse::SSEMessage &msg) {
  20131. std::lock_guard<std::mutex> lock(messages_mutex);
  20132. received_messages.push_back(msg.data);
  20133. });
  20134. sse.set_reconnect_interval(100);
  20135. sse.set_max_reconnect_attempts(1);
  20136. sse.start_async();
  20137. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20138. sse.stop();
  20139. std::lock_guard<std::mutex> lock(messages_mutex);
  20140. EXPECT_GE(received_messages.size(), 2u);
  20141. if (received_messages.size() >= 2) {
  20142. EXPECT_EQ(received_messages[0], "message1");
  20143. EXPECT_EQ(received_messages[1], "message2");
  20144. }
  20145. }
  20146. // Test: on_event for specific types
  20147. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  20148. Client client("localhost", get_port());
  20149. sse::SSEClient sse(client, "/custom-events");
  20150. std::atomic<bool> update_received{false};
  20151. std::atomic<bool> delete_received{false};
  20152. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  20153. if (msg.data == "updated") { update_received.store(true); }
  20154. });
  20155. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  20156. if (msg.data == "deleted") { delete_received.store(true); }
  20157. });
  20158. sse.set_max_reconnect_attempts(1);
  20159. sse.start_async();
  20160. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  20161. sse.stop();
  20162. EXPECT_TRUE(update_received.load());
  20163. EXPECT_TRUE(delete_received.load());
  20164. }
  20165. // Test: on_error callback on connection failure
  20166. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  20167. // Connect to a non-existent port
  20168. Client client("localhost", 59999);
  20169. sse::SSEClient sse(client, "/events");
  20170. std::atomic<bool> error_called{false};
  20171. Error received_error = Error::Success;
  20172. sse.on_error([&](Error err) {
  20173. error_called.store(true);
  20174. received_error = err;
  20175. });
  20176. sse.set_reconnect_interval(50);
  20177. sse.set_max_reconnect_attempts(1);
  20178. sse.start_async();
  20179. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20180. sse.stop();
  20181. EXPECT_TRUE(error_called.load());
  20182. EXPECT_NE(received_error, Error::Success);
  20183. }
  20184. // Test: Last-Event-ID header sent on reconnect
  20185. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  20186. // Endpoint that sends event with ID
  20187. server_->Get("/event-with-id", [](const Request &, Response &res) {
  20188. res.set_chunked_content_provider(
  20189. "text/event-stream", [](size_t offset, DataSink &sink) {
  20190. if (offset == 0) {
  20191. std::string event = "id: evt-123\ndata: test\n\n";
  20192. sink.write(event.data(), event.size());
  20193. }
  20194. return false;
  20195. });
  20196. });
  20197. Client client("localhost", get_port());
  20198. sse::SSEClient sse(client, "/event-with-id");
  20199. std::atomic<bool> id_received{false};
  20200. sse.on_message([&](const sse::SSEMessage &msg) {
  20201. if (!msg.id.empty()) { id_received.store(true); }
  20202. });
  20203. sse.set_reconnect_interval(100);
  20204. sse.set_max_reconnect_attempts(1);
  20205. sse.start_async();
  20206. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20207. sse.stop();
  20208. EXPECT_TRUE(id_received.load());
  20209. EXPECT_EQ(sse.last_event_id(), "evt-123");
  20210. }
  20211. // Test: Manual stop
  20212. TEST_F(SSEIntegrationTest, ManualStop) {
  20213. // Endpoint that sends one event and stays open briefly
  20214. std::atomic<bool> handler_running{true};
  20215. server_->Get("/stay-open", [&handler_running](const Request &,
  20216. Response &res) {
  20217. res.set_chunked_content_provider(
  20218. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  20219. if (offset == 0) {
  20220. std::string event = "data: connected\n\n";
  20221. sink.write(event.data(), event.size());
  20222. }
  20223. // Keep connection open while handler_running is true
  20224. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  20225. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20226. }
  20227. return false;
  20228. });
  20229. });
  20230. Client client("localhost", get_port());
  20231. sse::SSEClient sse(client, "/stay-open");
  20232. std::atomic<bool> connected{false};
  20233. sse.on_open([&connected]() { connected.store(true); });
  20234. sse.set_reconnect_interval(100);
  20235. sse.set_max_reconnect_attempts(1);
  20236. sse.start_async();
  20237. // Wait for connection to establish
  20238. for (int i = 0; i < 20 && !connected.load(); ++i) {
  20239. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20240. }
  20241. EXPECT_TRUE(connected.load());
  20242. EXPECT_TRUE(sse.is_connected());
  20243. // Signal handler to stop
  20244. handler_running.store(false);
  20245. // Stop SSE client
  20246. sse.stop();
  20247. EXPECT_FALSE(sse.is_connected());
  20248. }
  20249. // Test: SSEClient with custom headers
  20250. TEST_F(SSEIntegrationTest, CustomHeaders) {
  20251. // Setup a server endpoint that checks for custom header
  20252. std::atomic<bool> header_received{false};
  20253. server_->Get("/header-check", [&](const Request &req, Response &res) {
  20254. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  20255. header_received.store(true);
  20256. }
  20257. res.set_chunked_content_provider("text/event-stream",
  20258. [](size_t, DataSink &) { return false; });
  20259. });
  20260. Client client("localhost", get_port());
  20261. Headers headers = {{"X-Custom-Header", "custom-value"}};
  20262. sse::SSEClient sse(client, "/header-check", headers);
  20263. sse.set_max_reconnect_attempts(1);
  20264. sse.start_async();
  20265. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  20266. sse.stop();
  20267. EXPECT_TRUE(header_received.load());
  20268. }
  20269. // Test: Reconnect interval configuration
  20270. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  20271. Client client("localhost", get_port());
  20272. sse::SSEClient sse(client, "/events");
  20273. auto &result = sse.set_reconnect_interval(500);
  20274. // Builder pattern should return reference to self
  20275. EXPECT_EQ(&result, &sse);
  20276. }
  20277. // Test: Max reconnect attempts
  20278. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  20279. // Connect to non-existent port to force reconnects
  20280. Client client("localhost", 59998);
  20281. sse::SSEClient sse(client, "/events");
  20282. std::atomic<int> error_count{0};
  20283. sse.on_error([&](Error) { error_count.fetch_add(1); });
  20284. sse.set_reconnect_interval(50);
  20285. sse.set_max_reconnect_attempts(2);
  20286. auto start = std::chrono::steady_clock::now();
  20287. sse.start(); // Blocking call
  20288. auto end = std::chrono::steady_clock::now();
  20289. // Should have stopped after 2 failed attempts
  20290. EXPECT_GE(error_count.load(), 2);
  20291. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  20292. auto duration =
  20293. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  20294. #ifdef _WIN32
  20295. // Windows is much slower for socket connection failures
  20296. EXPECT_LT(duration.count(), 7000);
  20297. #else
  20298. EXPECT_LT(duration.count(), 1000);
  20299. #endif
  20300. }
  20301. // Test: Multi-line data in integration
  20302. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  20303. // Endpoint with multi-line data
  20304. server_->Get("/multiline-data", [](const Request &, Response &res) {
  20305. res.set_chunked_content_provider(
  20306. "text/event-stream", [](size_t offset, DataSink &sink) {
  20307. if (offset == 0) {
  20308. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  20309. sink.write(event.data(), event.size());
  20310. }
  20311. return false;
  20312. });
  20313. });
  20314. Client client("localhost", get_port());
  20315. sse::SSEClient sse(client, "/multiline-data");
  20316. std::string received_data;
  20317. std::mutex data_mutex;
  20318. sse.on_message([&](const sse::SSEMessage &msg) {
  20319. std::lock_guard<std::mutex> lock(data_mutex);
  20320. received_data = msg.data;
  20321. });
  20322. sse.set_reconnect_interval(100);
  20323. sse.set_max_reconnect_attempts(1);
  20324. sse.start_async();
  20325. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20326. sse.stop();
  20327. std::lock_guard<std::mutex> lock(data_mutex);
  20328. EXPECT_EQ(received_data, "line1\nline2\nline3");
  20329. }
  20330. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  20331. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  20332. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  20333. DataSink &sink) {
  20334. if (offset == 0) {
  20335. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  20336. sink.write(events.data(), events.size());
  20337. }
  20338. return false;
  20339. });
  20340. });
  20341. Client client("localhost", get_port());
  20342. sse::SSEClient sse(client, "/empty-data-lines");
  20343. std::mutex mutex;
  20344. std::condition_variable cv;
  20345. std::vector<std::string> received;
  20346. sse.on_message([&](const sse::SSEMessage &msg) {
  20347. std::lock_guard<std::mutex> lock(mutex);
  20348. received.push_back(msg.data);
  20349. cv.notify_all();
  20350. });
  20351. sse.set_max_reconnect_attempts(1);
  20352. sse.start_async();
  20353. {
  20354. std::unique_lock<std::mutex> lock(mutex);
  20355. cv.wait_for(lock, std::chrono::seconds(2),
  20356. [&] { return received.size() >= 3; });
  20357. }
  20358. sse.stop();
  20359. ASSERT_GE(received.size(), 3u);
  20360. EXPECT_EQ(received[0], "");
  20361. EXPECT_EQ(received[1], "\nhello");
  20362. EXPECT_EQ(received[2], "");
  20363. }
  20364. // Test: Auto-reconnect after server disconnection
  20365. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  20366. std::atomic<int> connection_count{0};
  20367. std::atomic<int> message_count{0};
  20368. // Endpoint that sends one event and closes, forcing reconnect
  20369. server_->Get("/reconnect-test",
  20370. [&connection_count](const Request &, Response &res) {
  20371. connection_count.fetch_add(1);
  20372. res.set_chunked_content_provider(
  20373. "text/event-stream", [](size_t offset, DataSink &sink) {
  20374. if (offset == 0) {
  20375. std::string event = "data: hello\n\n";
  20376. sink.write(event.data(), event.size());
  20377. }
  20378. return false; // Close connection after sending
  20379. });
  20380. });
  20381. Client client("localhost", get_port());
  20382. sse::SSEClient sse(client, "/reconnect-test");
  20383. sse.on_message([&message_count](const sse::SSEMessage &) {
  20384. message_count.fetch_add(1);
  20385. });
  20386. sse.set_reconnect_interval(100);
  20387. sse.set_max_reconnect_attempts(3);
  20388. sse.start_async();
  20389. // Wait long enough for multiple reconnects
  20390. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20391. sse.stop();
  20392. // Should have connected multiple times (initial + reconnects)
  20393. EXPECT_GE(connection_count.load(), 2);
  20394. // Should have received messages from multiple connections
  20395. EXPECT_GE(message_count.load(), 2);
  20396. }
  20397. // Test: A retry field that is not all ASCII digits is ignored
  20398. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  20399. std::atomic<int> connection_count{0};
  20400. server_->Get("/bad-retry",
  20401. [&connection_count](const Request &, Response &res) {
  20402. connection_count.fetch_add(1);
  20403. res.set_chunked_content_provider(
  20404. "text/event-stream", [](size_t offset, DataSink &sink) {
  20405. if (offset == 0) {
  20406. std::string event = "retry: -1\ndata: hello\n\n";
  20407. sink.write(event.data(), event.size());
  20408. }
  20409. return false;
  20410. });
  20411. });
  20412. Client client("localhost", get_port());
  20413. sse::SSEClient sse(client, "/bad-retry");
  20414. sse.set_reconnect_interval(10000);
  20415. sse.start_async();
  20416. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20417. sse.stop();
  20418. EXPECT_EQ(connection_count.load(), 1);
  20419. }
  20420. // Test: A retry field of all ASCII digits sets the reconnection time
  20421. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  20422. std::mutex mutex;
  20423. std::condition_variable cv;
  20424. std::vector<std::chrono::steady_clock::time_point> connected_at;
  20425. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  20426. {
  20427. std::lock_guard<std::mutex> lock(mutex);
  20428. connected_at.push_back(std::chrono::steady_clock::now());
  20429. cv.notify_all();
  20430. }
  20431. res.set_chunked_content_provider(
  20432. "text/event-stream", [](size_t offset, DataSink &sink) {
  20433. if (offset == 0) {
  20434. std::string event = "retry: 0\ndata: hello\n\n";
  20435. sink.write(event.data(), event.size());
  20436. }
  20437. return false;
  20438. });
  20439. });
  20440. Client client("localhost", get_port());
  20441. sse::SSEClient sse(client, "/zero-retry");
  20442. sse.set_reconnect_interval(10000);
  20443. sse.start_async();
  20444. {
  20445. std::unique_lock<std::mutex> lock(mutex);
  20446. cv.wait_for(lock, std::chrono::seconds(5),
  20447. [&] { return connected_at.size() >= 2; });
  20448. }
  20449. sse.stop();
  20450. // The server-supplied interval is applied, but never below 100ms, so
  20451. // "retry: 0" does not cause a busy reconnect loop
  20452. std::lock_guard<std::mutex> lock(mutex);
  20453. ASSERT_GE(connected_at.size(), 2u);
  20454. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  20455. connected_at[1] - connected_at[0])
  20456. .count();
  20457. EXPECT_GE(interval_ms, 100);
  20458. }
  20459. // Test: Last-Event-ID sent on reconnect
  20460. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  20461. std::atomic<int> connection_count{0};
  20462. std::vector<std::string> received_last_event_ids;
  20463. std::mutex id_mutex;
  20464. // Endpoint that checks Last-Event-ID header and sends event with ID
  20465. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  20466. int conn = connection_count.fetch_add(1);
  20467. // Capture the Last-Event-ID header from each connection
  20468. {
  20469. std::lock_guard<std::mutex> lock(id_mutex);
  20470. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  20471. }
  20472. res.set_chunked_content_provider(
  20473. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  20474. if (offset == 0) {
  20475. std::string event =
  20476. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  20477. sink.write(event.data(), event.size());
  20478. }
  20479. return false;
  20480. });
  20481. });
  20482. Client client("localhost", get_port());
  20483. sse::SSEClient sse(client, "/reconnect-with-id");
  20484. sse.set_reconnect_interval(100);
  20485. sse.set_max_reconnect_attempts(3);
  20486. sse.start_async();
  20487. // Wait for at least 2 connections
  20488. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  20489. sse.stop();
  20490. // Verify behavior
  20491. std::lock_guard<std::mutex> lock(id_mutex);
  20492. EXPECT_GE(received_last_event_ids.size(), 2u);
  20493. // First connection should have no Last-Event-ID
  20494. if (!received_last_event_ids.empty()) {
  20495. EXPECT_EQ(received_last_event_ids[0], "");
  20496. }
  20497. // Second connection should have Last-Event-ID from first connection
  20498. if (received_last_event_ids.size() >= 2) {
  20499. EXPECT_EQ(received_last_event_ids[1], "event-0");
  20500. }
  20501. }
  20502. // Test: set_headers updates headers used on reconnect
  20503. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  20504. std::vector<std::string> received_tokens;
  20505. std::mutex token_mutex;
  20506. // Endpoint that captures Authorization header
  20507. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  20508. {
  20509. std::lock_guard<std::mutex> lock(token_mutex);
  20510. received_tokens.push_back(req.get_header_value("Authorization"));
  20511. }
  20512. res.set_chunked_content_provider(
  20513. "text/event-stream", [](size_t offset, DataSink &sink) {
  20514. if (offset == 0) {
  20515. std::string event = "data: hello\n\n";
  20516. sink.write(event.data(), event.size());
  20517. }
  20518. return false; // Close connection to trigger reconnect
  20519. });
  20520. });
  20521. Client client("localhost", get_port());
  20522. Headers headers = {{"Authorization", "Bearer old-token"}};
  20523. sse::SSEClient sse(client, "/auth-check", headers);
  20524. // Update headers on each successful connection
  20525. sse.on_open(
  20526. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  20527. sse.set_reconnect_interval(100);
  20528. sse.set_max_reconnect_attempts(3);
  20529. sse.start_async();
  20530. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20531. sse.stop();
  20532. std::lock_guard<std::mutex> lock(token_mutex);
  20533. ASSERT_GE(received_tokens.size(), 2u);
  20534. // First connection uses original header
  20535. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  20536. // Second connection uses updated header from set_headers
  20537. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  20538. }
  20539. // Test: 401 allows reconnection (so on_error can refresh headers)
  20540. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  20541. std::atomic<int> connection_count{0};
  20542. // Endpoint: returns 401 on first attempt, 200 on second
  20543. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  20544. int conn = connection_count.fetch_add(1);
  20545. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  20546. res.status = StatusCode::Unauthorized_401;
  20547. res.set_content("Unauthorized", "text/plain");
  20548. return;
  20549. }
  20550. res.set_chunked_content_provider(
  20551. "text/event-stream", [](size_t offset, DataSink &sink) {
  20552. if (offset == 0) {
  20553. std::string event = "data: authenticated\n\n";
  20554. sink.write(event.data(), event.size());
  20555. }
  20556. return false;
  20557. });
  20558. });
  20559. Client client("localhost", get_port());
  20560. Headers headers = {{"Authorization", "Bearer expired"}};
  20561. sse::SSEClient sse(client, "/auth-retry", headers);
  20562. std::atomic<bool> message_received{false};
  20563. // Refresh token on error
  20564. sse.on_error(
  20565. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  20566. sse.on_message([&](const sse::SSEMessage &msg) {
  20567. if (msg.data == "authenticated") { message_received.store(true); }
  20568. });
  20569. sse.set_reconnect_interval(100);
  20570. sse.set_max_reconnect_attempts(3);
  20571. sse.start_async();
  20572. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  20573. sse.stop();
  20574. // Should have reconnected after 401 and succeeded with new token
  20575. EXPECT_GE(connection_count.load(), 2);
  20576. EXPECT_TRUE(message_received.load());
  20577. }
  20578. TEST(Issue2318Test, EmptyHostString) {
  20579. {
  20580. httplib::Client cli_empty("", PORT);
  20581. auto res = cli_empty.Get("/");
  20582. ASSERT_FALSE(res);
  20583. EXPECT_EQ(httplib::Error::Connection, res.error());
  20584. }
  20585. {
  20586. httplib::Client cli(" ", PORT);
  20587. auto res = cli.Get("/");
  20588. ASSERT_FALSE(res);
  20589. EXPECT_EQ(httplib::Error::Connection, res.error());
  20590. }
  20591. }
  20592. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20593. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  20594. Server svr;
  20595. // Set a small payload limit (1KB)
  20596. svr.set_payload_max_length(1024);
  20597. svr.Post("/test", [&](const Request &req, Response &res) {
  20598. res.set_content("Body size: " + std::to_string(req.body.size()),
  20599. "text/plain");
  20600. });
  20601. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  20602. auto se = detail::scope_exit([&] {
  20603. svr.stop();
  20604. listen_thread.join();
  20605. });
  20606. svr.wait_until_ready();
  20607. // Create data that compresses well but exceeds limit when decompressed
  20608. // 8KB of repeated null bytes compresses to a very small size
  20609. std::string original_data(8 * 1024, '\0');
  20610. // Compress the data using gzip
  20611. std::string compressed_data;
  20612. detail::gzip_compressor compressor;
  20613. compressor.compress(original_data.data(), original_data.size(), true,
  20614. [&](const char *data, size_t size) {
  20615. compressed_data.append(data, size);
  20616. return true;
  20617. });
  20618. // Verify compression worked (compressed should be much smaller)
  20619. ASSERT_LT(compressed_data.size(), original_data.size());
  20620. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  20621. // Send compressed data with Content-Encoding: gzip
  20622. Client cli(HOST, PORT);
  20623. Headers headers = {{"Content-Encoding", "gzip"}};
  20624. auto res =
  20625. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  20626. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  20627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20628. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  20629. }
  20630. #endif
  20631. // ============================================================================
  20632. // OpenSSL-Specific Tests
  20633. // ============================================================================
  20634. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20635. X509 *readCertificate(const std::string &strFileName) {
  20636. std::ifstream inStream(strFileName);
  20637. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  20638. std::istreambuf_iterator<char>());
  20639. if (strCertPEM.empty()) return (nullptr);
  20640. BIO *pbCert = BIO_new(BIO_s_mem());
  20641. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  20642. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  20643. BIO_free(pbCert);
  20644. return (pCert);
  20645. }
  20646. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  20647. std::ifstream inStream(strFileName);
  20648. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  20649. std::istreambuf_iterator<char>());
  20650. if (strPrivateKeyPEM.empty()) return (nullptr);
  20651. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  20652. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  20653. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  20654. BIO_free(pbPrivKey);
  20655. return (pPrivateKey);
  20656. }
  20657. TEST(BindServerTest, UpdateCerts) {
  20658. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20659. int port = svr.bind_to_any_port("0.0.0.0");
  20660. ASSERT_TRUE(svr.is_valid());
  20661. ASSERT_TRUE(port > 0);
  20662. X509 *cert = readCertificate(SERVER_CERT_FILE);
  20663. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  20664. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  20665. ASSERT_TRUE(cert != nullptr);
  20666. ASSERT_TRUE(ca_cert != nullptr);
  20667. ASSERT_TRUE(key != nullptr);
  20668. X509_STORE *cert_store = X509_STORE_new();
  20669. X509_STORE_add_cert(cert_store, ca_cert);
  20670. // svr.update_certs(cert, key, cert_store); // deprecated
  20671. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  20672. CLIENT_CA_CERT_FILE);
  20673. ASSERT_TRUE(svr.is_valid());
  20674. svr.stop();
  20675. X509_STORE_free(cert_store);
  20676. X509_free(cert);
  20677. X509_free(ca_cert);
  20678. EVP_PKEY_free(key);
  20679. }
  20680. // Test that update_certs() updates client CA list correctly
  20681. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  20682. // Start with file-based constructor
  20683. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20684. ASSERT_TRUE(svr.is_valid());
  20685. // Initially no client CA list should be set
  20686. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20687. ASSERT_TRUE(ssl_ctx != nullptr);
  20688. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  20689. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  20690. EXPECT_EQ(0, count_before);
  20691. // Now update with client CA (PEM string)
  20692. std::string cert_pem, key_pem, ca_pem;
  20693. read_file(SERVER_CERT_FILE, cert_pem);
  20694. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  20695. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  20696. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  20697. ASSERT_TRUE(svr.is_valid());
  20698. // Now client CA list should be set
  20699. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  20700. ASSERT_TRUE(ca_list_after != nullptr);
  20701. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  20702. }
  20703. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  20704. // Test that the file-path SSLServer constructor properly sets the client CA
  20705. // list that is sent to clients during the TLS handshake (CertificateRequest)
  20706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20707. ASSERT_TRUE(svr.is_valid());
  20708. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  20709. ASSERT_TRUE(ssl_ctx != nullptr);
  20710. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  20711. ASSERT_TRUE(ca_list != nullptr);
  20712. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  20713. }
  20714. #endif
  20715. // ============================================================================
  20716. // MbedTLS-Specific Tests
  20717. // ============================================================================
  20718. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  20719. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  20720. using namespace httplib::tls;
  20721. // Track if callback was invoked
  20722. bool callback_invoked = false;
  20723. // The callback receives void* ctx which is actually MbedTlsContext*
  20724. // We can access the mbedtls_ssl_config via the context
  20725. auto setup_callback = [&callback_invoked](void *ctx) {
  20726. callback_invoked = true;
  20727. // Cast to MbedTlsContext* to access the ssl config
  20728. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  20729. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  20730. // Use static variables to hold certificate data (simplified for test)
  20731. static mbedtls_x509_crt own_cert;
  20732. static mbedtls_pk_context own_key;
  20733. static mbedtls_x509_crt ca_chain;
  20734. static bool initialized = false;
  20735. if (!initialized) {
  20736. mbedtls_x509_crt_init(&own_cert);
  20737. mbedtls_pk_init(&own_key);
  20738. mbedtls_x509_crt_init(&ca_chain);
  20739. // Load server certificate
  20740. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  20741. return false;
  20742. }
  20743. // Load server private key.
  20744. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  20745. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  20746. #if MBEDTLS_VERSION_MAJOR == 3
  20747. ,
  20748. mbedtls_ctr_drbg_random, nullptr
  20749. #endif
  20750. ) != 0) {
  20751. return false;
  20752. }
  20753. // Load CA chain for client verification
  20754. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  20755. return false;
  20756. }
  20757. initialized = true;
  20758. }
  20759. // Configure the SSL config
  20760. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  20761. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  20762. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  20763. // Set minimum TLS version using mbedTLS native API
  20764. #if MBEDTLS_VERSION_MAJOR >= 3
  20765. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  20766. #else
  20767. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  20768. MBEDTLS_SSL_MINOR_VERSION_3);
  20769. #endif
  20770. return true;
  20771. };
  20772. SSLServer svr(setup_callback);
  20773. ASSERT_TRUE(svr.is_valid());
  20774. ASSERT_TRUE(callback_invoked);
  20775. svr.Get("/test", [&](const Request &req, Response &res) {
  20776. res.set_content("test", "text/plain");
  20777. auto cert = req.peer_cert();
  20778. ASSERT_TRUE(static_cast<bool>(cert));
  20779. auto common_name = cert.subject_cn();
  20780. EXPECT_EQ("Common Name", common_name);
  20781. });
  20782. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20783. auto se = detail::scope_exit([&] {
  20784. svr.stop();
  20785. t.join();
  20786. ASSERT_FALSE(svr.is_running());
  20787. });
  20788. svr.wait_until_ready();
  20789. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  20790. cli.enable_server_certificate_verification(false);
  20791. cli.set_connection_timeout(30);
  20792. auto res = cli.Get("/test");
  20793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20794. ASSERT_EQ(StatusCode::OK_200, res->status);
  20795. }
  20796. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  20797. // context (owning mbedtls_ssl_config) before shutting down a still-open
  20798. // keep-alive SSL session, which reads through that config in
  20799. // mbedtls_ssl_close_notify.
  20800. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  20801. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20802. ASSERT_TRUE(svr.is_valid());
  20803. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  20804. res.set_content("test", "text/plain");
  20805. });
  20806. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  20807. auto se = detail::scope_exit([&] {
  20808. svr.stop();
  20809. t.join();
  20810. ASSERT_FALSE(svr.is_running());
  20811. });
  20812. svr.wait_until_ready();
  20813. {
  20814. SSLClient cli(HOST, PORT);
  20815. cli.enable_server_certificate_verification(false);
  20816. cli.set_keep_alive(true);
  20817. auto res = cli.Get("/test");
  20818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20819. ASSERT_EQ(StatusCode::OK_200, res->status);
  20820. // cli is destructed here with the keep-alive SSL session still open.
  20821. }
  20822. }
  20823. #endif
  20824. // WebSocket Tests
  20825. TEST(WebSocketTest, RSVBitsMustBeZero) {
  20826. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  20827. // defining the meaning of these bits has been negotiated.
  20828. auto make_frame = [](uint8_t first_byte) {
  20829. std::string frame;
  20830. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  20831. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  20832. frame += "Hello";
  20833. return frame;
  20834. };
  20835. // RSV1 set (0x40)
  20836. {
  20837. detail::BufferStream strm;
  20838. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  20839. ws::Opcode opcode;
  20840. std::string payload;
  20841. bool fin;
  20842. EXPECT_EQ(
  20843. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20844. ws::impl::FrameRead::Fail);
  20845. }
  20846. // RSV2 set (0x20)
  20847. {
  20848. detail::BufferStream strm;
  20849. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  20850. ws::Opcode opcode;
  20851. std::string payload;
  20852. bool fin;
  20853. EXPECT_EQ(
  20854. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20855. ws::impl::FrameRead::Fail);
  20856. }
  20857. // RSV3 set (0x10)
  20858. {
  20859. detail::BufferStream strm;
  20860. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  20861. ws::Opcode opcode;
  20862. std::string payload;
  20863. bool fin;
  20864. EXPECT_EQ(
  20865. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20866. ws::impl::FrameRead::Fail);
  20867. }
  20868. // No RSV bits set - should succeed
  20869. {
  20870. detail::BufferStream strm;
  20871. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  20872. ws::Opcode opcode;
  20873. std::string payload;
  20874. bool fin;
  20875. EXPECT_EQ(
  20876. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20877. ws::impl::FrameRead::Ok);
  20878. EXPECT_EQ(ws::Opcode::Text, opcode);
  20879. EXPECT_EQ("Hello", payload);
  20880. EXPECT_TRUE(fin);
  20881. }
  20882. }
  20883. TEST(WebSocketTest, ControlFrameValidation) {
  20884. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  20885. // payload length <= 125.
  20886. // Ping with FIN=0 - must be rejected
  20887. {
  20888. detail::BufferStream strm;
  20889. std::string frame;
  20890. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  20891. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20892. strm.write(frame.data(), frame.size());
  20893. ws::Opcode opcode;
  20894. std::string payload;
  20895. bool fin;
  20896. EXPECT_EQ(
  20897. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20898. ws::impl::FrameRead::Fail);
  20899. }
  20900. // Close with FIN=0 - must be rejected
  20901. {
  20902. detail::BufferStream strm;
  20903. std::string frame;
  20904. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  20905. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  20906. strm.write(frame.data(), frame.size());
  20907. ws::Opcode opcode;
  20908. std::string payload;
  20909. bool fin;
  20910. EXPECT_EQ(
  20911. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20912. ws::impl::FrameRead::Fail);
  20913. }
  20914. // Ping with payload_len=126 (extended length) - must be rejected
  20915. {
  20916. detail::BufferStream strm;
  20917. std::string frame;
  20918. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20919. frame += static_cast<char>(126); // payload_len=126 (>125)
  20920. frame += static_cast<char>(0x00); // extended length high byte
  20921. frame += static_cast<char>(126); // extended length low byte
  20922. frame += std::string(126, 'x');
  20923. strm.write(frame.data(), frame.size());
  20924. ws::Opcode opcode;
  20925. std::string payload;
  20926. bool fin;
  20927. EXPECT_EQ(
  20928. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20929. ws::impl::FrameRead::Fail);
  20930. }
  20931. // Ping with FIN=1 and payload_len=125 - should succeed
  20932. {
  20933. detail::BufferStream strm;
  20934. std::string frame;
  20935. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  20936. frame += static_cast<char>(125); // payload_len=125
  20937. frame += std::string(125, 'x');
  20938. strm.write(frame.data(), frame.size());
  20939. ws::Opcode opcode;
  20940. std::string payload;
  20941. bool fin;
  20942. EXPECT_EQ(
  20943. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20944. ws::impl::FrameRead::Ok);
  20945. EXPECT_EQ(ws::Opcode::Ping, opcode);
  20946. EXPECT_EQ(125u, payload.size());
  20947. EXPECT_TRUE(fin);
  20948. }
  20949. }
  20950. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  20951. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  20952. // length MUST be 0.
  20953. // MSB set - must be rejected
  20954. {
  20955. detail::BufferStream strm;
  20956. std::string frame;
  20957. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20958. frame += static_cast<char>(127); // 64-bit extended length
  20959. frame += static_cast<char>(0x80); // MSB set (invalid)
  20960. frame += std::string(7, '\0'); // remaining 7 bytes of length
  20961. strm.write(frame.data(), frame.size());
  20962. ws::Opcode opcode;
  20963. std::string payload;
  20964. bool fin;
  20965. EXPECT_EQ(
  20966. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20967. ws::impl::FrameRead::Fail);
  20968. }
  20969. // MSB clear - should pass length parsing (will be rejected by max_len,
  20970. // but that's a different check; use a small length to verify)
  20971. {
  20972. detail::BufferStream strm;
  20973. std::string frame;
  20974. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  20975. frame += static_cast<char>(127); // 64-bit extended length
  20976. frame += std::string(7, '\0'); // high bytes = 0
  20977. frame += static_cast<char>(0x03); // length = 3
  20978. frame += "abc";
  20979. strm.write(frame.data(), frame.size());
  20980. ws::Opcode opcode;
  20981. std::string payload;
  20982. bool fin;
  20983. EXPECT_EQ(
  20984. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  20985. ws::impl::FrameRead::Ok);
  20986. EXPECT_EQ(ws::Opcode::Text, opcode);
  20987. EXPECT_EQ("abc", payload);
  20988. }
  20989. }
  20990. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  20991. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  20992. // Valid UTF-8
  20993. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  20994. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  20995. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  20996. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  20997. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  20998. // Invalid UTF-8
  20999. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  21000. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  21001. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  21002. EXPECT_FALSE(
  21003. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  21004. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  21005. }
  21006. TEST(WebSocketTest, ConnectAndDisconnect) {
  21007. Server svr;
  21008. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21009. std::string msg;
  21010. while (ws.read(msg)) {}
  21011. });
  21012. auto port = svr.bind_to_any_port(HOST);
  21013. std::thread t([&]() { svr.listen_after_bind(); });
  21014. svr.wait_until_ready();
  21015. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21016. auto res = client.connect();
  21017. ASSERT_TRUE(res);
  21018. EXPECT_EQ(Error::Success, res.error());
  21019. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  21020. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  21021. EXPECT_TRUE(client.is_open());
  21022. client.close();
  21023. EXPECT_FALSE(client.is_open());
  21024. svr.stop();
  21025. t.join();
  21026. }
  21027. TEST(WebSocketTest, ValidURL) {
  21028. ws::WebSocketClient ws1("ws://localhost:8080/path");
  21029. EXPECT_TRUE(ws1.is_valid());
  21030. ws::WebSocketClient ws2("ws://example.com/path");
  21031. EXPECT_TRUE(ws2.is_valid());
  21032. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  21033. EXPECT_TRUE(ws3.is_valid());
  21034. #ifdef CPPHTTPLIB_SSL_ENABLED
  21035. ws::WebSocketClient wss1("wss://example.com/path");
  21036. EXPECT_TRUE(wss1.is_valid());
  21037. ws::WebSocketClient wss2("wss://example.com:443/path");
  21038. EXPECT_TRUE(wss2.is_valid());
  21039. #endif
  21040. }
  21041. TEST(WebSocketTest, InvalidURL) {
  21042. // No scheme
  21043. ws::WebSocketClient ws1("localhost:8080/path");
  21044. EXPECT_FALSE(ws1.is_valid());
  21045. // No path
  21046. ws::WebSocketClient ws2("ws://localhost:8080");
  21047. EXPECT_FALSE(ws2.is_valid());
  21048. // Empty string
  21049. ws::WebSocketClient ws3("");
  21050. EXPECT_FALSE(ws3.is_valid());
  21051. // Missing host
  21052. ws::WebSocketClient ws4("ws://:8080/path");
  21053. EXPECT_FALSE(ws4.is_valid());
  21054. // Port number overflow — should not crash
  21055. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  21056. EXPECT_FALSE(ws5.is_valid());
  21057. // Port out of range
  21058. ws::WebSocketClient ws6("ws://localhost:99999/path");
  21059. EXPECT_FALSE(ws6.is_valid());
  21060. }
  21061. TEST(WebSocketTest, UnsupportedScheme) {
  21062. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  21063. ws::WebSocketClient ws1("http://localhost:8080/path");
  21064. EXPECT_FALSE(ws1.is_valid());
  21065. ws::WebSocketClient ws2("https://localhost:8080/path");
  21066. EXPECT_FALSE(ws2.is_valid());
  21067. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  21068. EXPECT_FALSE(ws3.is_valid());
  21069. #else
  21070. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  21071. std::invalid_argument);
  21072. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  21073. std::invalid_argument);
  21074. #endif
  21075. }
  21076. TEST(WebSocketTest, ConnectWhenInvalid) {
  21077. ws::WebSocketClient ws("not a valid url");
  21078. EXPECT_FALSE(ws.is_valid());
  21079. auto res = ws.connect();
  21080. EXPECT_FALSE(res);
  21081. EXPECT_EQ(Error::Connection, res.error());
  21082. EXPECT_EQ(-1, res.status());
  21083. }
  21084. TEST(WebSocketTest, ConnectRefusedReportsError) {
  21085. // Grab a port that is free, then close it again so nothing listens there
  21086. Server svr;
  21087. auto port = svr.bind_to_any_port(HOST);
  21088. svr.stop();
  21089. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21090. auto res = client.connect();
  21091. ASSERT_FALSE(res);
  21092. EXPECT_EQ(Error::Connection, res.error());
  21093. EXPECT_EQ(-1, res.status());
  21094. }
  21095. TEST(WebSocketTest, DefaultPort) {
  21096. ws::WebSocketClient ws1("ws://example.com/path");
  21097. EXPECT_TRUE(ws1.is_valid());
  21098. // ws:// defaults to port 80 (verified by successful parse)
  21099. #ifdef CPPHTTPLIB_SSL_ENABLED
  21100. ws::WebSocketClient ws2("wss://example.com/path");
  21101. EXPECT_TRUE(ws2.is_valid());
  21102. // wss:// defaults to port 443 (verified by successful parse)
  21103. #endif
  21104. }
  21105. TEST(WebSocketTest, IPv6LiteralAddress) {
  21106. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  21107. EXPECT_TRUE(ws1.is_valid());
  21108. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  21109. EXPECT_TRUE(ws2.is_valid());
  21110. }
  21111. TEST(WebSocketTest, ComplexPath) {
  21112. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  21113. EXPECT_TRUE(ws1.is_valid());
  21114. ws::WebSocketClient ws2("ws://localhost:8080/");
  21115. EXPECT_TRUE(ws2.is_valid());
  21116. }
  21117. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  21118. Server svr;
  21119. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21120. std::string msg;
  21121. while (ws.read(msg)) {}
  21122. });
  21123. auto port = svr.bind_to_any_port(HOST);
  21124. std::thread t([&]() { svr.listen_after_bind(); });
  21125. svr.wait_until_ready();
  21126. auto another_host = "example.com";
  21127. auto wrong_ip = "192.0.2.1";
  21128. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21129. client.set_hostname_addr_map({{another_host, wrong_ip}});
  21130. ASSERT_TRUE(client.connect());
  21131. EXPECT_TRUE(client.is_open());
  21132. client.close();
  21133. svr.stop();
  21134. t.join();
  21135. }
  21136. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  21137. Server svr;
  21138. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21139. std::string msg;
  21140. while (ws.read(msg)) {}
  21141. });
  21142. auto port = svr.bind_to_any_port(HOST);
  21143. std::thread t([&]() { svr.listen_after_bind(); });
  21144. svr.wait_until_ready();
  21145. auto wrong_ip = "192.0.2.1";
  21146. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21147. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  21148. client.set_connection_timeout(1);
  21149. client.set_read_timeout(1);
  21150. client.set_write_timeout(1);
  21151. EXPECT_FALSE(client.connect());
  21152. EXPECT_FALSE(client.is_open());
  21153. svr.stop();
  21154. t.join();
  21155. }
  21156. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  21157. // A mapped value that is not an IP literal must be resolved. HOST resolves
  21158. // from the hosts file, so this test needs no external DNS. "target.invalid"
  21159. // (RFC 6761) is only a map key and the Host header value.
  21160. auto host = "target.invalid";
  21161. Server svr;
  21162. std::string received_host;
  21163. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21164. received_host = req.get_header_value("Host");
  21165. std::string msg;
  21166. while (ws.read(msg)) {}
  21167. });
  21168. auto port = svr.bind_to_any_port(HOST);
  21169. std::thread t([&]() { svr.listen_after_bind(); });
  21170. // ASSERT_* below returns from the test body, which would leave t joinable
  21171. // and make ~thread call std::terminate.
  21172. auto se = detail::scope_exit([&] {
  21173. svr.stop();
  21174. if (t.joinable()) { t.join(); }
  21175. });
  21176. svr.wait_until_ready();
  21177. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  21178. std::to_string(port) + "/ws");
  21179. client.set_hostname_addr_map({{host, HOST}});
  21180. ASSERT_TRUE(client.connect());
  21181. EXPECT_TRUE(client.is_open());
  21182. client.close();
  21183. svr.stop();
  21184. t.join();
  21185. // The mapping only redirects the connection; the identity stays host_.
  21186. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  21187. }
  21188. class WebSocketIntegrationTest : public ::testing::Test {
  21189. protected:
  21190. void SetUp() override {
  21191. server_ = httplib::detail::make_unique<Server>();
  21192. setup_server();
  21193. start_server();
  21194. }
  21195. void TearDown() override {
  21196. server_->stop();
  21197. if (server_thread_.joinable()) { server_thread_.join(); }
  21198. }
  21199. void setup_server() {
  21200. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  21201. std::string msg;
  21202. ws::ReadResult ret;
  21203. while ((ret = ws.read(msg))) {
  21204. if (ret == ws::Binary) {
  21205. ws.send(msg.data(), msg.size());
  21206. } else {
  21207. ws.send(msg);
  21208. }
  21209. }
  21210. });
  21211. server_->WebSocket("/ws-echo-string",
  21212. [](const Request &, ws::WebSocket &ws) {
  21213. std::string msg;
  21214. while (ws.read(msg)) {
  21215. ws.send("echo: " + msg);
  21216. }
  21217. });
  21218. server_->WebSocket(
  21219. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  21220. // Echo back request metadata
  21221. ws.send("path:" + req.path);
  21222. ws.send("header:" + req.get_header_value("X-Test-Header"));
  21223. std::string msg;
  21224. while (ws.read(msg)) {}
  21225. });
  21226. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  21227. std::string msg;
  21228. ws.read(msg); // wait for a message
  21229. ws.close();
  21230. });
  21231. server_->WebSocket("/ws-close-status",
  21232. [](const Request &, ws::WebSocket &ws) {
  21233. std::string msg;
  21234. ws.read(msg); // wait for a message
  21235. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  21236. });
  21237. server_->WebSocket(
  21238. "/ws-subprotocol",
  21239. [](const Request &, ws::WebSocket &ws) {
  21240. std::string msg;
  21241. while (ws.read(msg)) {
  21242. ws.send(msg);
  21243. }
  21244. },
  21245. [](const std::vector<std::string> &protocols) -> std::string {
  21246. for (const auto &p : protocols) {
  21247. if (p == "graphql-ws") { return p; }
  21248. }
  21249. return "";
  21250. });
  21251. server_->WebSocket(
  21252. "/ws-subprotocol-unoffered",
  21253. [](const Request &, ws::WebSocket &ws) {
  21254. std::string msg;
  21255. while (ws.read(msg)) {
  21256. ws.send(msg);
  21257. }
  21258. },
  21259. [](const std::vector<std::string> &) -> std::string {
  21260. return "admin";
  21261. });
  21262. }
  21263. void start_server() {
  21264. port_ = server_->bind_to_any_port(HOST);
  21265. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21266. server_->wait_until_ready();
  21267. }
  21268. std::unique_ptr<Server> server_;
  21269. std::thread server_thread_;
  21270. int port_ = 0;
  21271. };
  21272. TEST_F(WebSocketIntegrationTest, TextEcho) {
  21273. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21274. "/ws-echo");
  21275. ASSERT_TRUE(client.connect());
  21276. ASSERT_TRUE(client.is_open());
  21277. ASSERT_TRUE(client.send("Hello WebSocket"));
  21278. std::string msg;
  21279. EXPECT_EQ(ws::Text, client.read(msg));
  21280. EXPECT_EQ("Hello WebSocket", msg);
  21281. client.close();
  21282. }
  21283. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  21284. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21285. "/ws-echo");
  21286. ASSERT_TRUE(client.connect());
  21287. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  21288. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  21289. std::string msg;
  21290. EXPECT_EQ(ws::Binary, client.read(msg));
  21291. EXPECT_EQ(binary_data, msg);
  21292. client.close();
  21293. }
  21294. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  21295. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21296. "/ws-echo");
  21297. ASSERT_TRUE(client.connect());
  21298. for (int i = 0; i < 10; i++) {
  21299. auto text = "message " + std::to_string(i);
  21300. ASSERT_TRUE(client.send(text));
  21301. std::string msg;
  21302. ASSERT_TRUE(client.read(msg));
  21303. EXPECT_EQ(text, msg);
  21304. }
  21305. client.close();
  21306. }
  21307. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  21308. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21309. "/ws-close");
  21310. ASSERT_TRUE(client.connect());
  21311. // Send a message to trigger the server to close
  21312. ASSERT_TRUE(client.send("trigger close"));
  21313. // The server will close, so read should return false
  21314. std::string msg;
  21315. EXPECT_FALSE(client.read(msg));
  21316. EXPECT_FALSE(client.is_open());
  21317. }
  21318. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  21319. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21320. "/ws-echo");
  21321. ASSERT_TRUE(client.connect());
  21322. // 128KB message
  21323. std::string large_data(128 * 1024, 'X');
  21324. ASSERT_TRUE(client.send(large_data));
  21325. std::string msg;
  21326. ASSERT_TRUE(client.read(msg));
  21327. EXPECT_EQ(large_data, msg);
  21328. client.close();
  21329. }
  21330. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  21331. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21332. "/ws-echo");
  21333. ASSERT_TRUE(client.connect());
  21334. const int num_threads = 4;
  21335. std::vector<std::thread> threads;
  21336. std::atomic<int> send_count{0};
  21337. for (int t = 0; t < num_threads; t++) {
  21338. threads.emplace_back([&client, &send_count, t]() {
  21339. for (int i = 0; i < 5; i++) {
  21340. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  21341. if (client.send(text)) { send_count++; }
  21342. }
  21343. });
  21344. }
  21345. for (auto &th : threads) {
  21346. th.join();
  21347. }
  21348. int received = 0;
  21349. std::string msg;
  21350. while (received < send_count.load()) {
  21351. if (!client.read(msg)) { break; }
  21352. received++;
  21353. }
  21354. EXPECT_EQ(send_count.load(), received);
  21355. client.close();
  21356. }
  21357. TEST_F(WebSocketIntegrationTest, ReadString) {
  21358. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21359. "/ws-echo-string");
  21360. ASSERT_TRUE(client.connect());
  21361. ASSERT_TRUE(client.send("hello"));
  21362. std::string msg;
  21363. ASSERT_TRUE(client.read(msg));
  21364. EXPECT_EQ("echo: hello", msg);
  21365. ASSERT_TRUE(client.send("world"));
  21366. ASSERT_TRUE(client.read(msg));
  21367. EXPECT_EQ("echo: world", msg);
  21368. client.close();
  21369. }
  21370. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  21371. Headers headers = {{"X-Test-Header", "test-value"}};
  21372. ws::WebSocketClient client(
  21373. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  21374. ASSERT_TRUE(client.connect());
  21375. std::string msg;
  21376. ASSERT_TRUE(client.read(msg));
  21377. EXPECT_EQ("path:/ws-request-info", msg);
  21378. ASSERT_TRUE(client.read(msg));
  21379. EXPECT_EQ("header:test-value", msg);
  21380. client.close();
  21381. }
  21382. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  21383. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21384. "/ws-echo");
  21385. client.set_read_timeout(1, 0); // 1 second
  21386. ASSERT_TRUE(client.connect());
  21387. // Don't send anything — server echo handler waits for a message, so read()
  21388. // should time out. The connection survives it: nothing was consumed.
  21389. std::string msg;
  21390. EXPECT_EQ(client.read(msg), ws::Timeout);
  21391. EXPECT_TRUE(client.is_open());
  21392. // And it is still usable afterwards.
  21393. EXPECT_TRUE(client.send("after timeout"));
  21394. EXPECT_EQ(client.read(msg), ws::Text);
  21395. EXPECT_EQ(msg, "after timeout");
  21396. }
  21397. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  21398. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21399. "/ws-echo");
  21400. client.set_read_timeout(1, 0);
  21401. ASSERT_TRUE(client.connect());
  21402. ASSERT_TRUE(client.send("first"));
  21403. std::string msg;
  21404. ASSERT_EQ(client.read(msg), ws::Text);
  21405. ASSERT_EQ(msg, "first");
  21406. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  21407. // not be used with a read timeout: it would reprocess the previous message.
  21408. EXPECT_EQ(client.read(msg), ws::Timeout);
  21409. EXPECT_EQ(msg, "first");
  21410. }
  21411. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  21412. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21413. "/ws-echo");
  21414. ASSERT_TRUE(client.connect());
  21415. // Setting it once the connection is open reaches the live stream, not just
  21416. // the seed for the next connect().
  21417. client.set_read_timeout(1, 0);
  21418. std::string msg;
  21419. EXPECT_EQ(client.read(msg), ws::Timeout);
  21420. EXPECT_TRUE(client.is_open());
  21421. }
  21422. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  21423. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21424. "/ws-echo");
  21425. client.set_read_timeout(5, 0);
  21426. ASSERT_TRUE(client.connect());
  21427. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21428. // The server should reject it and close the connection.
  21429. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  21430. client.send(oversized);
  21431. // The server's read() should have failed due to payload limit,
  21432. // so our read() should return false (connection closed).
  21433. std::string msg;
  21434. EXPECT_FALSE(client.read(msg));
  21435. }
  21436. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  21437. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21438. "/ws-echo");
  21439. client.set_read_timeout(10, 0);
  21440. ASSERT_TRUE(client.connect());
  21441. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  21442. // This should succeed.
  21443. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  21444. ASSERT_TRUE(client.send(at_limit));
  21445. std::string msg;
  21446. ASSERT_TRUE(client.read(msg));
  21447. EXPECT_EQ(at_limit.size(), msg.size());
  21448. client.close();
  21449. }
  21450. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  21451. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21452. "/nonexistent");
  21453. auto res = client.connect();
  21454. EXPECT_FALSE(res);
  21455. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  21456. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  21457. EXPECT_FALSE(client.is_open());
  21458. }
  21459. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  21460. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21461. "/ws-echo");
  21462. ASSERT_TRUE(client.connect());
  21463. ASSERT_TRUE(client.send(""));
  21464. std::string msg;
  21465. EXPECT_EQ(ws::Text, client.read(msg));
  21466. EXPECT_EQ("", msg);
  21467. client.close();
  21468. }
  21469. TEST_F(WebSocketIntegrationTest, Reconnect) {
  21470. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21471. "/ws-echo");
  21472. // First connection
  21473. ASSERT_TRUE(client.connect());
  21474. ASSERT_TRUE(client.send("first"));
  21475. std::string msg;
  21476. ASSERT_TRUE(client.read(msg));
  21477. EXPECT_EQ("first", msg);
  21478. client.close();
  21479. EXPECT_FALSE(client.is_open());
  21480. // Reconnect using the same client object
  21481. ASSERT_TRUE(client.connect());
  21482. ASSERT_TRUE(client.is_open());
  21483. ASSERT_TRUE(client.send("second"));
  21484. ASSERT_TRUE(client.read(msg));
  21485. EXPECT_EQ("second", msg);
  21486. client.close();
  21487. }
  21488. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  21489. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21490. "/ws-close-status");
  21491. ASSERT_TRUE(client.connect());
  21492. // Trigger the server to close with GoingAway status
  21493. ASSERT_TRUE(client.send("trigger"));
  21494. // read() should return false after receiving the close frame
  21495. std::string msg;
  21496. EXPECT_FALSE(client.read(msg));
  21497. EXPECT_FALSE(client.is_open());
  21498. }
  21499. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  21500. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21501. "/ws-echo");
  21502. ASSERT_TRUE(client.connect());
  21503. client.close(ws::CloseStatus::GoingAway, "client leaving");
  21504. EXPECT_FALSE(client.is_open());
  21505. }
  21506. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  21507. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  21508. ws::WebSocketClient client(
  21509. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21510. ASSERT_TRUE(client.connect());
  21511. // Server should have selected graphql-ws
  21512. EXPECT_EQ("graphql-ws", client.subprotocol());
  21513. client.close();
  21514. }
  21515. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  21516. Headers headers;
  21517. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  21518. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  21519. ws::WebSocketClient client(
  21520. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21521. ASSERT_TRUE(client.connect());
  21522. // The offer on the second field line counts too, so graphql-ws is selected
  21523. EXPECT_EQ("graphql-ws", client.subprotocol());
  21524. client.close();
  21525. }
  21526. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  21527. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  21528. ws::WebSocketClient client(
  21529. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  21530. ASSERT_TRUE(client.connect());
  21531. // Server should not have selected any subprotocol
  21532. EXPECT_TRUE(client.subprotocol().empty());
  21533. client.close();
  21534. }
  21535. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  21536. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  21537. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21538. "/ws-subprotocol-unoffered",
  21539. headers);
  21540. ASSERT_TRUE(client.connect());
  21541. EXPECT_TRUE(client.subprotocol().empty());
  21542. client.close();
  21543. }
  21544. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  21545. // Connect without requesting any subprotocol
  21546. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21547. "/ws-subprotocol");
  21548. ASSERT_TRUE(client.connect());
  21549. EXPECT_TRUE(client.subprotocol().empty());
  21550. client.close();
  21551. }
  21552. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  21553. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21554. "/ws-echo");
  21555. client.set_tcp_nodelay(true);
  21556. client.set_connection_timeout(3, 0);
  21557. bool socket_options_called = false;
  21558. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  21559. ASSERT_TRUE(client.connect());
  21560. ASSERT_TRUE(client.is_open());
  21561. EXPECT_TRUE(socket_options_called);
  21562. ASSERT_TRUE(client.send("hello"));
  21563. std::string msg;
  21564. auto result = client.read(msg);
  21565. EXPECT_EQ(result, ws::ReadResult::Text);
  21566. EXPECT_EQ(msg, "hello");
  21567. client.close();
  21568. }
  21569. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  21570. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  21571. "/ws-echo");
  21572. client.set_connection_timeout(std::chrono::seconds(3));
  21573. client.set_write_timeout(std::chrono::seconds(3));
  21574. // A sub-second remainder exercises the seconds/microseconds split.
  21575. client.set_read_timeout(std::chrono::milliseconds(1500));
  21576. ASSERT_TRUE(client.connect());
  21577. auto start = std::chrono::steady_clock::now();
  21578. std::string msg;
  21579. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  21580. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  21581. std::chrono::steady_clock::now() - start)
  21582. .count();
  21583. // Above 1s so that dropping the microseconds half of the split fails here.
  21584. // Ignoring the setter altogether would not reach this line at all: a client
  21585. // waits forever by default.
  21586. EXPECT_GE(elapsed, 1400);
  21587. EXPECT_LT(elapsed, 30000);
  21588. }
  21589. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  21590. Server svr;
  21591. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  21592. if (!req.has_header("Authorization")) {
  21593. res.status = StatusCode::Unauthorized_401;
  21594. res.set_content("Unauthorized", "text/plain");
  21595. return Server::HandlerResponse::Handled;
  21596. }
  21597. return Server::HandlerResponse::Unhandled;
  21598. });
  21599. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21600. std::string msg;
  21601. while (ws.read(msg)) {
  21602. ws.send(msg);
  21603. }
  21604. });
  21605. auto port = svr.bind_to_any_port("localhost");
  21606. std::thread t([&]() { svr.listen_after_bind(); });
  21607. svr.wait_until_ready();
  21608. // Without Authorization header - should be rejected before upgrade
  21609. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  21610. EXPECT_FALSE(client1.connect());
  21611. // The rejection is framed like any other HTTP response
  21612. {
  21613. Client cli("localhost", port);
  21614. Headers headers = {{"Upgrade", "websocket"},
  21615. {"Connection", "Upgrade"},
  21616. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21617. {"Sec-WebSocket-Version", "13"}};
  21618. auto res = cli.Get("/ws", headers);
  21619. ASSERT_TRUE(res);
  21620. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21621. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21622. EXPECT_EQ("Unauthorized", res->body);
  21623. }
  21624. // With Authorization header - should succeed
  21625. Headers headers = {{"Authorization", "Bearer token123"}};
  21626. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  21627. headers);
  21628. ASSERT_TRUE(client2.connect());
  21629. ASSERT_TRUE(client2.send("hello"));
  21630. std::string msg;
  21631. ASSERT_TRUE(client2.read(msg));
  21632. EXPECT_EQ("hello", msg);
  21633. client2.close();
  21634. svr.stop();
  21635. t.join();
  21636. }
  21637. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  21638. Server svr;
  21639. std::atomic<int> pre_request_calls{0};
  21640. std::atomic<bool> route_matched{false};
  21641. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  21642. pre_request_calls++;
  21643. if (req.matched_route == "/ws/:id") { route_matched = true; }
  21644. if (req.get_header_value("Authorization") != "Bearer token123") {
  21645. res.status = StatusCode::Unauthorized_401;
  21646. res.set_content("Unauthorized", "text/plain");
  21647. return Server::HandlerResponse::Handled;
  21648. }
  21649. return Server::HandlerResponse::Unhandled;
  21650. });
  21651. std::atomic<bool> handler_called{false};
  21652. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  21653. handler_called = true;
  21654. ws.send(req.matched_route + " " + req.path_params.at("id"));
  21655. });
  21656. auto port = svr.bind_to_any_port("localhost");
  21657. std::thread t([&]() { svr.listen_after_bind(); });
  21658. svr.wait_until_ready();
  21659. // Without Authorization header - should be rejected before upgrade
  21660. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  21661. "/ws/1");
  21662. EXPECT_FALSE(client1.connect());
  21663. EXPECT_FALSE(handler_called);
  21664. EXPECT_EQ(1, pre_request_calls);
  21665. EXPECT_TRUE(route_matched);
  21666. // The rejection is an ordinary HTTP response, not a protocol switch
  21667. {
  21668. Client cli("localhost", port);
  21669. Headers headers = {{"Upgrade", "websocket"},
  21670. {"Connection", "Upgrade"},
  21671. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  21672. {"Sec-WebSocket-Version", "13"}};
  21673. auto res = cli.Get("/ws/1", headers);
  21674. ASSERT_TRUE(res);
  21675. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21676. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  21677. EXPECT_EQ("Unauthorized", res->body);
  21678. }
  21679. EXPECT_FALSE(handler_called);
  21680. // With Authorization header - should succeed
  21681. Headers headers = {{"Authorization", "Bearer token123"}};
  21682. ws::WebSocketClient client2(
  21683. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  21684. ASSERT_TRUE(client2.connect());
  21685. std::string msg;
  21686. ASSERT_TRUE(client2.read(msg));
  21687. EXPECT_EQ("/ws/:id 2", msg);
  21688. EXPECT_TRUE(handler_called);
  21689. client2.close();
  21690. svr.stop();
  21691. t.join();
  21692. }
  21693. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  21694. Server svr;
  21695. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  21696. // A read timeout is how a handler gets control back. Without it, a handler
  21697. // parked in read() can never write on the connection it is reading.
  21698. ws.set_read_timeout(std::chrono::milliseconds(100));
  21699. std::string msg;
  21700. while (ws.is_open()) {
  21701. auto r = ws.read(msg);
  21702. if (r == httplib::ws::Timeout) {
  21703. ws.send("tick");
  21704. continue;
  21705. }
  21706. if (r == httplib::ws::Fail) { break; }
  21707. ws.send(msg);
  21708. }
  21709. });
  21710. auto port = svr.bind_to_any_port("localhost");
  21711. std::thread t([&]() { svr.listen_after_bind(); });
  21712. svr.wait_until_ready();
  21713. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  21714. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  21715. ASSERT_TRUE(client.connect());
  21716. // The client sends nothing, so anything it receives came out of the
  21717. // handler's timeout path.
  21718. std::string msg;
  21719. ASSERT_EQ(client.read(msg), ws::Text);
  21720. EXPECT_EQ("tick", msg);
  21721. client.close();
  21722. svr.stop();
  21723. t.join();
  21724. }
  21725. // Stream::read may return fewer bytes than asked for. This is that contract at
  21726. // its worst -- one byte per call -- which is what a frame header straddling a
  21727. // read buffer's boundary looks like to the frame parser.
  21728. class WsByteAtATimeStream : public Stream {
  21729. public:
  21730. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  21731. bool is_readable() const override { return true; }
  21732. bool wait_readable() const override { return true; }
  21733. bool wait_writable() const override { return true; }
  21734. ssize_t read(char *ptr, size_t size) override {
  21735. if (size == 0 || pos_ >= data_.size()) { return 0; }
  21736. *ptr = data_[pos_++];
  21737. return 1;
  21738. }
  21739. ssize_t write(const char *, size_t size) override {
  21740. return static_cast<ssize_t>(size);
  21741. }
  21742. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  21743. ip = "127.0.0.1";
  21744. port = 0;
  21745. }
  21746. void get_local_ip_and_port(std::string &ip, int &port) const override {
  21747. ip = "127.0.0.1";
  21748. port = 0;
  21749. }
  21750. socket_t socket() const override { return INVALID_SOCKET; }
  21751. time_t duration() const override { return 0; }
  21752. private:
  21753. std::string data_;
  21754. size_t pos_ = 0;
  21755. };
  21756. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  21757. // The payload uses the 16-bit extended length, so the header, the length
  21758. // and the mask key are all multi-byte fields here. Each used to be read
  21759. // with a single read() call, which fails as soon as one is split. The
  21760. // payload is also a little over one read chunk, so it is read in two.
  21761. std::string body;
  21762. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  21763. body += static_cast<char>(i % 251);
  21764. }
  21765. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  21766. std::string frame;
  21767. frame += static_cast<char>(0x81); // FIN + Text
  21768. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  21769. frame += static_cast<char>(body.size() >> 8);
  21770. frame += static_cast<char>(body.size() & 0xff);
  21771. for (size_t i = 0; i < 4; i++) {
  21772. frame += static_cast<char>(mask[i]);
  21773. }
  21774. for (size_t i = 0; i < body.size(); i++) {
  21775. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  21776. }
  21777. WsByteAtATimeStream strm(frame);
  21778. ws::Opcode opcode;
  21779. std::string payload;
  21780. bool fin = false;
  21781. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  21782. /*expect_masked=*/true, body.size()),
  21783. ws::impl::FrameRead::Ok);
  21784. EXPECT_TRUE(fin);
  21785. EXPECT_EQ(opcode, ws::Opcode::Text);
  21786. EXPECT_EQ(payload, body);
  21787. }
  21788. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  21789. std::string body(2000, 'x');
  21790. std::string frame;
  21791. frame += static_cast<char>(0x82); // FIN + Binary
  21792. frame += static_cast<char>(126); // 16-bit length follows
  21793. frame += static_cast<char>(body.size() >> 8);
  21794. frame += static_cast<char>(body.size() & 0xff);
  21795. frame += body;
  21796. detail::BufferStream strm;
  21797. strm.write(frame.data(), frame.size());
  21798. ws::Opcode opcode;
  21799. std::string payload;
  21800. bool fin;
  21801. EXPECT_EQ(
  21802. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  21803. ws::impl::FrameRead::Ok);
  21804. EXPECT_EQ(body, payload);
  21805. }
  21806. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  21807. // The header announces the largest payload allowed, and only 3 bytes of it
  21808. // ever arrive.
  21809. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  21810. std::string frame;
  21811. frame += static_cast<char>(0x82); // FIN + Binary
  21812. frame += static_cast<char>(127); // 64-bit length follows
  21813. for (int shift = 56; shift >= 0; shift -= 8) {
  21814. frame += static_cast<char>((len >> shift) & 0xff);
  21815. }
  21816. frame += "abc";
  21817. detail::BufferStream strm;
  21818. strm.write(frame.data(), frame.size());
  21819. ws::Opcode opcode;
  21820. std::string payload;
  21821. bool fin;
  21822. EXPECT_EQ(
  21823. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  21824. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  21825. ws::impl::FrameRead::Fail);
  21826. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  21827. }
  21828. TEST(WebSocketTest, QueryStringInHandshake) {
  21829. Server svr;
  21830. std::mutex mtx;
  21831. std::string received_target;
  21832. std::string received_token;
  21833. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21834. {
  21835. std::lock_guard<std::mutex> lock(mtx);
  21836. received_target = req.target;
  21837. if (req.has_param("token")) {
  21838. received_token = req.get_param_value("token");
  21839. }
  21840. }
  21841. std::string msg;
  21842. while (ws.read(msg)) {
  21843. ws.send(msg);
  21844. }
  21845. });
  21846. auto port = svr.bind_to_any_port("localhost");
  21847. std::thread t([&]() { svr.listen_after_bind(); });
  21848. svr.wait_until_ready();
  21849. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  21850. "/ws?token=ABC&session=123");
  21851. ASSERT_TRUE(client.connect());
  21852. // Round-trip ensures the handler has run and captured the request.
  21853. ASSERT_TRUE(client.send("hello"));
  21854. std::string msg;
  21855. ASSERT_TRUE(client.read(msg));
  21856. EXPECT_EQ("hello", msg);
  21857. client.close();
  21858. {
  21859. std::lock_guard<std::mutex> lock(mtx);
  21860. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  21861. EXPECT_EQ("ABC", received_token);
  21862. }
  21863. svr.stop();
  21864. t.join();
  21865. }
  21866. // Run a handshake against a throwaway server and hand the request the server
  21867. // received back to the caller, so tests can assert on the headers the client
  21868. // actually put on the wire.
  21869. static void capture_websocket_handshake_request(
  21870. const Headers &client_headers,
  21871. std::function<void(const Request &, int port)> verify) {
  21872. Server svr;
  21873. std::mutex mtx;
  21874. Request received;
  21875. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  21876. {
  21877. std::lock_guard<std::mutex> lock(mtx);
  21878. received = req;
  21879. }
  21880. std::string msg;
  21881. while (ws.read(msg)) {
  21882. ws.send(msg);
  21883. }
  21884. });
  21885. auto port = svr.bind_to_any_port("localhost");
  21886. std::thread t([&]() { svr.listen_after_bind(); });
  21887. auto se = detail::scope_exit([&] {
  21888. svr.stop();
  21889. t.join();
  21890. });
  21891. svr.wait_until_ready();
  21892. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  21893. client_headers);
  21894. ASSERT_TRUE(client.connect());
  21895. ASSERT_TRUE(client.send("hello"));
  21896. std::string msg;
  21897. ASSERT_TRUE(client.read(msg));
  21898. client.close();
  21899. {
  21900. std::lock_guard<std::mutex> lock(mtx);
  21901. verify(received, port);
  21902. }
  21903. }
  21904. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  21905. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  21906. // Non-default port must be present in the Host header. Default ports
  21907. // (80/443) are omitted; that logic is covered by
  21908. // MakeHostAndPortStringTest.
  21909. EXPECT_EQ("localhost:" + std::to_string(port),
  21910. req.get_header_value("Host"));
  21911. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  21912. req.get_header_value("User-Agent"));
  21913. EXPECT_FALSE(req.has_header("Accept"));
  21914. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  21915. EXPECT_FALSE(req.has_header("Content-Length"));
  21916. });
  21917. }
  21918. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  21919. capture_websocket_handshake_request(
  21920. {{"Host", "example.com"},
  21921. {"User-Agent", "custom-agent"},
  21922. {"X-Custom", "value"}},
  21923. [](const Request &req, int) {
  21924. EXPECT_EQ("example.com", req.get_header_value("Host"));
  21925. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  21926. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  21927. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  21928. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  21929. });
  21930. }
  21931. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  21932. capture_websocket_handshake_request(
  21933. {{"Upgrade", "bogus"},
  21934. {"Connection", "close"},
  21935. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  21936. {"Sec-WebSocket-Version", "8"}},
  21937. [](const Request &req, int) {
  21938. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  21939. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  21940. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  21941. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  21942. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  21943. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  21944. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  21945. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  21946. req.get_header_value("Sec-WebSocket-Key"));
  21947. });
  21948. }
  21949. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  21950. // A header the client refuses to send must abort the handshake before any
  21951. // part of it reaches the wire; a lone request line would otherwise sit in
  21952. // the peer's buffer as a truncated request.
  21953. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21954. ASSERT_NE(INVALID_SOCKET, srv);
  21955. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  21956. sockaddr_in addr{};
  21957. addr.sin_family = AF_INET;
  21958. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  21959. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21960. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  21961. ASSERT_EQ(0, ::listen(srv, 1));
  21962. sockaddr_in bound{};
  21963. socklen_t bound_len = sizeof(bound);
  21964. ASSERT_EQ(
  21965. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  21966. auto port = ntohs(bound.sin_port);
  21967. ssize_t received = -1;
  21968. std::thread t([&] {
  21969. // Bound every blocking call so a regression fails the test with a bad
  21970. // value instead of hanging the suite.
  21971. fd_set rfds;
  21972. FD_ZERO(&rfds);
  21973. FD_SET(srv, &rfds);
  21974. timeval tv{5, 0};
  21975. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  21976. 0) {
  21977. return;
  21978. }
  21979. sockaddr_in cli_addr{};
  21980. socklen_t cli_len = sizeof(cli_addr);
  21981. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21982. if (cli == INVALID_SOCKET) { return; }
  21983. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  21984. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21985. char buf[4096];
  21986. received = ::recv(cli, buf, sizeof(buf), 0);
  21987. });
  21988. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  21989. // connect() has already shut the socket down by the time it returns false,
  21990. // so the peer sees EOF without waiting for the client to be destroyed.
  21991. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  21992. {{"X-Bad", "a\r\nInjected: 1"}});
  21993. EXPECT_FALSE(client.connect());
  21994. t.join();
  21995. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  21996. EXPECT_EQ(0, received);
  21997. }
  21998. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  21999. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  22000. // contains "upgrade" as a substring is a different token and must not
  22001. // start a WebSocket handshake.
  22002. auto make_request = [](const std::vector<std::string> &connection_values) {
  22003. Request req;
  22004. req.method = "GET";
  22005. req.headers.emplace("Upgrade", "websocket");
  22006. for (const auto &value : connection_values) {
  22007. req.headers.emplace("Connection", value);
  22008. }
  22009. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22010. req.headers.emplace("Sec-WebSocket-Version", "13");
  22011. return req;
  22012. };
  22013. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  22014. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  22015. EXPECT_TRUE(
  22016. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  22017. EXPECT_TRUE(
  22018. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  22019. EXPECT_TRUE(
  22020. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  22021. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  22022. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  22023. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  22024. EXPECT_FALSE(
  22025. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  22026. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  22027. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22028. }
  22029. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  22030. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  22031. // asks recipients to match each protocol-name case-insensitively, and RFC
  22032. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  22033. // client naming websocket alongside another protocol, or on a second field
  22034. // line, is offering websocket; a value that merely contains "websocket" as a
  22035. // substring is a different protocol name and is not.
  22036. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  22037. Request req;
  22038. req.method = "GET";
  22039. for (const auto &value : upgrade_values) {
  22040. req.headers.emplace("Upgrade", value);
  22041. }
  22042. req.headers.emplace("Connection", "Upgrade");
  22043. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  22044. req.headers.emplace("Sec-WebSocket-Version", "13");
  22045. return req;
  22046. };
  22047. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  22048. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  22049. EXPECT_TRUE(
  22050. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  22051. EXPECT_TRUE(
  22052. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  22053. EXPECT_TRUE(
  22054. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  22055. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  22056. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  22057. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  22058. EXPECT_FALSE(
  22059. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  22060. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  22061. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  22062. }
  22063. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  22064. Server svr;
  22065. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  22066. auto port = svr.bind_to_any_port("localhost");
  22067. std::thread t([&]() { svr.listen_after_bind(); });
  22068. auto se = detail::scope_exit([&] {
  22069. svr.stop();
  22070. t.join();
  22071. });
  22072. svr.wait_until_ready();
  22073. Headers headers = {{"Upgrade", "websocket"},
  22074. {"Connection", "notupgrade"},
  22075. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  22076. {"Sec-WebSocket-Version", "13"}};
  22077. Client cli("localhost", port);
  22078. auto res = cli.Get("/ws", headers);
  22079. // The route exists only as a WebSocket route, so a request that fails the
  22080. // handshake check falls through to ordinary routing.
  22081. ASSERT_TRUE(res);
  22082. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  22083. }
  22084. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  22085. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  22086. // Connection value is the only thing left for the client to reject.
  22087. Server svr;
  22088. svr.Get("/ws", [](const Request &req, Response &res) {
  22089. res.status = StatusCode::SwitchingProtocol_101;
  22090. res.set_header("Upgrade", "websocket");
  22091. res.set_header("Connection", "notupgrade");
  22092. res.set_header("Sec-WebSocket-Accept",
  22093. detail::websocket_accept_key(
  22094. req.get_header_value("Sec-WebSocket-Key")));
  22095. });
  22096. auto port = svr.bind_to_any_port("localhost");
  22097. std::thread t([&]() { svr.listen_after_bind(); });
  22098. auto se = detail::scope_exit([&] {
  22099. svr.stop();
  22100. t.join();
  22101. });
  22102. svr.wait_until_ready();
  22103. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22104. auto res = client.connect();
  22105. EXPECT_FALSE(res);
  22106. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22107. EXPECT_FALSE(client.is_open());
  22108. }
  22109. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  22110. Server svr;
  22111. svr.Get("/ws", [](const Request &req, Response &res) {
  22112. res.status = StatusCode::SwitchingProtocol_101;
  22113. res.set_header("Upgrade", "websocket");
  22114. res.set_header("Connection", "Upgrade");
  22115. res.set_header("Sec-WebSocket-Accept",
  22116. detail::websocket_accept_key(
  22117. req.get_header_value("Sec-WebSocket-Key")));
  22118. res.set_header("Sec-WebSocket-Protocol", "admin");
  22119. });
  22120. auto port = svr.bind_to_any_port("localhost");
  22121. std::thread t([&]() { svr.listen_after_bind(); });
  22122. auto se = detail::scope_exit([&] {
  22123. svr.stop();
  22124. t.join();
  22125. });
  22126. svr.wait_until_ready();
  22127. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  22128. // Server selects a subprotocol the client never offered
  22129. {
  22130. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  22131. ws::WebSocketClient client(url, headers);
  22132. auto res = client.connect();
  22133. EXPECT_FALSE(res);
  22134. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22135. EXPECT_FALSE(client.is_open());
  22136. EXPECT_TRUE(client.subprotocol().empty());
  22137. }
  22138. // Client offered none but the server named one anyway
  22139. {
  22140. ws::WebSocketClient client(url);
  22141. auto res = client.connect();
  22142. EXPECT_FALSE(res);
  22143. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  22144. EXPECT_FALSE(client.is_open());
  22145. EXPECT_TRUE(client.subprotocol().empty());
  22146. }
  22147. }
  22148. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  22149. // The socket path doubles as the URL host, so it must not contain '/'.
  22150. const char *shard = getenv("GTEST_SHARD_INDEX");
  22151. const std::string sock_path =
  22152. shard ? std::string("httplib-ws-") + shard + ".sock"
  22153. : std::string("httplib-ws.sock");
  22154. std::remove(sock_path.c_str());
  22155. Server svr;
  22156. std::mutex mtx;
  22157. std::string received_host;
  22158. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  22159. {
  22160. std::lock_guard<std::mutex> lock(mtx);
  22161. received_host = req.get_header_value("Host");
  22162. }
  22163. std::string msg;
  22164. while (ws.read(msg)) {
  22165. ws.send(msg);
  22166. }
  22167. });
  22168. svr.set_address_family(AF_UNIX);
  22169. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  22170. auto se = detail::scope_exit([&] {
  22171. svr.stop();
  22172. t.join();
  22173. std::remove(sock_path.c_str());
  22174. });
  22175. svr.wait_until_ready();
  22176. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  22177. client.set_address_family(AF_UNIX);
  22178. ASSERT_TRUE(client.connect());
  22179. ASSERT_TRUE(client.send("hello"));
  22180. std::string msg;
  22181. ASSERT_TRUE(client.read(msg));
  22182. client.close();
  22183. {
  22184. std::lock_guard<std::mutex> lock(mtx);
  22185. // There is no host:port for a Unix socket, so the same "localhost"
  22186. // placeholder the HTTP client uses is expected.
  22187. EXPECT_EQ("localhost", received_host);
  22188. }
  22189. }
  22190. // Two threads must never parse WebSocket frames from the same stream.
  22191. // close() used to read the peer's Close reply with its own frame read, so it
  22192. // raced a reader thread that was in the middle of a payload: the payload loop
  22193. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  22194. // so bytes taken by close() were replaced with bytes from further along the
  22195. // stream. The message kept its length and silently changed content.
  22196. //
  22197. // The raw peer below sends a frame header plus part of the payload, waits for
  22198. // the handler to call close(), and only then sends the rest. Whichever thread
  22199. // would win the race for those bytes, the message must arrive intact, because
  22200. // close() must not touch the stream while read() owns it.
  22201. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  22202. #ifndef _WIN32
  22203. signal(SIGPIPE, SIG_IGN);
  22204. #endif
  22205. const size_t payload_len = 120; // fits the 7-bit length field
  22206. const size_t prefix_len = 8;
  22207. const int attempts = 8;
  22208. std::string expected(payload_len, '\0');
  22209. for (size_t i = 0; i < payload_len; i++) {
  22210. expected[i] = static_cast<char>('a' + i % 26);
  22211. }
  22212. std::atomic<bool> peer_stalled{false};
  22213. std::atomic<bool> handler_done{false};
  22214. std::mutex received_mutex;
  22215. std::vector<std::string> received;
  22216. // Bound every wait, so a regression fails the test instead of hanging the
  22217. // suite.
  22218. auto wait_for = [](const std::atomic<bool> &flag) {
  22219. for (int i = 0; i < 500 && !flag; i++) {
  22220. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22221. }
  22222. };
  22223. Server svr;
  22224. svr.set_websocket_ping_interval(0);
  22225. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22226. std::thread reader([&]() {
  22227. std::string msg;
  22228. while (ws.read(msg)) {
  22229. std::lock_guard<std::mutex> guard(received_mutex);
  22230. received.push_back(msg);
  22231. }
  22232. });
  22233. // Wait until the peer stalls mid-payload, so the reader thread is parked
  22234. // inside read_websocket_frame() when close() runs.
  22235. wait_for(peer_stalled);
  22236. ws.close();
  22237. reader.join();
  22238. handler_done = true;
  22239. });
  22240. auto port = svr.bind_to_any_port("127.0.0.1");
  22241. std::thread t([&]() { svr.listen_after_bind(); });
  22242. auto se = detail::scope_exit([&] {
  22243. svr.stop();
  22244. t.join();
  22245. });
  22246. svr.wait_until_ready();
  22247. auto send_bytes = [](socket_t s, const std::string &data) {
  22248. #ifdef _WIN32
  22249. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  22250. #else
  22251. auto n = ::send(s, data.data(), data.size(), 0);
  22252. #endif
  22253. return n == static_cast<decltype(n)>(data.size());
  22254. };
  22255. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  22256. // Every length used here fits the 7-bit length field.
  22257. auto masked_header = [](uint8_t first_byte, size_t len) {
  22258. std::string h;
  22259. h += static_cast<char>(first_byte);
  22260. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  22261. h.append(4, '\0'); // mask key
  22262. return h;
  22263. };
  22264. for (int attempt = 0; attempt < attempts; attempt++) {
  22265. peer_stalled = false;
  22266. handler_done = false;
  22267. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22268. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  22269. auto se_sock = detail::scope_exit([&] {
  22270. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  22271. });
  22272. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22273. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  22274. sockaddr_in addr{};
  22275. addr.sin_family = AF_INET;
  22276. addr.sin_port = htons(static_cast<uint16_t>(port));
  22277. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22278. ASSERT_EQ(
  22279. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  22280. << "attempt " << attempt;
  22281. ASSERT_TRUE(send_bytes(sock,
  22282. "GET /ws HTTP/1.1\r\n"
  22283. "Host: 127.0.0.1\r\n"
  22284. "Upgrade: websocket\r\n"
  22285. "Connection: Upgrade\r\n"
  22286. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22287. "Sec-WebSocket-Version: 13\r\n"
  22288. "\r\n"))
  22289. << "attempt " << attempt;
  22290. std::string response;
  22291. while (response.find("\r\n\r\n") == std::string::npos) {
  22292. char buf[512];
  22293. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  22294. if (n <= 0) { break; }
  22295. response.append(buf, static_cast<size_t>(n));
  22296. }
  22297. ASSERT_NE(std::string::npos, response.find(" 101 "))
  22298. << "attempt " << attempt;
  22299. // Send the header of a Binary message but only the first prefix_len bytes
  22300. // of its payload, leaving the reader thread stalled inside the payload.
  22301. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  22302. expected.substr(0, prefix_len)))
  22303. << "attempt " << attempt;
  22304. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22305. peer_stalled = true;
  22306. // Let close() send its Close frame and park in its own read before the
  22307. // rest of the payload arrives, so both threads are waiting for it.
  22308. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22309. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  22310. close_frame += static_cast<char>(0x03); // status 1000
  22311. close_frame += static_cast<char>(0xE8);
  22312. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  22313. << "attempt " << attempt;
  22314. // Closing the peer releases the reader thread even on the buggy path,
  22315. // where it waits for bytes another thread already consumed.
  22316. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22317. detail::close_socket(sock);
  22318. sock = INVALID_SOCKET;
  22319. wait_for(handler_done);
  22320. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  22321. }
  22322. std::lock_guard<std::mutex> guard(received_mutex);
  22323. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  22324. << "a message in flight when close() ran was dropped";
  22325. for (size_t i = 0; i < received.size(); i++) {
  22326. EXPECT_EQ(expected, received[i]) << "message " << i;
  22327. }
  22328. }
  22329. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  22330. std::atomic<bool> done{false};
  22331. std::string received;
  22332. Server svr;
  22333. svr.set_websocket_ping_interval(0);
  22334. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  22335. std::string msg;
  22336. if (ws.read(msg) == ws::Binary) { received = msg; }
  22337. done = true;
  22338. });
  22339. auto port = svr.bind_to_any_port("127.0.0.1");
  22340. std::thread t([&]() { svr.listen_after_bind(); });
  22341. auto se = detail::scope_exit([&] {
  22342. svr.stop();
  22343. t.join();
  22344. });
  22345. svr.wait_until_ready();
  22346. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  22347. ASSERT_NE(INVALID_SOCKET, sock);
  22348. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  22349. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  22350. sockaddr_in addr{};
  22351. addr.sin_family = AF_INET;
  22352. addr.sin_port = htons(static_cast<uint16_t>(port));
  22353. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  22354. ASSERT_EQ(0,
  22355. ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  22356. // Frames with an all-zero mask key, so the payload goes out verbatim.
  22357. auto frame = [](uint8_t first_byte, const std::string &payload) {
  22358. std::string f;
  22359. f += static_cast<char>(first_byte);
  22360. f += static_cast<char>(0x80 | payload.size());
  22361. f.append(4, '\0');
  22362. return f + payload;
  22363. };
  22364. std::string data = "GET /ws HTTP/1.1\r\n"
  22365. "Host: 127.0.0.1\r\n"
  22366. "Upgrade: websocket\r\n"
  22367. "Connection: Upgrade\r\n"
  22368. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  22369. "Sec-WebSocket-Version: 13\r\n"
  22370. "\r\n";
  22371. data += frame(0x02, "Hel"); // Binary, more to come
  22372. data += frame(0x89, "p"); // FIN + Ping
  22373. data += frame(0x80, "lo"); // FIN + Continuation
  22374. #ifdef _WIN32
  22375. ::send(sock, data.data(), static_cast<int>(data.size()), 0);
  22376. #else
  22377. ::send(sock, data.data(), data.size(), 0);
  22378. #endif
  22379. for (int i = 0; i < 500 && !done; i++) {
  22380. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22381. }
  22382. ASSERT_TRUE(done);
  22383. EXPECT_EQ("Hello", received);
  22384. }
  22385. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22386. class WebSocketSSLIntegrationTest : public ::testing::Test {
  22387. protected:
  22388. void SetUp() override {
  22389. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  22390. SERVER_PRIVATE_KEY_FILE);
  22391. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22392. std::string msg;
  22393. ws::ReadResult ret;
  22394. while ((ret = ws.read(msg))) {
  22395. if (ret == ws::Binary) {
  22396. ws.send(msg.data(), msg.size());
  22397. } else {
  22398. ws.send(msg);
  22399. }
  22400. }
  22401. });
  22402. port_ = server_->bind_to_any_port(HOST);
  22403. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22404. server_->wait_until_ready();
  22405. }
  22406. void TearDown() override {
  22407. server_->stop();
  22408. if (server_thread_.joinable()) { server_thread_.join(); }
  22409. }
  22410. std::unique_ptr<SSLServer> server_;
  22411. std::thread server_thread_;
  22412. int port_ = 0;
  22413. };
  22414. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  22415. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22416. "/ws-echo");
  22417. client.enable_server_certificate_verification(false);
  22418. ASSERT_TRUE(client.connect());
  22419. ASSERT_TRUE(client.is_open());
  22420. ASSERT_TRUE(client.send("Hello WSS"));
  22421. std::string msg;
  22422. EXPECT_EQ(ws::Text, client.read(msg));
  22423. EXPECT_EQ("Hello WSS", msg);
  22424. client.close();
  22425. }
  22426. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  22427. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  22428. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  22429. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  22430. // client (without calling close() first) is the only path that runs
  22431. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  22432. // bug exactly.
  22433. //
  22434. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  22435. // when linked against an instrumented libssl; run under Valgrind to catch it
  22436. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  22437. // suite (the freed session otherwise stalls on the close handshake) — this test
  22438. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  22439. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  22440. {
  22441. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22442. "/ws-echo");
  22443. client.enable_server_certificate_verification(false);
  22444. client.set_read_timeout(2, 0);
  22445. client.set_write_timeout(2, 0);
  22446. ASSERT_TRUE(client.connect());
  22447. ASSERT_TRUE(client.is_open());
  22448. ASSERT_TRUE(client.send("still open"));
  22449. // Intentionally do NOT call client.close(): leaving scope runs
  22450. // shutdown_and_close() with the WebSocket still open, which must send the
  22451. // close frame while the TLS session is still alive.
  22452. }
  22453. }
  22454. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  22455. // shutdown_and_close() at the start of connect(), reproducing the same
  22456. // use-after-free within the test body rather than at scope exit. The second
  22457. // connect must succeed and echo, proving the close handshake ran over a live
  22458. // session. See the note above about memory-tool requirements.
  22459. TEST_F(WebSocketSSLIntegrationTest,
  22460. ReconnectWhileOpenSendsCloseOverLiveSession) {
  22461. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  22462. "/ws-echo");
  22463. client.enable_server_certificate_verification(false);
  22464. client.set_read_timeout(2, 0);
  22465. client.set_write_timeout(2, 0);
  22466. ASSERT_TRUE(client.connect());
  22467. ASSERT_TRUE(client.is_open());
  22468. ASSERT_TRUE(client.send("still open"));
  22469. // Reconnect without closing first: connect() calls shutdown_and_close() on
  22470. // the still-open connection, which must not touch a freed TLS session.
  22471. ASSERT_TRUE(client.connect());
  22472. ASSERT_TRUE(client.is_open());
  22473. ASSERT_TRUE(client.send("after reconnect"));
  22474. std::string msg;
  22475. EXPECT_EQ(ws::Text, client.read(msg));
  22476. EXPECT_EQ("after reconnect", msg);
  22477. client.close();
  22478. }
  22479. #endif
  22480. #ifdef CPPHTTPLIB_SSL_ENABLED
  22481. class WebSocketSSLCATest : public ::testing::Test {
  22482. protected:
  22483. void SetUp() override {
  22484. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  22485. SERVER_PRIVATE_KEY_FILE);
  22486. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22487. std::string msg;
  22488. while (ws.read(msg)) {
  22489. ws.send(msg);
  22490. }
  22491. });
  22492. port_ = server_->bind_to_any_port("127.0.0.1");
  22493. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22494. server_->wait_until_ready();
  22495. }
  22496. void TearDown() override {
  22497. server_->stop();
  22498. if (server_thread_.joinable()) { server_thread_.join(); }
  22499. }
  22500. std::string url() const {
  22501. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  22502. }
  22503. std::unique_ptr<SSLServer> server_;
  22504. std::thread server_thread_;
  22505. int port_ = 0;
  22506. };
  22507. // A custom CA loaded as PEM verifies the server with full certificate
  22508. // verification enabled
  22509. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  22510. ws::WebSocketClient client(url());
  22511. std::string cert;
  22512. read_file(SERVER_CERT2_FILE, cert);
  22513. client.load_ca_cert_store(cert.c_str(), cert.size());
  22514. ASSERT_TRUE(client.connect());
  22515. ASSERT_TRUE(client.send("hello"));
  22516. std::string msg;
  22517. EXPECT_EQ(ws::Text, client.read(msg));
  22518. EXPECT_EQ("hello", msg);
  22519. client.close();
  22520. }
  22521. // A custom CA that does not cover the server must fail verification (the
  22522. // custom CA is exclusive; system certs are not loaded alongside it)
  22523. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  22524. ws::WebSocketClient client(url());
  22525. std::string cert;
  22526. read_file(CLIENT_CA_CERT_FILE, cert);
  22527. client.load_ca_cert_store(cert.c_str(), cert.size());
  22528. auto res = client.connect();
  22529. ASSERT_FALSE(res);
  22530. EXPECT_EQ(Error::SSLServerVerification, res.error());
  22531. EXPECT_EQ(-1, res.status());
  22532. EXPECT_NE(0u, res.ssl_backend_error());
  22533. }
  22534. // The same CA as a file path rather than PEM in memory
  22535. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  22536. ws::WebSocketClient client(url());
  22537. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22538. ASSERT_TRUE(client.connect());
  22539. ASSERT_TRUE(client.send("hello"));
  22540. std::string msg;
  22541. EXPECT_EQ(ws::Text, client.read(msg));
  22542. EXPECT_EQ("hello", msg);
  22543. client.close();
  22544. }
  22545. // ...and a CA file that does not cover the server still fails, so it is the
  22546. // path above that decides the outcome
  22547. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  22548. ws::WebSocketClient client(url());
  22549. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22550. ASSERT_FALSE(client.connect());
  22551. }
  22552. // Regression test: reconnecting with a native custom CA store used to reuse
  22553. // a store handle the previous TLS context had already freed (use-after-free
  22554. // under the OpenSSL backend). The context now lives as long as the client.
  22555. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  22556. ws::WebSocketClient client(url());
  22557. std::string cert;
  22558. read_file(SERVER_CERT2_FILE, cert);
  22559. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  22560. ASSERT_TRUE(client.connect());
  22561. client.close();
  22562. ASSERT_TRUE(client.connect());
  22563. ASSERT_TRUE(client.send("again"));
  22564. std::string msg;
  22565. EXPECT_EQ(ws::Text, client.read(msg));
  22566. EXPECT_EQ("again", msg);
  22567. client.close();
  22568. }
  22569. // Regression test: a certificate with a trusted chain but no identity match
  22570. // for the server IP must be rejected. The Mbed TLS backend used to skip
  22571. // verification entirely for IP hosts, so this connection succeeded there.
  22572. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  22573. // chain verification while the identity check must still fail.
  22574. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  22575. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22576. ASSERT_TRUE(svr.is_valid());
  22577. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22578. std::string msg;
  22579. while (ws.read(msg)) {
  22580. ws.send(msg);
  22581. }
  22582. });
  22583. auto port = svr.bind_to_any_port("127.0.0.1");
  22584. auto t = std::thread([&]() { svr.listen_after_bind(); });
  22585. auto se = detail::scope_exit([&] {
  22586. svr.stop();
  22587. t.join();
  22588. });
  22589. svr.wait_until_ready();
  22590. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  22591. "/echo");
  22592. std::string cert;
  22593. read_file(SERVER_CERT_FILE, cert);
  22594. client.load_ca_cert_store(cert.c_str(), cert.size());
  22595. ASSERT_FALSE(client.connect());
  22596. }
  22597. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  22598. // SNI, so nothing binds the host name to the TLS session. These bind the
  22599. // server to "localhost" instead, the only shape that exercises the SNI and
  22600. // hostname-verification path with certificate verification left enabled.
  22601. class WebSocketSSLDnsHostTest : public ::testing::Test {
  22602. protected:
  22603. void Start(const char *cert_file) {
  22604. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  22605. SERVER_PRIVATE_KEY_FILE);
  22606. ASSERT_TRUE(server_->is_valid());
  22607. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  22608. std::string msg;
  22609. while (ws.read(msg)) {
  22610. ws.send(msg);
  22611. }
  22612. });
  22613. port_ = server_->bind_to_any_port("localhost");
  22614. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22615. server_->wait_until_ready();
  22616. }
  22617. void TearDown() override {
  22618. if (server_) { server_->stop(); }
  22619. if (server_thread_.joinable()) { server_thread_.join(); }
  22620. }
  22621. std::string url() const {
  22622. return "wss://localhost:" + std::to_string(port_) + "/echo";
  22623. }
  22624. std::unique_ptr<SSLServer> server_;
  22625. std::thread server_thread_;
  22626. int port_ = 0;
  22627. };
  22628. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  22629. // out and the connection is usable
  22630. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  22631. Start(SERVER_CERT2_FILE);
  22632. ws::WebSocketClient client(url());
  22633. client.set_ca_cert_path(SERVER_CERT2_FILE);
  22634. ASSERT_TRUE(client.connect());
  22635. ASSERT_TRUE(client.send("hello"));
  22636. std::string msg;
  22637. EXPECT_EQ(ws::Text, client.read(msg));
  22638. EXPECT_EQ("hello", msg);
  22639. client.close();
  22640. }
  22641. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  22642. // while the identity check must still reject "localhost"
  22643. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  22644. Start(SERVER_CERT_FILE);
  22645. ws::WebSocketClient client(url());
  22646. client.set_ca_cert_path(SERVER_CERT_FILE);
  22647. auto res = client.connect();
  22648. ASSERT_FALSE(res);
  22649. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  22650. EXPECT_EQ(-1, res.status());
  22651. }
  22652. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  22653. // disabled: the chain is still checked, only the identity check is skipped
  22654. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  22655. Start(SERVER_CERT_FILE);
  22656. ws::WebSocketClient client(url());
  22657. client.set_ca_cert_path(SERVER_CERT_FILE);
  22658. client.enable_server_hostname_verification(false);
  22659. ASSERT_TRUE(client.connect());
  22660. ASSERT_TRUE(client.send("hello"));
  22661. std::string msg;
  22662. EXPECT_EQ(ws::Text, client.read(msg));
  22663. EXPECT_EQ("hello", msg);
  22664. client.close();
  22665. }
  22666. // A CA that did not sign the server certificate fails the chain, even though
  22667. // the name would match
  22668. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  22669. Start(SERVER_CERT2_FILE);
  22670. ws::WebSocketClient client(url());
  22671. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  22672. ASSERT_FALSE(client.connect());
  22673. }
  22674. // With verification disabled, neither the chain nor the name is checked
  22675. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  22676. Start(SERVER_CERT_FILE);
  22677. ws::WebSocketClient client(url());
  22678. client.enable_server_certificate_verification(false);
  22679. ASSERT_TRUE(client.connect());
  22680. ASSERT_TRUE(client.send("hello"));
  22681. std::string msg;
  22682. EXPECT_EQ(ws::Text, client.read(msg));
  22683. EXPECT_EQ("hello", msg);
  22684. client.close();
  22685. }
  22686. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  22687. protected:
  22688. void SetUp() override {
  22689. server_ = httplib::detail::make_unique<SSLServer>(
  22690. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22691. ASSERT_TRUE(server_->is_valid());
  22692. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  22693. std::string msg;
  22694. while (ws.read(msg)) {
  22695. ws.send(msg);
  22696. }
  22697. });
  22698. port_ = server_->bind_to_any_port("localhost");
  22699. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  22700. server_->wait_until_ready();
  22701. }
  22702. void TearDown() override {
  22703. server_->stop();
  22704. if (server_thread_.joinable()) { server_thread_.join(); }
  22705. }
  22706. std::string url() const {
  22707. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  22708. }
  22709. void ConnectWithClientCert(const std::string &client_cert_file,
  22710. const std::string &client_private_key_file,
  22711. const char *private_key_password) {
  22712. std::string cert_pem, key_pem;
  22713. read_file(client_cert_file, cert_pem);
  22714. read_file(client_private_key_file, key_pem);
  22715. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  22716. key_pem.c_str(), key_pem.size(),
  22717. private_key_password};
  22718. ws::WebSocketClient client(url(), pem);
  22719. ASSERT_TRUE(client.is_valid());
  22720. client.enable_server_certificate_verification(false);
  22721. ASSERT_TRUE(client.connect());
  22722. ASSERT_TRUE(client.send("hello"));
  22723. std::string msg;
  22724. EXPECT_EQ(ws::Text, client.read(msg));
  22725. EXPECT_EQ("hello", msg);
  22726. client.close();
  22727. }
  22728. std::unique_ptr<SSLServer> server_;
  22729. std::thread server_thread_;
  22730. int port_ = 0;
  22731. };
  22732. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  22733. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  22734. }
  22735. // Control for the tests above: the fixture's server really does require a
  22736. // client certificate, so it is the PEM the constructor installed that decides
  22737. // the outcome.
  22738. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  22739. ws::WebSocketClient client(url());
  22740. ASSERT_TRUE(client.is_valid());
  22741. client.enable_server_certificate_verification(false);
  22742. EXPECT_FALSE(client.connect());
  22743. }
  22744. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  22745. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  22746. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  22747. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  22748. }
  22749. #endif
  22750. #if !defined(_WIN32)
  22751. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  22752. auto secret_dir = std::string("./symlink_test_secret");
  22753. auto served_dir = std::string("./symlink_test_served");
  22754. auto secret_file = secret_dir + "/secret.txt";
  22755. auto symlink_path = served_dir + "/escape";
  22756. // Setup: create directories and files
  22757. mkdir(secret_dir.c_str(), 0755);
  22758. mkdir(served_dir.c_str(), 0755);
  22759. {
  22760. std::ofstream ofs(secret_file);
  22761. ofs << "SECRET_DATA";
  22762. }
  22763. // Create symlink using absolute path so it resolves correctly
  22764. #ifdef PATH_MAX
  22765. char abs_secret[PATH_MAX];
  22766. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  22767. #else
  22768. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  22769. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  22770. ASSERT_NE(nullptr, abs_secret);
  22771. #endif
  22772. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  22773. auto se = detail::scope_exit([&] {
  22774. unlink(symlink_path.c_str());
  22775. unlink(secret_file.c_str());
  22776. rmdir(served_dir.c_str());
  22777. rmdir(secret_dir.c_str());
  22778. });
  22779. Server svr;
  22780. svr.set_mount_point("/", served_dir);
  22781. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  22782. auto se2 = detail::scope_exit([&] {
  22783. svr.stop();
  22784. listen_thread.join();
  22785. });
  22786. svr.wait_until_ready();
  22787. Client cli("localhost", PORT);
  22788. // Symlink pointing outside base dir should be blocked
  22789. auto res = cli.Get("/escape/secret.txt");
  22790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22791. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  22792. }
  22793. #endif
  22794. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  22795. // "GET /smuggled" request), reads the first response, and only then sends the
  22796. // embedded request as the body. Returns how many times /smuggled ran.
  22797. //
  22798. // The body is sent AFTER receiving the first response (as in the original
  22799. // PoC) so that the stream_line_reader cannot buffer it together with the
  22800. // headers of the first request.
  22801. static int count_smuggled_requests(const std::string &outer_head,
  22802. std::string &first_response) {
  22803. Server svr;
  22804. svr.set_mount_point("/", "./www");
  22805. std::atomic<int> smuggled_count(0);
  22806. svr.Get("/smuggled", [&](const Request &, Response &res) {
  22807. smuggled_count++;
  22808. res.set_content("oops", "text/plain");
  22809. });
  22810. svr.Post("/post", [&](const Request &req, Response &res) {
  22811. res.set_content(req.body, "text/plain");
  22812. });
  22813. auto port = svr.bind_to_any_port("localhost");
  22814. thread t = thread([&] { svr.listen_after_bind(); });
  22815. auto se = detail::scope_exit([&] {
  22816. svr.stop();
  22817. t.join();
  22818. });
  22819. svr.wait_until_ready();
  22820. auto error = Error::Success;
  22821. auto sock = detail::create_client_socket(
  22822. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  22823. /*connection_timeout_sec=*/2, 0,
  22824. /*read_timeout_sec=*/2, 0,
  22825. /*write_timeout_sec=*/2, 0, std::string(), error);
  22826. EXPECT_NE(INVALID_SOCKET, sock);
  22827. if (sock == INVALID_SOCKET) { return -1; }
  22828. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  22829. // The "smuggled" request will be sent as the body of the outer request
  22830. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  22831. "Host: localhost\r\n"
  22832. "Connection: close\r\n"
  22833. "\r\n";
  22834. auto head = outer_head;
  22835. auto len = std::to_string(smuggled.size());
  22836. for (auto pos = head.find("{len}"); pos != std::string::npos;
  22837. pos = head.find("{len}", pos + len.size())) {
  22838. head.replace(pos, 5, len);
  22839. }
  22840. // Step 1: Send only the outer request headers (no body yet)
  22841. auto sent = send(sock, head.data(), head.size(), 0);
  22842. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  22843. // Step 2: Read the first response
  22844. char buf[4096];
  22845. for (;;) {
  22846. auto n = recv(sock, buf, sizeof(buf), 0);
  22847. if (n <= 0) break;
  22848. first_response.append(buf, static_cast<size_t>(n));
  22849. // Stop once we have a complete response (headers + body)
  22850. auto hdr_end = first_response.find("\r\n\r\n");
  22851. if (hdr_end != std::string::npos) {
  22852. // Check for Content-Length to know when the body is complete
  22853. auto cl_pos = first_response.find("Content-Length:");
  22854. if (cl_pos != std::string::npos) {
  22855. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  22856. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  22857. auto cl = std::stoul(
  22858. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  22859. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  22860. } else {
  22861. break; // No Content-Length, assume headers-only response
  22862. }
  22863. }
  22864. }
  22865. // Step 3: Now send the body, which looks like a new HTTP request. On a
  22866. // vulnerable server the keep-alive loop reads this as a second request. The
  22867. // server may already have closed the connection, so the result is ignored.
  22868. send(sock, smuggled.data(), smuggled.size(), 0);
  22869. // Half-close so that a server which drained the body sees EOF and closes,
  22870. // instead of the read below waiting for the read timeout.
  22871. #ifdef _WIN32
  22872. ::shutdown(sock, SD_SEND);
  22873. #else
  22874. ::shutdown(sock, SHUT_WR);
  22875. #endif
  22876. // Step 4: Read until the server closes the connection
  22877. for (;;) {
  22878. auto n = recv(sock, buf, sizeof(buf), 0);
  22879. if (n <= 0) break;
  22880. }
  22881. return smuggled_count.load();
  22882. }
  22883. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  22884. // A GET request with Content-Length to a static file handler must have its
  22885. // body drained before the keep-alive connection is reused. Otherwise the
  22886. // unread body bytes are interpreted as the next HTTP request.
  22887. std::string first_response;
  22888. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22889. "Host: localhost\r\n"
  22890. "Content-Length: {len}\r\n"
  22891. "\r\n",
  22892. first_response));
  22893. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  22894. }
  22895. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  22896. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  22897. // be answered with 400 and the connection closed. Treating it as "no body"
  22898. // leaves the body to be parsed as the next request.
  22899. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  22900. const char *targets[] = {
  22901. "GET /file", // handler that never reads the body
  22902. "GET /not-found", // no handler matches (404)
  22903. "POST /post", // handler that reads the body
  22904. };
  22905. for (auto target : targets) {
  22906. for (auto value : values) {
  22907. std::string first_response;
  22908. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  22909. " HTTP/1.1\r\n"
  22910. "Host: localhost\r\n"
  22911. "Content-Length: " +
  22912. value + "\r\n\r\n",
  22913. first_response))
  22914. << target << " with Content-Length: " << value;
  22915. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  22916. << target << " with Content-Length: " << value;
  22917. }
  22918. }
  22919. }
  22920. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  22921. // A 400 for an unparseable request line leaves the rest of the message
  22922. // unread, so the connection must be closed rather than reused.
  22923. std::string first_response;
  22924. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  22925. "Host: localhost\r\n"
  22926. "Content-Length: {len}\r\n"
  22927. "\r\n",
  22928. first_response));
  22929. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22930. }
  22931. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  22932. // Same as above for a header block that fails to parse.
  22933. std::string first_response;
  22934. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  22935. "Host: localhost\r\n"
  22936. "Bad Header\r\n"
  22937. "Content-Length: {len}\r\n"
  22938. "\r\n",
  22939. first_response));
  22940. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  22941. }
  22942. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  22943. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  22944. // server must not read another request on that connection, even when the
  22945. // request had no body to drain.
  22946. std::string first_response;
  22947. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  22948. "Host: localhost\r\n"
  22949. "\r\n",
  22950. first_response));
  22951. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  22952. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  22953. }
  22954. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  22955. // A content reader that stops early leaves the stream inside the body.
  22956. // Draining the whole Content-Length from there, or reading the body again,
  22957. // reads into the next request, and whatever follows is parsed as a request
  22958. // of its own.
  22959. Server svr;
  22960. std::atomic<int> smuggled_count(0);
  22961. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  22962. svr.Post("/upload", [](const Request &req, Response &res,
  22963. const ContentReader &content_reader) {
  22964. // Stop at the last chunk, so the whole body has been read however it
  22965. // arrives.
  22966. auto length = req.get_header_value_u64("Content-Length");
  22967. size_t total = 0;
  22968. auto consumed = content_reader([&](const char *, size_t n) {
  22969. total += n;
  22970. return total < length;
  22971. });
  22972. EXPECT_FALSE(consumed);
  22973. if (req.has_param("retry")) {
  22974. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  22975. }
  22976. // Replace the 400 the aborted read set, which would close the connection.
  22977. res.set_redirect("/done");
  22978. });
  22979. auto port = svr.bind_to_any_port(HOST);
  22980. thread t = thread([&] { svr.listen_after_bind(); });
  22981. auto se = detail::scope_exit([&] {
  22982. svr.stop();
  22983. t.join();
  22984. });
  22985. svr.wait_until_ready();
  22986. // A front end sees the second request as a POST whose body is the GET. The
  22987. // first body is as long as the POST's headers, so draining it again reads
  22988. // exactly those and leaves the GET to be parsed next.
  22989. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  22990. "Host: localhost\r\n"
  22991. "\r\n";
  22992. std::string second_head = "POST /post HTTP/1.1\r\n"
  22993. "Host: localhost\r\n"
  22994. "Content-Length: " +
  22995. std::to_string(inner.size()) +
  22996. "\r\n"
  22997. "\r\n";
  22998. for (auto target : {"/upload", "/upload?retry"}) {
  22999. smuggled_count = 0;
  23000. std::string request = "POST " + std::string(target) +
  23001. " HTTP/1.1\r\n"
  23002. "Host: localhost\r\n"
  23003. "Content-Length: " +
  23004. std::to_string(second_head.size()) +
  23005. "\r\n"
  23006. "\r\n" +
  23007. std::string(second_head.size(), 'A') + second_head +
  23008. inner;
  23009. std::string response;
  23010. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  23011. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  23012. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  23013. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  23014. EXPECT_EQ(0, smuggled_count.load()) << target;
  23015. }
  23016. }
  23017. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  23018. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  23019. // must be rejected with 400 Bad Request.
  23020. Server svr;
  23021. svr.Post("/test", [&](const Request &, Response &res) {
  23022. res.set_content("ok", "text/plain");
  23023. });
  23024. thread t = thread([&] { svr.listen(HOST, PORT); });
  23025. auto se = detail::scope_exit([&] {
  23026. svr.stop();
  23027. t.join();
  23028. ASSERT_FALSE(svr.is_running());
  23029. });
  23030. svr.wait_until_ready();
  23031. // Exact "chunked"
  23032. {
  23033. auto req = "POST /test HTTP/1.1\r\n"
  23034. "Host: localhost\r\n"
  23035. "Content-Length: 5\r\n"
  23036. "Transfer-Encoding: chunked\r\n"
  23037. "Connection: close\r\n"
  23038. "\r\n"
  23039. "hello";
  23040. std::string response;
  23041. ASSERT_TRUE(send_request(1, req, &response));
  23042. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23043. response.substr(0, response.find("\r\n")));
  23044. }
  23045. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  23046. {
  23047. auto req = "POST /test HTTP/1.1\r\n"
  23048. "Host: localhost\r\n"
  23049. "Content-Length: 5\r\n"
  23050. "Transfer-Encoding: gzip, chunked\r\n"
  23051. "Connection: close\r\n"
  23052. "\r\n"
  23053. "hello";
  23054. std::string response;
  23055. ASSERT_TRUE(send_request(1, req, &response));
  23056. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23057. response.substr(0, response.find("\r\n")));
  23058. }
  23059. }
  23060. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  23061. Server svr;
  23062. svr.Post("/test", [&](const Request &, Response &res) {
  23063. res.set_content("ok", "text/plain");
  23064. });
  23065. thread t = thread([&] { svr.listen(HOST, PORT); });
  23066. auto se = detail::scope_exit([&] {
  23067. svr.stop();
  23068. t.join();
  23069. ASSERT_FALSE(svr.is_running());
  23070. });
  23071. svr.wait_until_ready();
  23072. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  23073. // length cannot be determined, so the server must answer 400 and close
  23074. // rather than treat the request as bodyless and leave the body in the
  23075. // socket for the next request to pick up.
  23076. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  23077. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  23078. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  23079. std::string response;
  23080. ASSERT_TRUE(send_request(1, req, &response));
  23081. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23082. response.substr(0, response.find("\r\n")))
  23083. << transfer_encoding;
  23084. }
  23085. // RFC 9110 5.3: the codings may also be split across several
  23086. // Transfer-Encoding lines, which combine in the order they were received.
  23087. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  23088. // just like the single-line "chunked, gzip" above.
  23089. {
  23090. auto req = "POST /test HTTP/1.1\r\n"
  23091. "Host: localhost\r\n"
  23092. "Transfer-Encoding: chunked\r\n"
  23093. "Transfer-Encoding: gzip\r\n"
  23094. "\r\n"
  23095. "0\r\n\r\n";
  23096. std::string response;
  23097. ASSERT_TRUE(send_request(1, req, &response));
  23098. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  23099. response.substr(0, response.find("\r\n")));
  23100. }
  23101. // A sequence ending in chunked stays valid.
  23102. auto req = "POST /test HTTP/1.1\r\n"
  23103. "Host: localhost\r\n"
  23104. "Transfer-Encoding: gzip, chunked\r\n"
  23105. "Connection: close\r\n"
  23106. "\r\n"
  23107. "0\r\n\r\n";
  23108. std::string response;
  23109. ASSERT_TRUE(send_request(1, req, &response));
  23110. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  23111. // ...including when it is spread over several lines.
  23112. auto split_req = "POST /test HTTP/1.1\r\n"
  23113. "Host: localhost\r\n"
  23114. "Transfer-Encoding: gzip\r\n"
  23115. "Transfer-Encoding: chunked\r\n"
  23116. "Connection: close\r\n"
  23117. "\r\n"
  23118. "0\r\n\r\n";
  23119. std::string split_response;
  23120. ASSERT_TRUE(send_request(1, split_req, &split_response));
  23121. EXPECT_EQ("HTTP/1.1 200 OK",
  23122. split_response.substr(0, split_response.find("\r\n")));
  23123. }
  23124. // Regression for issue #2450: a DELETE without Content-Length on a
  23125. // keep-alive connection must not let the post-response drain consume the
  23126. // next request's bytes.
  23127. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  23128. Server svr;
  23129. std::atomic<int> delete_count(0);
  23130. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  23131. delete_count++;
  23132. res.status = StatusCode::NoContent_204;
  23133. });
  23134. auto port = svr.bind_to_any_port(HOST);
  23135. thread t = thread([&] { svr.listen_after_bind(); });
  23136. auto se = detail::scope_exit([&] {
  23137. svr.stop();
  23138. t.join();
  23139. });
  23140. svr.wait_until_ready();
  23141. auto error = Error::Success;
  23142. auto sock = detail::create_client_socket(
  23143. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23144. /*connection_timeout_sec=*/2, 0,
  23145. /*read_timeout_sec=*/2, 0,
  23146. /*write_timeout_sec=*/2, 0, std::string(), error);
  23147. ASSERT_NE(INVALID_SOCKET, sock);
  23148. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23149. auto send_request_and_read_response = [&](const std::string &req,
  23150. std::string &out) -> bool {
  23151. auto sent = send(sock, req.data(), req.size(), 0);
  23152. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  23153. char buf[4096];
  23154. for (;;) {
  23155. auto n = recv(sock, buf, sizeof(buf), 0);
  23156. if (n <= 0) { return !out.empty(); }
  23157. out.append(buf, static_cast<size_t>(n));
  23158. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  23159. }
  23160. };
  23161. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  23162. "Host: localhost\r\n"
  23163. "\r\n";
  23164. std::string resp1;
  23165. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  23166. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  23167. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  23168. "Host: localhost\r\n"
  23169. "Connection: close\r\n"
  23170. "\r\n";
  23171. std::string resp2;
  23172. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  23173. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  23174. EXPECT_EQ(2, delete_count.load());
  23175. }
  23176. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  23177. Server svr;
  23178. svr.Post("/ingest", [&](const Request &, Response &res,
  23179. const ContentReader &content_reader) {
  23180. auto consumed = content_reader([](const char *, size_t) { return false; });
  23181. EXPECT_FALSE(consumed);
  23182. res.status = StatusCode::Conflict_409;
  23183. res.set_header("Connection", "close");
  23184. });
  23185. auto port = svr.bind_to_any_port(HOST);
  23186. thread t = thread([&] { svr.listen_after_bind(); });
  23187. auto se = detail::scope_exit([&] {
  23188. svr.stop();
  23189. t.join();
  23190. });
  23191. svr.wait_until_ready();
  23192. auto error = Error::Success;
  23193. auto sock = detail::create_client_socket(
  23194. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  23195. /*connection_timeout_sec=*/2, 0,
  23196. /*read_timeout_sec=*/1, 0,
  23197. /*write_timeout_sec=*/2, 0, std::string(), error);
  23198. ASSERT_NE(INVALID_SOCKET, sock);
  23199. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  23200. std::string request = "POST /ingest HTTP/1.1\r\n"
  23201. "Host: localhost\r\n"
  23202. "Transfer-Encoding: chunked\r\n"
  23203. "\r\n"
  23204. "4\r\n"
  23205. "data\r\n";
  23206. auto sent = send(sock, request.data(), request.size(), 0);
  23207. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  23208. std::string response;
  23209. ssize_t received = 0;
  23210. do {
  23211. char buf[4096];
  23212. received = recv(sock, buf, sizeof(buf), 0);
  23213. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  23214. } while (received > 0);
  23215. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  23216. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  23217. EXPECT_EQ(0, received);
  23218. }
  23219. namespace no_proxy_test {
  23220. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  23221. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  23222. // calling listen().
  23223. class ScopedServer {
  23224. public:
  23225. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  23226. ~ScopedServer() {
  23227. svr_.stop();
  23228. if (th_.joinable()) { th_.join(); }
  23229. }
  23230. Server &svr() { return svr_; }
  23231. int port() const { return port_; }
  23232. void listen() {
  23233. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23234. svr_.wait_until_ready();
  23235. }
  23236. private:
  23237. Server svr_;
  23238. std::thread th_;
  23239. int port_ = 0;
  23240. };
  23241. class ProxyAndTargetServers {
  23242. public:
  23243. ProxyAndTargetServers() {
  23244. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  23245. proxy_hits_++;
  23246. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23247. res.set_content("via-proxy", "text/plain");
  23248. });
  23249. target_.Get(".*", [this](const Request &req, Response &res) {
  23250. target_hits_++;
  23251. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  23252. res.set_content("direct", "text/plain");
  23253. });
  23254. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  23255. target_port_ = target_.bind_to_any_port("127.0.0.1");
  23256. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  23257. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  23258. proxy_mock_.wait_until_ready();
  23259. target_.wait_until_ready();
  23260. }
  23261. ~ProxyAndTargetServers() {
  23262. proxy_mock_.stop();
  23263. target_.stop();
  23264. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  23265. if (target_thread_.joinable()) { target_thread_.join(); }
  23266. }
  23267. Server &proxy_mock() { return proxy_mock_; }
  23268. Server &target() { return target_; }
  23269. int proxy_port() const { return proxy_port_; }
  23270. int target_port() const { return target_port_; }
  23271. int proxy_hits() const { return proxy_hits_.load(); }
  23272. int target_hits() const { return target_hits_.load(); }
  23273. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  23274. void reset_counters() {
  23275. proxy_hits_ = 0;
  23276. target_hits_ = 0;
  23277. last_had_proxy_authz_ = false;
  23278. }
  23279. private:
  23280. Server proxy_mock_;
  23281. Server target_;
  23282. std::thread proxy_thread_;
  23283. std::thread target_thread_;
  23284. int proxy_port_ = 0;
  23285. int target_port_ = 0;
  23286. std::atomic<int> proxy_hits_{0};
  23287. std::atomic<int> target_hits_{0};
  23288. std::atomic<bool> last_had_proxy_authz_{false};
  23289. };
  23290. inline std::unique_ptr<Client> make_client(const std::string &host,
  23291. ProxyAndTargetServers &s) {
  23292. auto cli = detail::make_unique<Client>(host, s.target_port());
  23293. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  23294. cli->set_proxy("127.0.0.1", s.proxy_port());
  23295. return cli;
  23296. }
  23297. } // namespace no_proxy_test
  23298. using no_proxy_test::make_client;
  23299. using no_proxy_test::ProxyAndTargetServers;
  23300. TEST(NoProxyTest, ExactHostnameBypasses) {
  23301. ProxyAndTargetServers s;
  23302. auto cli = make_client("example.com", s);
  23303. cli->set_no_proxy({"example.com"});
  23304. auto res = cli->Get("/");
  23305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23306. EXPECT_EQ(0, s.proxy_hits());
  23307. EXPECT_EQ(1, s.target_hits());
  23308. }
  23309. TEST(NoProxyTest, SubdomainBypasses) {
  23310. ProxyAndTargetServers s;
  23311. auto cli = make_client("foo.example.com", s);
  23312. cli->set_no_proxy({"example.com"});
  23313. auto res = cli->Get("/");
  23314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23315. EXPECT_EQ(0, s.proxy_hits());
  23316. EXPECT_EQ(1, s.target_hits());
  23317. }
  23318. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  23319. // Regression guard: "evilexample.com" must not be considered a subdomain
  23320. // of "example.com". Without the dot-boundary rule, a naive endsWith
  23321. // check would let traffic bypass the proxy and leak credentials direct
  23322. // to the attacker host.
  23323. ProxyAndTargetServers s;
  23324. auto cli = make_client("evilexample.com", s);
  23325. cli->set_no_proxy({"example.com"});
  23326. auto res = cli->Get("/");
  23327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23328. EXPECT_GE(s.proxy_hits(), 1);
  23329. EXPECT_EQ(0, s.target_hits());
  23330. }
  23331. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  23332. ProxyAndTargetServers s;
  23333. auto cli = make_client("example.com.evil.com", s);
  23334. cli->set_no_proxy({"example.com"});
  23335. auto res = cli->Get("/");
  23336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23337. EXPECT_GE(s.proxy_hits(), 1);
  23338. EXPECT_EQ(0, s.target_hits());
  23339. }
  23340. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  23341. ProxyAndTargetServers s;
  23342. auto cli = make_client("example.com", s);
  23343. cli->set_no_proxy({".example.com"});
  23344. auto res = cli->Get("/");
  23345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23346. EXPECT_EQ(0, s.proxy_hits());
  23347. EXPECT_EQ(1, s.target_hits());
  23348. }
  23349. TEST(NoProxyTest, CaseInsensitiveHostname) {
  23350. ProxyAndTargetServers s;
  23351. auto cli = make_client("Example.COM", s);
  23352. cli->set_no_proxy({"EXAMPLE.com"});
  23353. auto res = cli->Get("/");
  23354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23355. EXPECT_EQ(0, s.proxy_hits());
  23356. EXPECT_EQ(1, s.target_hits());
  23357. }
  23358. TEST(NoProxyTest, TrailingDotIsNormalized) {
  23359. ProxyAndTargetServers s;
  23360. auto cli = make_client("example.com.", s);
  23361. cli->set_no_proxy({"example.com"});
  23362. auto res = cli->Get("/");
  23363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23364. EXPECT_EQ(0, s.proxy_hits());
  23365. EXPECT_EQ(1, s.target_hits());
  23366. }
  23367. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  23368. // Trailing dots must be normalized on BOTH sides — host and entry.
  23369. // An implementation that only strips the host-side trailing dot would
  23370. // fail to match host "example.com" against entry "example.com." because
  23371. // a literal substring search would compare 11 chars against 12.
  23372. ProxyAndTargetServers s;
  23373. auto cli = make_client("example.com", s);
  23374. cli->set_no_proxy({"example.com."});
  23375. auto res = cli->Get("/");
  23376. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23377. EXPECT_EQ(0, s.proxy_hits());
  23378. EXPECT_EQ(1, s.target_hits());
  23379. }
  23380. TEST(NoProxyTest, WildcardBypassesEverything) {
  23381. ProxyAndTargetServers s;
  23382. auto cli = make_client("anything.invalid.test", s);
  23383. cli->set_no_proxy({"*"});
  23384. auto res = cli->Get("/");
  23385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23386. EXPECT_EQ(0, s.proxy_hits());
  23387. EXPECT_EQ(1, s.target_hits());
  23388. }
  23389. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  23390. ProxyAndTargetServers s;
  23391. Client cli("127.0.0.1", s.target_port());
  23392. cli.set_proxy("127.0.0.1", s.proxy_port());
  23393. cli.set_no_proxy({"127.0.0.1"});
  23394. auto res = cli.Get("/");
  23395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23396. EXPECT_EQ(0, s.proxy_hits());
  23397. EXPECT_EQ(1, s.target_hits());
  23398. }
  23399. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  23400. ProxyAndTargetServers s;
  23401. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  23402. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  23403. cli.set_proxy("127.0.0.1", s.proxy_port());
  23404. cli.set_no_proxy({"::1"});
  23405. auto res = cli.Get("/");
  23406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23407. EXPECT_EQ(0, s.proxy_hits());
  23408. EXPECT_EQ(1, s.target_hits());
  23409. }
  23410. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  23411. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  23412. // must still be recognized as IPv6 for CIDR matching. Implementations
  23413. // that detect IPv6 only when the host begins with '[' would parse the
  23414. // host as a hostname and miss the match.
  23415. ProxyAndTargetServers s;
  23416. Client cli("fe80::1", s.target_port());
  23417. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23418. cli.set_proxy("127.0.0.1", s.proxy_port());
  23419. cli.set_no_proxy({"fe80::/10"});
  23420. auto res = cli.Get("/");
  23421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23422. EXPECT_EQ(0, s.proxy_hits());
  23423. EXPECT_EQ(1, s.target_hits());
  23424. }
  23425. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  23426. ProxyAndTargetServers s;
  23427. Client cli("::1", s.target_port());
  23428. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  23429. cli.set_proxy("127.0.0.1", s.proxy_port());
  23430. cli.set_no_proxy({"[::1]"});
  23431. auto res = cli.Get("/");
  23432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23433. EXPECT_EQ(0, s.proxy_hits());
  23434. EXPECT_EQ(1, s.target_hits());
  23435. }
  23436. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  23437. ProxyAndTargetServers s;
  23438. Client cli("fe80::1", s.target_port());
  23439. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  23440. cli.set_proxy("127.0.0.1", s.proxy_port());
  23441. cli.set_no_proxy({"[fe80::]/10"});
  23442. auto res = cli.Get("/");
  23443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23444. EXPECT_EQ(0, s.proxy_hits());
  23445. EXPECT_EQ(1, s.target_hits());
  23446. }
  23447. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  23448. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  23449. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  23450. // tricks via address-family conversion.
  23451. ProxyAndTargetServers s;
  23452. Client cli("::ffff:127.0.0.1", s.target_port());
  23453. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  23454. cli.set_proxy("127.0.0.1", s.proxy_port());
  23455. cli.set_no_proxy({"127.0.0.1"});
  23456. auto res = cli.Get("/");
  23457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23458. EXPECT_GE(s.proxy_hits(), 1);
  23459. EXPECT_EQ(0, s.target_hits());
  23460. }
  23461. TEST(NoProxyTest, IPv4CidrMatch) {
  23462. ProxyAndTargetServers s;
  23463. Client cli("127.0.0.1", s.target_port());
  23464. cli.set_proxy("127.0.0.1", s.proxy_port());
  23465. cli.set_no_proxy({"127.0.0.0/8"});
  23466. auto res = cli.Get("/");
  23467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23468. EXPECT_EQ(0, s.proxy_hits());
  23469. EXPECT_EQ(1, s.target_hits());
  23470. }
  23471. TEST(NoProxyTest, IPv4CidrNonMatch) {
  23472. ProxyAndTargetServers s;
  23473. Client cli("127.0.0.1", s.target_port());
  23474. cli.set_proxy("127.0.0.1", s.proxy_port());
  23475. cli.set_no_proxy({"10.0.0.0/8"});
  23476. auto res = cli.Get("/");
  23477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23478. EXPECT_GE(s.proxy_hits(), 1);
  23479. EXPECT_EQ(0, s.target_hits());
  23480. }
  23481. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  23482. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  23483. // IPv4 target matches.
  23484. ProxyAndTargetServers s;
  23485. Client cli("127.0.0.1", s.target_port());
  23486. cli.set_proxy("127.0.0.1", s.proxy_port());
  23487. cli.set_no_proxy({"0.0.0.0/0"});
  23488. auto res = cli.Get("/");
  23489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23490. EXPECT_EQ(0, s.proxy_hits());
  23491. EXPECT_EQ(1, s.target_hits());
  23492. }
  23493. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  23494. ProxyAndTargetServers s;
  23495. Client cli("127.0.0.1", s.target_port());
  23496. cli.set_proxy("127.0.0.1", s.proxy_port());
  23497. cli.set_no_proxy({"127.0.0.1"});
  23498. auto res = cli.Get("/");
  23499. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23500. EXPECT_EQ(0, s.proxy_hits());
  23501. EXPECT_EQ(1, s.target_hits());
  23502. }
  23503. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  23504. ProxyAndTargetServers s;
  23505. Client cli("127.0.0.1", s.target_port());
  23506. cli.set_proxy("127.0.0.1", s.proxy_port());
  23507. cli.set_no_proxy({"127.0.0.0/33"});
  23508. auto res = cli.Get("/");
  23509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23510. EXPECT_GE(s.proxy_hits(), 1);
  23511. EXPECT_EQ(0, s.target_hits());
  23512. }
  23513. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  23514. // Empty prefix after the slash must be rejected, not silently treated as /32.
  23515. ProxyAndTargetServers s;
  23516. Client cli("127.0.0.1", s.target_port());
  23517. cli.set_proxy("127.0.0.1", s.proxy_port());
  23518. cli.set_no_proxy({"127.0.0.1/"});
  23519. auto res = cli.Get("/");
  23520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23521. EXPECT_GE(s.proxy_hits(), 1);
  23522. EXPECT_EQ(0, s.target_hits());
  23523. }
  23524. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  23525. ProxyAndTargetServers s;
  23526. auto cli = make_client("internal.corp", s);
  23527. cli->set_proxy_basic_auth("u", "p");
  23528. cli->set_no_proxy({"internal.corp"});
  23529. auto res = cli->Get("/");
  23530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23531. EXPECT_EQ(1, s.target_hits());
  23532. EXPECT_EQ(0, s.proxy_hits());
  23533. EXPECT_FALSE(s.last_had_proxy_authz())
  23534. << "Proxy-Authorization must not be sent direct to the target";
  23535. }
  23536. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  23537. ProxyAndTargetServers s;
  23538. auto cli = make_client("public.example", s);
  23539. cli->set_proxy_basic_auth("u", "p");
  23540. cli->set_no_proxy({"internal.corp"}); // does not match
  23541. auto res = cli->Get("/");
  23542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23543. EXPECT_GE(s.proxy_hits(), 1);
  23544. EXPECT_TRUE(s.last_had_proxy_authz());
  23545. }
  23546. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  23547. std::atomic<int> hits{0};
  23548. std::atomic<int> hits_with_authz{0};
  23549. no_proxy_test::ScopedServer proxy_mock;
  23550. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23551. hits++;
  23552. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  23553. if (req.target.find("/redir") != std::string::npos) {
  23554. res.set_redirect("http://other.example/landed");
  23555. } else {
  23556. res.set_content("via-proxy", "text/plain");
  23557. }
  23558. });
  23559. proxy_mock.listen();
  23560. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  23561. hits = 0;
  23562. hits_with_authz = 0;
  23563. Client cli("public.example", 80);
  23564. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23565. cli.set_proxy_basic_auth(c.first, c.second);
  23566. cli.set_follow_location(true);
  23567. // The redirect to another host goes through the proxy as well
  23568. auto res = cli.Get("/redir");
  23569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23570. EXPECT_EQ(2, hits.load());
  23571. EXPECT_EQ(2, hits_with_authz.load());
  23572. }
  23573. }
  23574. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  23575. ProxyAndTargetServers s;
  23576. auto cli = make_client("anything.test", s);
  23577. auto res = cli->Get("/");
  23578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23579. EXPECT_GE(s.proxy_hits(), 1);
  23580. EXPECT_EQ(0, s.target_hits());
  23581. }
  23582. TEST(NoProxyTest, PortSpecificEntryRejected) {
  23583. ProxyAndTargetServers s;
  23584. auto cli = make_client("example.com", s);
  23585. cli->set_no_proxy({"example.com:8080"});
  23586. auto res = cli->Get("/");
  23587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23588. EXPECT_GE(s.proxy_hits(), 1);
  23589. EXPECT_EQ(0, s.target_hits());
  23590. }
  23591. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  23592. ProxyAndTargetServers s;
  23593. auto cli = make_client("anything.test", s);
  23594. cli->set_no_proxy({"", " ", "\t"});
  23595. auto res = cli->Get("/");
  23596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23597. EXPECT_GE(s.proxy_hits(), 1);
  23598. EXPECT_EQ(0, s.target_hits());
  23599. }
  23600. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  23601. // An entry with leading/trailing whitespace must still match — env-style
  23602. // values are commonly pasted with stray spaces and an implementation
  23603. // that feeds the raw token directly to inet_pton would fail to match
  23604. // valid CIDRs because of the spaces.
  23605. ProxyAndTargetServers s;
  23606. Client cli("127.0.0.1", s.target_port());
  23607. cli.set_proxy("127.0.0.1", s.proxy_port());
  23608. cli.set_no_proxy({" 127.0.0.0/8 "});
  23609. auto res = cli.Get("/");
  23610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23611. EXPECT_EQ(0, s.proxy_hits());
  23612. EXPECT_EQ(1, s.target_hits());
  23613. }
  23614. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  23615. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  23616. // go direct and must NOT carry Proxy-Authorization.
  23617. std::atomic<int> proxy_hits{0};
  23618. std::atomic<int> target_hits{0};
  23619. std::atomic<bool> target_saw_authz{false};
  23620. no_proxy_test::ScopedServer proxy_mock, target;
  23621. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23622. proxy_hits++;
  23623. res.status = 302;
  23624. res.set_header("Location", "http://127.0.0.1:" +
  23625. std::to_string(target.port()) + "/landed");
  23626. });
  23627. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23628. target_hits++;
  23629. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  23630. res.set_content("direct", "text/plain");
  23631. });
  23632. proxy_mock.listen();
  23633. target.listen();
  23634. Client cli("public.example", target.port());
  23635. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23636. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23637. cli.set_proxy_basic_auth("u", "p");
  23638. cli.set_no_proxy({"127.0.0.1"});
  23639. cli.set_follow_location(true);
  23640. auto res = cli.Get("/redir");
  23641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23642. EXPECT_GE(proxy_hits.load(), 1);
  23643. EXPECT_GE(target_hits.load(), 1);
  23644. EXPECT_FALSE(target_saw_authz.load());
  23645. }
  23646. #ifdef CPPHTTPLIB_SSL_ENABLED
  23647. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  23648. // Direct origin replying 407 must not trigger the digest retry; otherwise
  23649. // proxy creds would be sent to the (possibly hostile) origin.
  23650. std::atomic<int> target_hits{0};
  23651. std::atomic<bool> target_saw_proxy_authz{false};
  23652. no_proxy_test::ScopedServer target;
  23653. target.svr().Get(".*", [&](const Request &req, Response &res) {
  23654. target_hits++;
  23655. if (req.has_header("Proxy-Authorization")) {
  23656. target_saw_proxy_authz = true;
  23657. }
  23658. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23659. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  23660. "nonce=\"abc\", algorithm=MD5");
  23661. });
  23662. target.listen();
  23663. // The proxy address is set to the target's port: the bypass MUST kick in;
  23664. // if it doesn't, the test still routes "via proxy" to the same server and
  23665. // the Proxy-Authorization assertion below catches the leak.
  23666. Client cli("evil.example", target.port());
  23667. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  23668. cli.set_proxy("127.0.0.1", target.port());
  23669. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23670. cli.set_no_proxy({"evil.example"});
  23671. auto res = cli.Get("/x");
  23672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23673. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23674. EXPECT_EQ(1, target_hits.load());
  23675. EXPECT_FALSE(target_saw_proxy_authz.load());
  23676. }
  23677. #endif
  23678. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  23679. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  23680. std::atomic<int> proxy_hits{0};
  23681. std::atomic<int> bypass_hits{0};
  23682. std::atomic<bool> proxy_saw_c_url{false};
  23683. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  23684. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  23685. proxy_hits++;
  23686. if (req.path.find("/start") != std::string::npos) {
  23687. res.status = 302;
  23688. res.set_header("Location", "http://127.0.0.1:" +
  23689. std::to_string(bypass_server.port()) +
  23690. "/middle");
  23691. return;
  23692. }
  23693. if (req.path.find("/end") != std::string::npos) {
  23694. proxy_saw_c_url = true;
  23695. res.set_content("c-via-proxy", "text/plain");
  23696. return;
  23697. }
  23698. res.set_content("unexpected", "text/plain");
  23699. });
  23700. // public.example's "advertised" port is arbitrary (the request never lands
  23701. // there — it goes through the proxy), but use a dynamic value to stay
  23702. // friendly with sharded parallel runs.
  23703. int public_port = bypass_server.port();
  23704. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  23705. bypass_hits++;
  23706. res.status = 302;
  23707. res.set_header("Location", "http://public.example:" +
  23708. std::to_string(public_port) + "/end");
  23709. });
  23710. proxy_mock.listen();
  23711. bypass_server.listen();
  23712. Client cli("public.example", public_port);
  23713. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23714. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23715. cli.set_no_proxy({"127.0.0.1"});
  23716. cli.set_follow_location(true);
  23717. auto res = cli.Get("/start");
  23718. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23719. EXPECT_EQ(StatusCode::OK_200, res->status);
  23720. EXPECT_EQ("c-via-proxy", res->body);
  23721. EXPECT_GE(proxy_hits.load(), 2);
  23722. EXPECT_GE(bypass_hits.load(), 1);
  23723. EXPECT_TRUE(proxy_saw_c_url.load());
  23724. }
  23725. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  23726. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  23727. // request reconnects to the correct endpoint.
  23728. std::atomic<int> proxy_hits{0};
  23729. std::atomic<int> target_hits{0};
  23730. no_proxy_test::ScopedServer proxy_mock, target;
  23731. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  23732. proxy_hits++;
  23733. res.set_content("via-proxy", "text/plain");
  23734. });
  23735. target.svr().Get(".*", [&](const Request &, Response &res) {
  23736. target_hits++;
  23737. res.set_content("direct", "text/plain");
  23738. });
  23739. proxy_mock.listen();
  23740. target.listen();
  23741. Client cli("public.example", target.port());
  23742. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  23743. cli.set_proxy("127.0.0.1", proxy_mock.port());
  23744. cli.set_keep_alive(true);
  23745. auto res1 = cli.Get("/a");
  23746. ASSERT_TRUE(res1);
  23747. EXPECT_EQ("via-proxy", res1->body);
  23748. EXPECT_EQ(1, proxy_hits.load());
  23749. EXPECT_EQ(0, target_hits.load());
  23750. cli.set_no_proxy({"public.example"});
  23751. auto res2 = cli.Get("/b");
  23752. ASSERT_TRUE(res2);
  23753. EXPECT_EQ("direct", res2->body);
  23754. EXPECT_EQ(1, proxy_hits.load());
  23755. EXPECT_EQ(1, target_hits.load());
  23756. }
  23757. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  23758. namespace proxy_tunnel_test {
  23759. // SSLServer counterpart to no_proxy_test::ScopedServer.
  23760. class ScopedSSLServer {
  23761. public:
  23762. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  23763. port_ = svr_.bind_to_any_port("127.0.0.1");
  23764. }
  23765. ~ScopedSSLServer() {
  23766. svr_.stop();
  23767. if (th_.joinable()) { th_.join(); }
  23768. }
  23769. SSLServer &svr() { return svr_; }
  23770. int port() const { return port_; }
  23771. void listen() {
  23772. th_ = std::thread([this] { svr_.listen_after_bind(); });
  23773. svr_.wait_until_ready();
  23774. }
  23775. private:
  23776. SSLServer svr_;
  23777. std::thread th_;
  23778. int port_ = 0;
  23779. };
  23780. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  23781. class ScopedConnectProxy {
  23782. public:
  23783. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  23784. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  23785. if (listen_fd_ < 0) { return; }
  23786. int yes = 1;
  23787. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  23788. sockaddr_in a{};
  23789. a.sin_family = AF_INET;
  23790. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23791. a.sin_port = 0;
  23792. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  23793. return;
  23794. }
  23795. socklen_t alen = sizeof(a);
  23796. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  23797. 0) {
  23798. return;
  23799. }
  23800. port_ = ntohs(a.sin_port);
  23801. if (::listen(listen_fd_, 1) != 0) { return; }
  23802. th_ = std::thread([this] { run(); });
  23803. }
  23804. ~ScopedConnectProxy() {
  23805. stop_ = true;
  23806. if (listen_fd_ >= 0) {
  23807. ::shutdown(listen_fd_, SHUT_RDWR);
  23808. ::close(listen_fd_);
  23809. }
  23810. if (th_.joinable()) { th_.join(); }
  23811. }
  23812. int port() const { return port_; }
  23813. int connect_hits() const { return connect_hits_.load(); }
  23814. // Head of the last CONNECT request, as the proxy saw it on the wire.
  23815. std::string connect_request() const {
  23816. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23817. return connect_request_;
  23818. }
  23819. private:
  23820. void run() {
  23821. while (!stop_.load()) {
  23822. fd_set rfds;
  23823. FD_ZERO(&rfds);
  23824. FD_SET(listen_fd_, &rfds);
  23825. timeval tv{0, 100 * 1000};
  23826. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  23827. if (sel <= 0) { continue; }
  23828. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  23829. if (client_fd < 0) { continue; }
  23830. std::string req;
  23831. char buf[2048];
  23832. while (req.find("\r\n\r\n") == std::string::npos) {
  23833. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  23834. if (n <= 0) { break; }
  23835. req.append(buf, static_cast<size_t>(n));
  23836. }
  23837. if (req.compare(0, 7, "CONNECT") != 0) {
  23838. ::close(client_fd);
  23839. continue;
  23840. }
  23841. connect_hits_++;
  23842. {
  23843. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  23844. connect_request_ = req;
  23845. }
  23846. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  23847. ::send(client_fd, ok, std::strlen(ok), 0);
  23848. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  23849. sockaddr_in o{};
  23850. o.sin_family = AF_INET;
  23851. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  23852. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  23853. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  23854. 0) {
  23855. ::close(client_fd);
  23856. ::close(origin_fd);
  23857. continue;
  23858. }
  23859. auto forward = [](int from, int to) {
  23860. char b[8192];
  23861. for (;;) {
  23862. ssize_t n = ::recv(from, b, sizeof(b), 0);
  23863. if (n <= 0) { break; }
  23864. ssize_t off = 0;
  23865. while (off < n) {
  23866. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  23867. if (s <= 0) {
  23868. off = n;
  23869. break;
  23870. }
  23871. off += s;
  23872. }
  23873. }
  23874. ::shutdown(to, SHUT_WR);
  23875. };
  23876. std::thread t1([&] { forward(client_fd, origin_fd); });
  23877. std::thread t2([&] { forward(origin_fd, client_fd); });
  23878. t1.join();
  23879. t2.join();
  23880. ::close(client_fd);
  23881. ::close(origin_fd);
  23882. }
  23883. }
  23884. int forward_port_ = -1;
  23885. int listen_fd_ = -1;
  23886. int port_ = 0;
  23887. std::thread th_;
  23888. std::atomic<bool> stop_{false};
  23889. std::atomic<int> connect_hits_{0};
  23890. mutable std::mutex connect_request_mutex_;
  23891. std::string connect_request_;
  23892. };
  23893. // Sends one request through the CONNECT proxy to the TLS origin with a
  23894. // credential configured for each hop, and checks that each credential reaches
  23895. // only the hop it was configured for: the proxy's on the CONNECT request, the
  23896. // origin's (every header in origin_headers) on the tunnelled request.
  23897. void CredentialsStayWithTheirHop(
  23898. const std::function<void(SSLClient &)> &set_credentials,
  23899. const std::string &scheme,
  23900. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  23901. std::atomic<int> origin_hits{0};
  23902. std::atomic<bool> origin_saw_proxy_authz{false};
  23903. std::atomic<bool> origin_saw_headers{false};
  23904. ScopedSSLServer origin;
  23905. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23906. origin_hits++;
  23907. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  23908. origin_saw_headers =
  23909. std::all_of(origin_headers.begin(), origin_headers.end(),
  23910. [&](const std::string &h) { return req.has_header(h); });
  23911. res.set_content("ok", "text/plain");
  23912. });
  23913. origin.listen();
  23914. ScopedConnectProxy proxy(origin.port());
  23915. ASSERT_NE(0, proxy.port());
  23916. // Pinned to 127.0.0.1 for the same reason as the test below.
  23917. SSLClient cli("127.0.0.1", origin.port());
  23918. cli.enable_server_certificate_verification(false);
  23919. cli.set_proxy("127.0.0.1", proxy.port());
  23920. set_credentials(cli);
  23921. auto res = cli.Get("/x");
  23922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23923. EXPECT_EQ(StatusCode::OK_200, res->status);
  23924. EXPECT_EQ(1, origin_hits.load());
  23925. EXPECT_EQ(1, proxy.connect_hits());
  23926. EXPECT_TRUE(origin_saw_headers.load());
  23927. EXPECT_FALSE(origin_saw_proxy_authz.load())
  23928. << "Proxy-Authorization must not be sent inside the tunnel";
  23929. auto connect_req = proxy.connect_request();
  23930. EXPECT_NE(std::string::npos,
  23931. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  23932. for (const auto &h : origin_headers) {
  23933. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  23934. << h << " must not be sent to the proxy on CONNECT";
  23935. }
  23936. }
  23937. } // namespace proxy_tunnel_test
  23938. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  23939. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23940. [](SSLClient &cli) {
  23941. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23942. cli.set_basic_auth("origin-user", "origin-pass");
  23943. },
  23944. "Basic");
  23945. }
  23946. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  23947. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23948. [](SSLClient &cli) {
  23949. cli.set_proxy_bearer_token_auth("proxy-token");
  23950. cli.set_bearer_token_auth("origin-token");
  23951. },
  23952. "Bearer");
  23953. }
  23954. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  23955. proxy_tunnel_test::CredentialsStayWithTheirHop(
  23956. [](SSLClient &cli) {
  23957. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  23958. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  23959. {"Cookie", "sid=origin-session"},
  23960. {"X-Api-Key", "origin-key"}});
  23961. },
  23962. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  23963. }
  23964. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  23965. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  23966. // retry; otherwise proxy creds would be sent to the origin.
  23967. std::atomic<int> origin_hits{0};
  23968. std::atomic<bool> origin_saw_proxy_authz{false};
  23969. proxy_tunnel_test::ScopedSSLServer origin;
  23970. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  23971. origin_hits++;
  23972. if (req.has_header("Proxy-Authorization")) {
  23973. origin_saw_proxy_authz = true;
  23974. }
  23975. res.status = StatusCode::ProxyAuthenticationRequired_407;
  23976. res.set_header("Proxy-Authenticate",
  23977. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  23978. "algorithm=MD5");
  23979. });
  23980. origin.listen();
  23981. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  23982. ASSERT_NE(0, proxy.port());
  23983. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  23984. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  23985. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  23986. // and answer with its own status, making this test flaky.
  23987. SSLClient cli("127.0.0.1", origin.port());
  23988. cli.enable_server_certificate_verification(false);
  23989. cli.set_proxy("127.0.0.1", proxy.port());
  23990. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  23991. auto res = cli.Get("/x");
  23992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  23993. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  23994. EXPECT_EQ(1, origin_hits.load());
  23995. EXPECT_FALSE(origin_saw_proxy_authz.load());
  23996. EXPECT_EQ(1, proxy.connect_hits());
  23997. }
  23998. #endif